entities listlengths 1 8.61k | max_stars_repo_path stringlengths 7 172 | max_stars_repo_name stringlengths 5 89 | max_stars_count int64 0 82k | content stringlengths 14 1.05M | id stringlengths 2 6 | new_content stringlengths 15 1.05M | modified bool 1 class | references stringlengths 29 1.05M |
|---|---|---|---|---|---|---|---|---|
[
{
"context": "ata = JSON.stringify\n username: userName\n @.userEndpointRequest(data)\n\n ",
"end": 1064,
"score": 0.9986321330070496,
"start": 1056,
"tag": "USERNAME",
"value": "userName"
},
{
"context": "ssName={userNameControlClass} id=\"userNa... | client/app/coffee/components/quiz/initUser.coffee | designeng/dictionary | 0 | define [
"underscore"
"jquery"
"react"
"reactRouter"
"components/ajax/ajaxRequest"
], (_, $, React, Router, AjaxRequest) ->
Route = Router.Route
Link = Router.Link
UserForm = React.createClass
contextTypes:
router: React.PropTypes.func
componentDidMount: ->
$("#userForm").show()
@.formWarning = $("#formWarning")
@.userNameFormGroup = $("#userNameFormGroup")
@.formWarning.hide()
validateForm: ->
userName = $.trim($("#userName").val())
if !userName
@.formWarning.text("User name is required!").show()
@.userNameFormGroup.addClass("has-error")
return false
else
@.formWarning.hide()
@.userNameFormGroup.removeClass("has-error")
return userName
clickHandler: ->
userName = @.validateForm()
if userName
data = JSON.stringify
username: userName
@.userEndpointRequest(data)
onChangeHandler: ->
return true
onSubmit: ->
@.clickHandler()
return false
userEndpointRequest: (data) ->
new AjaxRequest(@.props.endpoint, data, @.props.method, "application/json").always @afterSendRequest
afterSendRequest: (result) ->
if @.isMounted()
this.setState
id: result.id
word: result.word
choises: result.choises
if result? and !result.error
@.context.router.transitionTo(@.props.next)
$("#userForm").hide()
return false
render: ->
formClass = "form-horizontal"
userNameControlClass = "user-name-input col-sm-2 form-control"
controlBtnClass = "btn btn-info user-btn"
inputWrapperClass = "col-sm-10"
formGroupClass = "form-group"
formWarningClass = "bg-danger warning"
return (
<form className={formClass} id="userForm" onSubmit={@.onSubmit}>
<p className={formWarningClass} id="formWarning"></p>
<div className={formGroupClass}>
<div className={inputWrapperClass} id="userNameFormGroup">
<input type="text" className={userNameControlClass} id="userName" name="userName" placeholder="User Name" onChange={@.onChangeHandler}/>
</div>
<div className={inputWrapperClass}>
<button type="button" id="userFormBtn" className={controlBtnClass} onClick={@.clickHandler}>Start quiz</button>
</div>
</div>
</form>
)
InitUser = React.createClass
render: ->
panelClass = "panel panel-default"
panelBodyClass = "panel-body"
panelTitleClass = "panel-title"
panelHeadingClass = "panel-heading"
return (
<div className={panelClass}>
<div className={panelHeadingClass}>
<h3 className={panelTitleClass}>Dictionary Quiz</h3>
</div>
<div className={panelBodyClass}>
<UserForm endpoint="../api/web/v1/sessions" method="POST" next="questions"/>
</div>
</div>
)
return InitUser | 145141 | define [
"underscore"
"jquery"
"react"
"reactRouter"
"components/ajax/ajaxRequest"
], (_, $, React, Router, AjaxRequest) ->
Route = Router.Route
Link = Router.Link
UserForm = React.createClass
contextTypes:
router: React.PropTypes.func
componentDidMount: ->
$("#userForm").show()
@.formWarning = $("#formWarning")
@.userNameFormGroup = $("#userNameFormGroup")
@.formWarning.hide()
validateForm: ->
userName = $.trim($("#userName").val())
if !userName
@.formWarning.text("User name is required!").show()
@.userNameFormGroup.addClass("has-error")
return false
else
@.formWarning.hide()
@.userNameFormGroup.removeClass("has-error")
return userName
clickHandler: ->
userName = @.validateForm()
if userName
data = JSON.stringify
username: userName
@.userEndpointRequest(data)
onChangeHandler: ->
return true
onSubmit: ->
@.clickHandler()
return false
userEndpointRequest: (data) ->
new AjaxRequest(@.props.endpoint, data, @.props.method, "application/json").always @afterSendRequest
afterSendRequest: (result) ->
if @.isMounted()
this.setState
id: result.id
word: result.word
choises: result.choises
if result? and !result.error
@.context.router.transitionTo(@.props.next)
$("#userForm").hide()
return false
render: ->
formClass = "form-horizontal"
userNameControlClass = "user-name-input col-sm-2 form-control"
controlBtnClass = "btn btn-info user-btn"
inputWrapperClass = "col-sm-10"
formGroupClass = "form-group"
formWarningClass = "bg-danger warning"
return (
<form className={formClass} id="userForm" onSubmit={@.onSubmit}>
<p className={formWarningClass} id="formWarning"></p>
<div className={formGroupClass}>
<div className={inputWrapperClass} id="userNameFormGroup">
<input type="text" className={userNameControlClass} id="userName" name="userName" placeholder="<NAME>" onChange={@.onChangeHandler}/>
</div>
<div className={inputWrapperClass}>
<button type="button" id="userFormBtn" className={controlBtnClass} onClick={@.clickHandler}>Start quiz</button>
</div>
</div>
</form>
)
InitUser = React.createClass
render: ->
panelClass = "panel panel-default"
panelBodyClass = "panel-body"
panelTitleClass = "panel-title"
panelHeadingClass = "panel-heading"
return (
<div className={panelClass}>
<div className={panelHeadingClass}>
<h3 className={panelTitleClass}>Dictionary Quiz</h3>
</div>
<div className={panelBodyClass}>
<UserForm endpoint="../api/web/v1/sessions" method="POST" next="questions"/>
</div>
</div>
)
return InitUser | true | define [
"underscore"
"jquery"
"react"
"reactRouter"
"components/ajax/ajaxRequest"
], (_, $, React, Router, AjaxRequest) ->
Route = Router.Route
Link = Router.Link
UserForm = React.createClass
contextTypes:
router: React.PropTypes.func
componentDidMount: ->
$("#userForm").show()
@.formWarning = $("#formWarning")
@.userNameFormGroup = $("#userNameFormGroup")
@.formWarning.hide()
validateForm: ->
userName = $.trim($("#userName").val())
if !userName
@.formWarning.text("User name is required!").show()
@.userNameFormGroup.addClass("has-error")
return false
else
@.formWarning.hide()
@.userNameFormGroup.removeClass("has-error")
return userName
clickHandler: ->
userName = @.validateForm()
if userName
data = JSON.stringify
username: userName
@.userEndpointRequest(data)
onChangeHandler: ->
return true
onSubmit: ->
@.clickHandler()
return false
userEndpointRequest: (data) ->
new AjaxRequest(@.props.endpoint, data, @.props.method, "application/json").always @afterSendRequest
afterSendRequest: (result) ->
if @.isMounted()
this.setState
id: result.id
word: result.word
choises: result.choises
if result? and !result.error
@.context.router.transitionTo(@.props.next)
$("#userForm").hide()
return false
render: ->
formClass = "form-horizontal"
userNameControlClass = "user-name-input col-sm-2 form-control"
controlBtnClass = "btn btn-info user-btn"
inputWrapperClass = "col-sm-10"
formGroupClass = "form-group"
formWarningClass = "bg-danger warning"
return (
<form className={formClass} id="userForm" onSubmit={@.onSubmit}>
<p className={formWarningClass} id="formWarning"></p>
<div className={formGroupClass}>
<div className={inputWrapperClass} id="userNameFormGroup">
<input type="text" className={userNameControlClass} id="userName" name="userName" placeholder="PI:NAME:<NAME>END_PI" onChange={@.onChangeHandler}/>
</div>
<div className={inputWrapperClass}>
<button type="button" id="userFormBtn" className={controlBtnClass} onClick={@.clickHandler}>Start quiz</button>
</div>
</div>
</form>
)
InitUser = React.createClass
render: ->
panelClass = "panel panel-default"
panelBodyClass = "panel-body"
panelTitleClass = "panel-title"
panelHeadingClass = "panel-heading"
return (
<div className={panelClass}>
<div className={panelHeadingClass}>
<h3 className={panelTitleClass}>Dictionary Quiz</h3>
</div>
<div className={panelBodyClass}>
<UserForm endpoint="../api/web/v1/sessions" method="POST" next="questions"/>
</div>
</div>
)
return InitUser |
[
{
"context": "overview Tests for no-unescaped-entities\n# @author Patrick Hayes\n###\n'use strict'\n\n# -----------------------------",
"end": 76,
"score": 0.9998119473457336,
"start": 63,
"tag": "NAME",
"value": "Patrick Hayes"
}
] | src/tests/rules/no-unescaped-entities.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-unescaped-entities
# @author Patrick Hayes
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-unescaped-entities'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unescaped-entities', rule,
valid: [
code: '''
Hello = createReactClass({
render: ->
return (
<div/>
)
})
'''
,
code: '''
Hello = createReactClass
render: ->
<div>Here is some text!</div>
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>I&rsquove escaped some entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some escaped entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>{">" + "<" + "&" + '"'}</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <>Here is some text!</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>I&rsquove escaped some entities: > < &</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>{">" + "<" + "&" + '"'}</>
})
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return <div>></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some bad entities: ></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>first line is ok
so is second
and here are some bad entities: ></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>'</div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Multiple errors: '>></div>
})
'''
errors: [
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
]
,
code: '''
Hello = createReactClass
render: ->
<div>{"Unbalanced braces"}}</div>
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>{"Unbalanced braces"}}</>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
]
| 194343 | ###*
# @fileoverview Tests for no-unescaped-entities
# @author <NAME>
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-unescaped-entities'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unescaped-entities', rule,
valid: [
code: '''
Hello = createReactClass({
render: ->
return (
<div/>
)
})
'''
,
code: '''
Hello = createReactClass
render: ->
<div>Here is some text!</div>
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>I&rsquove escaped some entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some escaped entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>{">" + "<" + "&" + '"'}</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <>Here is some text!</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>I&rsquove escaped some entities: > < &</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>{">" + "<" + "&" + '"'}</>
})
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return <div>></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some bad entities: ></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>first line is ok
so is second
and here are some bad entities: ></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>'</div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Multiple errors: '>></div>
})
'''
errors: [
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
]
,
code: '''
Hello = createReactClass
render: ->
<div>{"Unbalanced braces"}}</div>
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>{"Unbalanced braces"}}</>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
]
| true | ###*
# @fileoverview Tests for no-unescaped-entities
# @author PI:NAME:<NAME>END_PI
###
'use strict'
# ------------------------------------------------------------------------------
# Requirements
# ------------------------------------------------------------------------------
rule = require '../../rules/no-unescaped-entities'
{RuleTester} = require 'eslint'
path = require 'path'
# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unescaped-entities', rule,
valid: [
code: '''
Hello = createReactClass({
render: ->
return (
<div/>
)
})
'''
,
code: '''
Hello = createReactClass
render: ->
<div>Here is some text!</div>
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>I&rsquove escaped some entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some escaped entities: > < &</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <div>{">" + "<" + "&" + '"'}</div>
})
'''
,
code: '''
Hello = createReactClass({
render: ->
return <>Here is some text!</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>I&rsquove escaped some entities: > < &</>
})
'''
,
# parser: 'babel-eslint'
code: '''
Hello = createReactClass({
render: ->
return <>{">" + "<" + "&" + '"'}</>
})
'''
# parser: 'babel-eslint'
]
invalid: [
code: '''
Hello = createReactClass({
render: ->
return <div>></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>first line is ok
so is second
and here are some bad entities: ></div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>first line is ok
so is second
and here are some bad entities: ></>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>'</div>
})
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <div>Multiple errors: '>></div>
})
'''
errors: [
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
,
message: 'HTML entities must be escaped.'
]
,
code: '''
Hello = createReactClass
render: ->
<div>{"Unbalanced braces"}}</div>
'''
errors: [message: 'HTML entities must be escaped.']
,
code: '''
Hello = createReactClass({
render: ->
return <>{"Unbalanced braces"}}</>
})
'''
# parser: 'babel-eslint'
errors: [message: 'HTML entities must be escaped.']
]
|
[
{
"context": " @favorite_song)\n\n model = new Contact({name: 'Ringo', number: '555-555-5556', favorite_song: 'Yellow ",
"end": 1494,
"score": 0.9997191429138184,
"start": 1489,
"tag": "NAME",
"value": "Ringo"
},
{
"context": "\n\n # get\n assert.equal(view_model._name(), 'R... | test/spec/plugins/formatting.tests.coffee | kmalakoff/knockback | 160 | assert = assert or require?('chai').assert
describe 'formatted-observable @quick @formatting', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Various scenarios', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "Name: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
@name_number = kb.formattedObservable('Name: {0}, #: {1}', @_name, @_number)
@number_name = kb.formattedObservable('#: {1}, Name: {0}', @_name, @_number)
@name_number_name = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}', @_name, @_number)
@name_number_name_song = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}, Song: "{2}"', @_name, @_number, @favorite_song)
model = new Contact({name: 'Ringo', number: '555-555-5556', favorite_song: 'Yellow Submarine'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'Name: Ringo', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: Ringo, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: Ringo', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Ringo, #: 555-555-5556, Name: Ringo', "combined repeat")
# set from the model
model.set({name: 'Starr', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), 'Starr', "Name changed")
assert.equal(view_model.name(), 'Name: Starr', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: Starr, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: Starr', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Starr, #: XXX-XXX-XXXX, Name: Starr', "combined repeat")
# set from the generated attribute
view_model._name('Ringo')
view_model._number('555-555-5556')
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'Name: Ringo', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: Ringo, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: Ringo', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Ringo, #: 555-555-5556, Name: Ringo', "combined repeat")
# set from the view model - simple
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
assert.equal(view_model.name_number(), 'Name: Ringo, #: 9222-222-222', "combined in order")
assert.equal(view_model.number_name(), '#: 9222-222-222, Name: Ringo', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Ringo, #: 9222-222-222, Name: Ringo', "combined repeat")
# set from the view model - in order
view_model.name_number('Name: Starr, #: XXX-XXX-XXXX')
assert.equal(view_model._name(), 'Starr', "Name changed")
assert.equal(view_model.name(), 'Name: Starr', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: Starr, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: Starr', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Starr, #: XXX-XXX-XXXX, Name: Starr', "combined repeat")
# set from the view model - in reverse order
view_model.number_name('#: 555-555-5556, Name: Ringo')
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'Name: Ringo', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: Ringo, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: Ringo', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Ringo, #: 555-555-5556, Name: Ringo', "combined repeat")
# set from the view model - with repeats (it takes the first match if different)
view_model.name_number_name('Name: Starr, #: XXX-XXX-XXXX, Name: Bongo')
assert.equal(view_model._name(), 'Starr', "Name changed")
assert.equal(view_model.name(), 'Name: Starr', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: Starr, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: Starr', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Starr, #: XXX-XXX-XXXX, Name: Starr', "combined repeat")
# add a new parameter
assert.equal(view_model.name_number_name_song(), 'Name: Starr, #: XXX-XXX-XXXX, Name: Starr, Song: "Yellow Submarine"', "works with repeat parameters")
view_model.name_number_name_song('Name: Ringo, #: 555-555-5556, Name: Ringo, Song: "Yellow"')
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'Name: Ringo', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: Ringo, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: Ringo', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: Ringo, #: 555-555-5556, Name: Ringo', "combined repeat")
assert.equal(view_model.favorite_song(), 'Yellow', "combined repeat")
assert.equal(view_model.name_number_name_song(), 'Name: Ringo, #: 555-555-5556, Name: Ringo, Song: "Yellow"', "combined repeat")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Using Coffeescript classes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "First: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
model = new Contact({name: 'Ringo', number: '555-555-5556'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'First: Ringo', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
# set from the view model
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
# set from the model
model.set({name: 'Starr', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), 'Starr', "Name changed")
assert.equal(view_model.name(), 'First: Starr', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
# set from the generated attribute
view_model._name('Ringo')
assert.equal(view_model._name(), 'Ringo', "Interesting name")
assert.equal(view_model.name(), 'First: Ringo', "Interesting name")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. requires', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @first, @last)
model = new kb.Model()
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: , First: ', "full name is good")
model.set({first: 'Ringo', last: 'Starr'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(model.get('first'), 'Ringo', "first name is good")
assert.equal(model.get('last'), 'The Starr', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.formattedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: 'Ringo', last: 'Starr'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: The Starr, First: Ringo', "full name is good")
assert.equal(model.get('first'), 'Ringo', "first name is good")
assert.equal(model.get('last'), 'The Starr', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.observableFormatted', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.observableFormatted('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: 'Ringo', last: 'Starr'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: The Starr, First: Ringo', "full name is good")
assert.equal(model.get('first'), 'Ringo', "first name is good")
assert.equal(model.get('last'), 'The Starr', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| 3563 | assert = assert or require?('chai').assert
describe 'formatted-observable @quick @formatting', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Various scenarios', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "Name: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
@name_number = kb.formattedObservable('Name: {0}, #: {1}', @_name, @_number)
@number_name = kb.formattedObservable('#: {1}, Name: {0}', @_name, @_number)
@name_number_name = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}', @_name, @_number)
@name_number_name_song = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}, Song: "{2}"', @_name, @_number, @favorite_song)
model = new Contact({name: '<NAME>', number: '555-555-5556', favorite_song: 'Yellow Submarine'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'Name: <NAME>', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: 555-555-5556, Name: <NAME>', "combined repeat")
# set from the model
model.set({name: '<NAME>', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), '<NAME>', "Name changed")
assert.equal(view_model.name(), 'Name: <NAME>', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: XXX-XXX-XXXX, Name: <NAME>', "combined repeat")
# set from the generated attribute
view_model._name('<NAME>')
view_model._number('555-555-5556')
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'Name: <NAME>', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: 555-555-5556, Name: <NAME>', "combined repeat")
# set from the view model - simple
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: 9222-222-222', "combined in order")
assert.equal(view_model.number_name(), '#: 9222-222-222, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: 9222-222-222, Name: <NAME>', "combined repeat")
# set from the view model - in order
view_model.name_number('Name: <NAME>, #: XXX-XXX-XXXX')
assert.equal(view_model._name(), '<NAME>', "Name changed")
assert.equal(view_model.name(), 'Name: <NAME>', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: XXX-XXX-XXXX, Name: <NAME>', "combined repeat")
# set from the view model - in reverse order
view_model.number_name('#: 555-555-5556, Name: <NAME>')
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'Name: <NAME>', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: 555-555-5556, Name: <NAME>', "combined repeat")
# set from the view model - with repeats (it takes the first match if different)
view_model.name_number_name('Name: <NAME>, #: XXX-XXX-XXXX, Name: <NAME>')
assert.equal(view_model._name(), '<NAME>', "Name changed")
assert.equal(view_model.name(), 'Name: <NAME>', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: XXX-XXX-XXXX, Name: <NAME>', "combined repeat")
# add a new parameter
assert.equal(view_model.name_number_name_song(), 'Name: <NAME>, #: XXX-XXX-XXXX, Name: <NAME>, Song: "Yellow Submarine"', "works with repeat parameters")
view_model.name_number_name_song('Name: <NAME>, #: 555-555-5556, Name: <NAME>, Song: "Yellow"')
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'Name: <NAME>', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: <NAME>, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: <NAME>', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: <NAME>, #: 555-555-5556, Name: <NAME>', "combined repeat")
assert.equal(view_model.favorite_song(), 'Yellow', "combined repeat")
assert.equal(view_model.name_number_name_song(), 'Name: <NAME>, #: 555-555-5556, Name: <NAME>, Song: "Yellow"', "combined repeat")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Using Coffeescript classes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "First: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
model = new Contact({name: '<NAME>', number: '555-555-5556'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'First: <NAME>', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
# set from the view model
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
# set from the model
model.set({name: '<NAME>', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), '<NAME>', "Name changed")
assert.equal(view_model.name(), 'First: <NAME>', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
# set from the generated attribute
view_model._name('<NAME>')
assert.equal(view_model._name(), '<NAME>', "Interesting name")
assert.equal(view_model.name(), 'First: <NAME>', "Interesting name")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. requires', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @first, @last)
model = new kb.Model()
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: , First: ', "full name is good")
model.set({first: '<NAME>', last: '<NAME>'})
assert.equal(view_model.full_name(), 'Last: <NAME>, First: <NAME>', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: <NAME>, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: <NAME>')
assert.equal(model.get('first'), '<NAME>', "first name is good")
assert.equal(model.get('last'), '<NAME>', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.formattedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: '<NAME>', last: '<NAME>'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: The Starr, First: Ringo', "full name is good")
assert.equal(model.get('first'), 'Ringo', "first name is good")
assert.equal(model.get('last'), '<NAME> Starr', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.observableFormatted', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.observableFormatted('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: '<NAME>', last: '<NAME>'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: <NAME>arr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: <NAME>, First: <NAME>', "full name is good")
assert.equal(model.get('first'), '<NAME>', "first name is good")
assert.equal(model.get('last'), '<NAME>', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
| true | assert = assert or require?('chai').assert
describe 'formatted-observable @quick @formatting', ->
kb = window?.kb; try kb or= require?('knockback') catch; try kb or= require?('../../../knockback')
{_, ko} = kb
it 'TEST DEPENDENCY MISSING', (done) ->
assert.ok(!!ko, 'ko')
assert.ok(!!_, '_')
assert.ok(!!kb.Model, 'kb.Model')
assert.ok(!!kb.Collection, 'kb.Collection')
assert.ok(!!kb, 'kb')
assert.ok(!!kb, 'kb')
done()
Contact = if kb.Parse then kb.Model.extend('Contact', { defaults: {name: '', number: 0, date: new Date()} }) else kb.Model.extend({ defaults: {name: '', number: 0, date: new Date()} })
Contacts = kb.Collection.extend({model: Contact})
it 'Various scenarios', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "Name: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
@name_number = kb.formattedObservable('Name: {0}, #: {1}', @_name, @_number)
@number_name = kb.formattedObservable('#: {1}, Name: {0}', @_name, @_number)
@name_number_name = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}', @_name, @_number)
@name_number_name_song = kb.formattedObservable('Name: {0}, #: {1}, Name: {0}, Song: "{2}"', @_name, @_number, @favorite_song)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556', favorite_song: 'Yellow Submarine'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the generated attribute
view_model._name('PI:NAME:<NAME>END_PI')
view_model._number('555-555-5556')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the view model - simple
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: 9222-222-222', "combined in order")
assert.equal(view_model.number_name(), '#: 9222-222-222, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: 9222-222-222, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the view model - in order
view_model.name_number('Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the view model - in reverse order
view_model.number_name('#: 555-555-5556, Name: PI:NAME:<NAME>END_PI')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# set from the view model - with repeats (it takes the first match if different)
view_model.name_number_name('Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX', "combined in order")
assert.equal(view_model.number_name(), '#: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI', "combined repeat")
# add a new parameter
assert.equal(view_model.name_number_name_song(), 'Name: PI:NAME:<NAME>END_PI, #: XXX-XXX-XXXX, Name: PI:NAME:<NAME>END_PI, Song: "Yellow Submarine"', "works with repeat parameters")
view_model.name_number_name_song('Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI, Song: "Yellow"')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'Name: PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
assert.equal(view_model.name_number(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556', "combined in order")
assert.equal(view_model.number_name(), '#: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined out of order")
assert.equal(view_model.name_number_name(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI', "combined repeat")
assert.equal(view_model.favorite_song(), 'Yellow', "combined repeat")
assert.equal(view_model.name_number_name_song(), 'Name: PI:NAME:<NAME>END_PI, #: 555-555-5556, Name: PI:NAME:<NAME>END_PI, Song: "Yellow"', "combined repeat")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '4. Using Coffeescript classes', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelCustom extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['name', 'number']})
@name = ko.computed(=> return "First: #{@_name()}")
@number = kb.formattedObservable('#: {0}', @_number)
model = new Contact({name: 'PI:NAME:<NAME>END_PI', number: '555-555-5556'})
view_model = new ContactViewModelCustom(model)
# get
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model._number(), '555-555-5556', "Not so interesting number")
assert.equal(view_model.number(), '#: 555-555-5556', "Not so interesting number")
# set from the view model
view_model.number('#: 9222-222-222')
assert.equal(model.get('number'), '9222-222-222', "Number was changed")
assert.equal(view_model._number(), '9222-222-222', "Number was changed")
assert.equal(view_model.number(), '#: 9222-222-222', "Number was changed")
# set from the model
model.set({name: 'PI:NAME:<NAME>END_PI', number: 'XXX-XXX-XXXX'})
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Name changed")
assert.equal(view_model._number(), 'XXX-XXX-XXXX', "Number was changed")
assert.equal(view_model.number(), '#: XXX-XXX-XXXX', "Number was changed")
# set from the generated attribute
view_model._name('PI:NAME:<NAME>END_PI')
assert.equal(view_model._name(), 'PI:NAME:<NAME>END_PI', "Interesting name")
assert.equal(view_model.name(), 'First: PI:NAME:<NAME>END_PI', "Interesting name")
# and cleanup after yourself when you are done.
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it '6. requires', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {requires: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @first, @last)
model = new kb.Model()
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: , First: ', "full name is good")
model.set({first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'})
assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: PI:NAME:<NAME>END_PI', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: PI:NAME:<NAME>END_PI')
assert.equal(model.get('first'), 'PI:NAME:<NAME>END_PI', "first name is good")
assert.equal(model.get('last'), 'PI:NAME:<NAME>END_PI', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.formattedObservable', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.formattedObservable('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: Starr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: The Starr, First: Ringo', "full name is good")
assert.equal(model.get('first'), 'Ringo', "first name is good")
assert.equal(model.get('last'), 'PI:NAME:<NAME>END_PI Starr', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
it 'kb.observableFormatted', (done) ->
kb.statistics = new kb.Statistics() # turn on stats
class ContactViewModelFullName extends kb.ViewModel
constructor: (model) ->
super(model, {internals: ['first', 'last']})
@full_name = kb.observableFormatted('Last: {1}, First: {0}', @_first, @_last)
model = new kb.Model({first: 'PI:NAME:<NAME>END_PI', last: 'PI:NAME:<NAME>END_PI'})
view_model = new ContactViewModelFullName(model)
assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PIarr, First: Ringo', "full name is good")
model.set({first: 'Bongo'})
assert.equal(view_model.full_name(), 'Last: Starr, First: Bongo', "full name is good")
view_model.full_name('Last: The Starr, First: Ringo')
assert.equal(view_model.full_name(), 'Last: PI:NAME:<NAME>END_PI, First: PI:NAME:<NAME>END_PI', "full name is good")
assert.equal(model.get('first'), 'PI:NAME:<NAME>END_PI', "first name is good")
assert.equal(model.get('last'), 'PI:NAME:<NAME>END_PI', "last name is good")
# clean up
kb.release(view_model)
assert.equal(kb.statistics.registeredStatsString('all released'), 'all released', "Cleanup: stats"); kb.statistics = null
done()
|
[
{
"context": "-#{account}-conjur.example.com'\n }\n username = 'the-username'\n token = {\n data: username\n }\n \n describe",
"end": 344,
"score": 0.9995629191398621,
"start": 332,
"tag": "USERNAME",
"value": "the-username"
},
{
"context": "cribe '#authenticate', ->\n ex... | test/user_test.coffee | conjurinc/api-node | 2 | assert = require('assert')
gently = new (require('gently'))
userAPI = require('../lib/conjur/user')
describe 'User', ->
account = 'the-account'
endpoints = {
authn: (account)->
'http://authn-#{account}-conjur.example.com'
directory: (account)->
'http://core-#{account}-conjur.example.com'
}
username = 'the-username'
token = {
data: username
}
describe '#authenticate', ->
expectedUsername = 'bob'
expectedPassword = 'the-password'
beforeEach ->
authnAPI = require('../lib/conjur/authn')
authenticate = (username, password, cb)->
if username == expectedUsername && password == expectedPassword
cb(null)
else
cb('Authentication failed')
gently.expect authnAPI, 'connect', (theURL)->
assert.equal endpoints.authn(account), theURL
{ authenticate: authenticate }
describe 'with expected username and password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate 'the-password', (err)->
assert !err
done()
describe 'with invalid password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate 'other-password', (err)->
assert.equal err, 'Authentication failed'
done()
describe '#uidnumbers', ->
beforeEach ->
uidnumbers = (logins, cb)->
cb(null, [ 1001, 1002 ])
dirAPI = require('../lib/conjur/directory')
gently.expect dirAPI, 'connect', (theURL, theToken)->
assert.equal endpoints.directory(account), theURL
assert.deepEqual token, theToken
{ uidnumbers: uidnumbers }
it 'succeeds', (done)->
user = userAPI.connect(endpoints).users(account, token).uidnumbers [ 'login-1', 'login-2' ], (err, ids)->
assert !err
assert.deepEqual ids, [ 1001, 1002 ]
done()
| 21138 | assert = require('assert')
gently = new (require('gently'))
userAPI = require('../lib/conjur/user')
describe 'User', ->
account = 'the-account'
endpoints = {
authn: (account)->
'http://authn-#{account}-conjur.example.com'
directory: (account)->
'http://core-#{account}-conjur.example.com'
}
username = 'the-username'
token = {
data: username
}
describe '#authenticate', ->
expectedUsername = 'bob'
expectedPassword = '<PASSWORD>'
beforeEach ->
authnAPI = require('../lib/conjur/authn')
authenticate = (username, password, cb)->
if username == expectedUsername && password == <PASSWORD>
cb(null)
else
cb('Authentication failed')
gently.expect authnAPI, 'connect', (theURL)->
assert.equal endpoints.authn(account), theURL
{ authenticate: authenticate }
describe 'with expected username and password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate '<PASSWORD>', (err)->
assert !err
done()
describe 'with invalid password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate '<PASSWORD>', (err)->
assert.equal err, 'Authentication failed'
done()
describe '#uidnumbers', ->
beforeEach ->
uidnumbers = (logins, cb)->
cb(null, [ 1001, 1002 ])
dirAPI = require('../lib/conjur/directory')
gently.expect dirAPI, 'connect', (theURL, theToken)->
assert.equal endpoints.directory(account), theURL
assert.deepEqual token, theToken
{ uidnumbers: uidnumbers }
it 'succeeds', (done)->
user = userAPI.connect(endpoints).users(account, token).uidnumbers [ 'login-1', 'login-2' ], (err, ids)->
assert !err
assert.deepEqual ids, [ 1001, 1002 ]
done()
| true | assert = require('assert')
gently = new (require('gently'))
userAPI = require('../lib/conjur/user')
describe 'User', ->
account = 'the-account'
endpoints = {
authn: (account)->
'http://authn-#{account}-conjur.example.com'
directory: (account)->
'http://core-#{account}-conjur.example.com'
}
username = 'the-username'
token = {
data: username
}
describe '#authenticate', ->
expectedUsername = 'bob'
expectedPassword = 'PI:PASSWORD:<PASSWORD>END_PI'
beforeEach ->
authnAPI = require('../lib/conjur/authn')
authenticate = (username, password, cb)->
if username == expectedUsername && password == PI:PASSWORD:<PASSWORD>END_PI
cb(null)
else
cb('Authentication failed')
gently.expect authnAPI, 'connect', (theURL)->
assert.equal endpoints.authn(account), theURL
{ authenticate: authenticate }
describe 'with expected username and password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate 'PI:PASSWORD:<PASSWORD>END_PI', (err)->
assert !err
done()
describe 'with invalid password', ->
it 'authenticates', (done)->
user = userAPI.connect(endpoints).user(account, 'bob').authenticate 'PI:PASSWORD:<PASSWORD>END_PI', (err)->
assert.equal err, 'Authentication failed'
done()
describe '#uidnumbers', ->
beforeEach ->
uidnumbers = (logins, cb)->
cb(null, [ 1001, 1002 ])
dirAPI = require('../lib/conjur/directory')
gently.expect dirAPI, 'connect', (theURL, theToken)->
assert.equal endpoints.directory(account), theURL
assert.deepEqual token, theToken
{ uidnumbers: uidnumbers }
it 'succeeds', (done)->
user = userAPI.connect(endpoints).users(account, token).uidnumbers [ 'login-1', 'login-2' ], (err, ids)->
assert !err
assert.deepEqual ids, [ 1001, 1002 ]
done()
|
[
{
"context": "view Tests for no-unneeded-ternary rule.\n# @author Gyandeep Singh\n###\n\n'use strict'\n\n#-----------------------------",
"end": 81,
"score": 0.9998480677604675,
"start": 67,
"tag": "NAME",
"value": "Gyandeep Singh"
}
] | src/tests/rules/no-unneeded-ternary.coffee | danielbayley/eslint-plugin-coffee | 21 | ###*
# @fileoverview Tests for no-unneeded-ternary rule.
# @author Gyandeep Singh
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unneeded-ternary'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unneeded-ternary', rule,
valid: [
'config.newIsCap = config.newIsCap isnt no'
"a = if x is 2 then 'Yes' else 'No'"
"a = if x is 2 then yes else 'No'"
"a = if x is 2 then 'Yes' else no"
"a = if x is 2 then 'true' else 'false'"
'a = if foo then foo else bar'
'''
value = 'a'
canSet = true
result = value or (if canSet then 'unset' else 'can not set')
'''
,
code: "a = if foo then 'Yes' else foo"
options: [defaultAssignment: no]
,
code: 'a = if foo then bar else foo'
options: [defaultAssignment: no]
]
invalid: [
code: 'a = if x is 2 then true else false'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x is 2 then yes else no'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x >= 2 then yes else no'
output: 'a = x >= 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x then yes else no'
output: 'a = !!x'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 15
]
,
code: 'a = if x is 1 then off else on'
output: 'a = x isnt 1'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: '''
a =
if x != 1
no
else
yes
'''
output: '''
a =
x == 1
'''
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 3
column: 5
]
,
code: 'a = if foo() then no else yes'
output: 'a = !foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if !foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if not foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if foo + bar then no else yes'
output: 'a = !(foo + bar)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if x instanceof foo then no else yes'
output: 'a = !(x instanceof foo)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = if foo then no else no'
output: 'a = no'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code: 'a = if foo() then no else no'
output: null
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if x instanceof foo then yes else no'
output: 'a = x instanceof foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = unless foo then yes else no'
output: 'a = !foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 21
]
,
code: '''
value = 'a'
canSet = yes
result = if value then value else if canSet then 'unset' else 'can not set'
'''
output: '''
value = 'a'
canSet = yes
result = value or (if canSet then 'unset' else 'can not set')
'''
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 3
column: 24
]
,
code: 'if foo then foo else (if bar then baz else qux)'
output: 'foo or (if bar then baz else qux)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 8
]
,
code: '-> if foo then foo else yield bar'
output: '-> foo or (yield bar)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 11
]
,
code: "a = if foo then foo else 'No'"
output: "a = foo or 'No'"
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code:
'a = if ((foo)) then (((((foo))))) else ((((((((((((((bar))))))))))))))'
output: 'a = ((foo)) or ((((((((((((((bar))))))))))))))'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 26
]
]
| 216684 | ###*
# @fileoverview Tests for no-unneeded-ternary rule.
# @author <NAME>
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unneeded-ternary'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unneeded-ternary', rule,
valid: [
'config.newIsCap = config.newIsCap isnt no'
"a = if x is 2 then 'Yes' else 'No'"
"a = if x is 2 then yes else 'No'"
"a = if x is 2 then 'Yes' else no"
"a = if x is 2 then 'true' else 'false'"
'a = if foo then foo else bar'
'''
value = 'a'
canSet = true
result = value or (if canSet then 'unset' else 'can not set')
'''
,
code: "a = if foo then 'Yes' else foo"
options: [defaultAssignment: no]
,
code: 'a = if foo then bar else foo'
options: [defaultAssignment: no]
]
invalid: [
code: 'a = if x is 2 then true else false'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x is 2 then yes else no'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x >= 2 then yes else no'
output: 'a = x >= 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x then yes else no'
output: 'a = !!x'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 15
]
,
code: 'a = if x is 1 then off else on'
output: 'a = x isnt 1'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: '''
a =
if x != 1
no
else
yes
'''
output: '''
a =
x == 1
'''
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 3
column: 5
]
,
code: 'a = if foo() then no else yes'
output: 'a = !foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if !foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if not foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if foo + bar then no else yes'
output: 'a = !(foo + bar)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if x instanceof foo then no else yes'
output: 'a = !(x instanceof foo)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = if foo then no else no'
output: 'a = no'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code: 'a = if foo() then no else no'
output: null
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if x instanceof foo then yes else no'
output: 'a = x instanceof foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = unless foo then yes else no'
output: 'a = !foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 21
]
,
code: '''
value = 'a'
canSet = yes
result = if value then value else if canSet then 'unset' else 'can not set'
'''
output: '''
value = 'a'
canSet = yes
result = value or (if canSet then 'unset' else 'can not set')
'''
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 3
column: 24
]
,
code: 'if foo then foo else (if bar then baz else qux)'
output: 'foo or (if bar then baz else qux)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 8
]
,
code: '-> if foo then foo else yield bar'
output: '-> foo or (yield bar)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 11
]
,
code: "a = if foo then foo else 'No'"
output: "a = foo or 'No'"
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code:
'a = if ((foo)) then (((((foo))))) else ((((((((((((((bar))))))))))))))'
output: 'a = ((foo)) or ((((((((((((((bar))))))))))))))'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 26
]
]
| true | ###*
# @fileoverview Tests for no-unneeded-ternary rule.
# @author PI:NAME:<NAME>END_PI
###
'use strict'
#------------------------------------------------------------------------------
# Requirements
#------------------------------------------------------------------------------
rule = require '../../rules/no-unneeded-ternary'
{RuleTester} = require 'eslint'
path = require 'path'
#------------------------------------------------------------------------------
# Tests
#------------------------------------------------------------------------------
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
ruleTester.run 'no-unneeded-ternary', rule,
valid: [
'config.newIsCap = config.newIsCap isnt no'
"a = if x is 2 then 'Yes' else 'No'"
"a = if x is 2 then yes else 'No'"
"a = if x is 2 then 'Yes' else no"
"a = if x is 2 then 'true' else 'false'"
'a = if foo then foo else bar'
'''
value = 'a'
canSet = true
result = value or (if canSet then 'unset' else 'can not set')
'''
,
code: "a = if foo then 'Yes' else foo"
options: [defaultAssignment: no]
,
code: 'a = if foo then bar else foo'
options: [defaultAssignment: no]
]
invalid: [
code: 'a = if x is 2 then true else false'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x is 2 then yes else no'
output: 'a = x is 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x >= 2 then yes else no'
output: 'a = x >= 2'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if x then yes else no'
output: 'a = !!x'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 15
]
,
code: 'a = if x is 1 then off else on'
output: 'a = x isnt 1'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: '''
a =
if x != 1
no
else
yes
'''
output: '''
a =
x == 1
'''
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 3
column: 5
]
,
code: 'a = if foo() then no else yes'
output: 'a = !foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if !foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 20
]
,
code: 'a = if not foo() then false else true'
output: 'a = !!foo()'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if foo + bar then no else yes'
output: 'a = !(foo + bar)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 23
]
,
code: 'a = if x instanceof foo then no else yes'
output: 'a = !(x instanceof foo)'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = if foo then no else no'
output: 'a = no'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code: 'a = if foo() then no else no'
output: null
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 19
]
,
code: 'a = if x instanceof foo then yes else no'
output: 'a = x instanceof foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 30
]
,
code: 'a = unless foo then yes else no'
output: 'a = !foo'
errors: [
message: 'Unnecessary use of boolean literals in conditional expression.'
type: 'ConditionalExpression'
line: 1
column: 21
]
,
code: '''
value = 'a'
canSet = yes
result = if value then value else if canSet then 'unset' else 'can not set'
'''
output: '''
value = 'a'
canSet = yes
result = value or (if canSet then 'unset' else 'can not set')
'''
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 3
column: 24
]
,
code: 'if foo then foo else (if bar then baz else qux)'
output: 'foo or (if bar then baz else qux)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 8
]
,
code: '-> if foo then foo else yield bar'
output: '-> foo or (yield bar)'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'IfStatement'
line: 1
column: 11
]
,
code: "a = if foo then foo else 'No'"
output: "a = foo or 'No'"
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 17
]
,
code:
'a = if ((foo)) then (((((foo))))) else ((((((((((((((bar))))))))))))))'
output: 'a = ((foo)) or ((((((((((((((bar))))))))))))))'
options: [defaultAssignment: no]
errors: [
message:
'Unnecessary use of conditional expression for default assignment.'
type: 'ConditionalExpression'
line: 1
column: 26
]
]
|
[
{
"context": "names before storing', ->\n store.push(name: 'Apple')\n expect(store.choices()[0].name).to.eq('ap",
"end": 931,
"score": 0.6571537256240845,
"start": 926,
"tag": "NAME",
"value": "Apple"
},
{
"context": "tical order', ->\n store\n .push(name: 'plum... | test/store_test.coffee | chalkchisel/velge | 0 | describe 'Velge.Store', ->
store = null
describe '#normalize', ->
beforeEach ->
store = new Velge.Store()
it 'defaults to downcasing input', ->
expect(store.normalize('Apple')).to.eq('apple')
it 'strips leading and trailing whitespace', ->
expect(store.normalize(' apple ')).to.eq('apple')
it 'is tollerant of non-string input', ->
expect(store.normalize(null)).to.eq('null')
expect(store.normalize(undefined)).to.eq('undefined')
expect(store.normalize(1)).to.eq('1')
describe '#validate', ->
beforeEach ->
store = new Velge.Store()
it 'is true for valid values', ->
expect(store.validate('apple')).to.be.true
it 'is false for invalid values', ->
expect(store.validate(' ')).to.be.false
describe '#push', ->
beforeEach ->
store = new Velge.Store()
it 'normalizes names before storing', ->
store.push(name: 'Apple')
expect(store.choices()[0].name).to.eq('apple')
it 'does not store duplicate choices', ->
store
.push(name: 'apple')
.push(name: 'apple')
expect(store.choices().length).to.eq(1)
it 'maintains choices in alphabetical order', ->
store
.push(name: 'plum')
.push(name: 'apple')
expect(store.choices()[0].name).to.eq('apple')
expect(store.choices()[1].name).to.eq('plum')
describe '#filter', ->
beforeEach ->
store = new Velge.Store()
.push(name: 'apple', chosen: false)
.push(name: 'kiwi', chosen: true)
.push(name: 'orange', chosen: false)
it 'filters down by the chosen property', ->
expect(store.filter(chosen: false).length).to.eq(2)
expect(store.filter(chosen: true).length).to.eq(1)
describe '#fuzzy', ->
beforeEach ->
store = new Velge.Store()
.push(name: 'apple')
.push(name: 'apricot')
.push(name: 'opples')
it 'finds all choices matching the query', ->
expect(store.fuzzy('p').length).to.eq(3)
expect(store.fuzzy('ap').length).to.eq(2)
expect(store.fuzzy('Ap').length).to.eq(2)
expect(store.fuzzy('pp').length).to.eq(2)
expect(store.fuzzy('PP').length).to.eq(2)
it 'sanitizes to prevent matching errors', ->
expect(store.fuzzy('{}[]()*+').length).to.eq(0)
it 'matches all choices without any value', ->
expect(store.fuzzy('').length).to.eq(3)
expect(store.fuzzy(' ').length).to.eq(3)
| 23488 | describe 'Velge.Store', ->
store = null
describe '#normalize', ->
beforeEach ->
store = new Velge.Store()
it 'defaults to downcasing input', ->
expect(store.normalize('Apple')).to.eq('apple')
it 'strips leading and trailing whitespace', ->
expect(store.normalize(' apple ')).to.eq('apple')
it 'is tollerant of non-string input', ->
expect(store.normalize(null)).to.eq('null')
expect(store.normalize(undefined)).to.eq('undefined')
expect(store.normalize(1)).to.eq('1')
describe '#validate', ->
beforeEach ->
store = new Velge.Store()
it 'is true for valid values', ->
expect(store.validate('apple')).to.be.true
it 'is false for invalid values', ->
expect(store.validate(' ')).to.be.false
describe '#push', ->
beforeEach ->
store = new Velge.Store()
it 'normalizes names before storing', ->
store.push(name: '<NAME>')
expect(store.choices()[0].name).to.eq('apple')
it 'does not store duplicate choices', ->
store
.push(name: 'apple')
.push(name: 'apple')
expect(store.choices().length).to.eq(1)
it 'maintains choices in alphabetical order', ->
store
.push(name: '<NAME>um')
.push(name: 'apple')
expect(store.choices()[0].name).to.eq('apple')
expect(store.choices()[1].name).to.eq('plum')
describe '#filter', ->
beforeEach ->
store = new Velge.Store()
.push(name: 'apple', chosen: false)
.push(name: '<NAME>', chosen: true)
.push(name: 'orange', chosen: false)
it 'filters down by the chosen property', ->
expect(store.filter(chosen: false).length).to.eq(2)
expect(store.filter(chosen: true).length).to.eq(1)
describe '#fuzzy', ->
beforeEach ->
store = new Velge.Store()
.push(name: '<NAME>')
.push(name: '<NAME>')
.push(name: '<NAME>')
it 'finds all choices matching the query', ->
expect(store.fuzzy('p').length).to.eq(3)
expect(store.fuzzy('ap').length).to.eq(2)
expect(store.fuzzy('Ap').length).to.eq(2)
expect(store.fuzzy('pp').length).to.eq(2)
expect(store.fuzzy('PP').length).to.eq(2)
it 'sanitizes to prevent matching errors', ->
expect(store.fuzzy('{}[]()*+').length).to.eq(0)
it 'matches all choices without any value', ->
expect(store.fuzzy('').length).to.eq(3)
expect(store.fuzzy(' ').length).to.eq(3)
| true | describe 'Velge.Store', ->
store = null
describe '#normalize', ->
beforeEach ->
store = new Velge.Store()
it 'defaults to downcasing input', ->
expect(store.normalize('Apple')).to.eq('apple')
it 'strips leading and trailing whitespace', ->
expect(store.normalize(' apple ')).to.eq('apple')
it 'is tollerant of non-string input', ->
expect(store.normalize(null)).to.eq('null')
expect(store.normalize(undefined)).to.eq('undefined')
expect(store.normalize(1)).to.eq('1')
describe '#validate', ->
beforeEach ->
store = new Velge.Store()
it 'is true for valid values', ->
expect(store.validate('apple')).to.be.true
it 'is false for invalid values', ->
expect(store.validate(' ')).to.be.false
describe '#push', ->
beforeEach ->
store = new Velge.Store()
it 'normalizes names before storing', ->
store.push(name: 'PI:NAME:<NAME>END_PI')
expect(store.choices()[0].name).to.eq('apple')
it 'does not store duplicate choices', ->
store
.push(name: 'apple')
.push(name: 'apple')
expect(store.choices().length).to.eq(1)
it 'maintains choices in alphabetical order', ->
store
.push(name: 'PI:NAME:<NAME>END_PIum')
.push(name: 'apple')
expect(store.choices()[0].name).to.eq('apple')
expect(store.choices()[1].name).to.eq('plum')
describe '#filter', ->
beforeEach ->
store = new Velge.Store()
.push(name: 'apple', chosen: false)
.push(name: 'PI:NAME:<NAME>END_PI', chosen: true)
.push(name: 'orange', chosen: false)
it 'filters down by the chosen property', ->
expect(store.filter(chosen: false).length).to.eq(2)
expect(store.filter(chosen: true).length).to.eq(1)
describe '#fuzzy', ->
beforeEach ->
store = new Velge.Store()
.push(name: 'PI:NAME:<NAME>END_PI')
.push(name: 'PI:NAME:<NAME>END_PI')
.push(name: 'PI:NAME:<NAME>END_PI')
it 'finds all choices matching the query', ->
expect(store.fuzzy('p').length).to.eq(3)
expect(store.fuzzy('ap').length).to.eq(2)
expect(store.fuzzy('Ap').length).to.eq(2)
expect(store.fuzzy('pp').length).to.eq(2)
expect(store.fuzzy('PP').length).to.eq(2)
it 'sanitizes to prevent matching errors', ->
expect(store.fuzzy('{}[]()*+').length).to.eq(0)
it 'matches all choices without any value', ->
expect(store.fuzzy('').length).to.eq(3)
expect(store.fuzzy(' ').length).to.eq(3)
|
[
{
"context": "$ ->\n input =\n user : $('#textboxUsername')\n pass : $('#textboxPassword')\n pass2: $('",
"end": 45,
"score": 0.7856966853141785,
"start": 30,
"tag": "USERNAME",
"value": "textboxUsername"
},
{
"context": "nput =\n user : $('#textboxUsername')\n pass :... | app/assets/js/register.coffee | lesmo/BlackSam | 1 | $ ->
input =
user : $('#textboxUsername')
pass : $('#textboxPassword')
pass2: $('#textboxPasswordRepeat')
hash : $('#hiddenUserhash')
error =
user : $('#errorUsernameLength')
pass : $('#errorPasswordLength')
pass2: $('#errorPasswordMatch')
# As we have Javascript, there's no need for HTML5 attribute
inp.removeAttr('required') for i, inp of input
$('form.register').submit (e) ->
inp.parent().removeClass('has-error') for i, inp of input
err.hide() for i, err of error
if input.user.val().length < 8
input.user.parent().addClass('has-error')
error.user.slideDown()
if input.pass.val().length < 8
input.pass.parent().addClass('has-error')
error.pass.slideDown()
if input.pass.val() isnt input.pass2.val()
input.pass2.parent().addClass('has-error')
error.pass2.slideDown()
if $(this).find('.has-error').length > 0
return e.preventDefault()
hash = input.user.val() + input.pass.val()
hash = CryptoJS.SHA512(hash).toString().toUpperCase()
hash = CryptoJS.SHA256(hash).toString().toUpperCase()
hash = CryptoJS.RIPEMD160(hash).toString().toUpperCase()
inp.val '' for i, inp of input
input.hash.val hash | 161010 | $ ->
input =
user : $('#textboxUsername')
pass : <PASSWORD>')
pass2: $('#textbox<PASSWORD>')
hash : $('#hiddenUserhash')
error =
user : $('#errorUsernameLength')
pass : $('#errorPassword<PASSWORD>')
pass2: $('#errorPasswordMatch')
# As we have Javascript, there's no need for HTML5 attribute
inp.removeAttr('required') for i, inp of input
$('form.register').submit (e) ->
inp.parent().removeClass('has-error') for i, inp of input
err.hide() for i, err of error
if input.user.val().length < 8
input.user.parent().addClass('has-error')
error.user.slideDown()
if input.pass.val().length < 8
input.pass.parent().addClass('has-error')
error.pass.slideDown()
if input.pass.val() isnt input.pass2.val()
input.pass2.parent().addClass('has-error')
error.pass2.slideDown()
if $(this).find('.has-error').length > 0
return e.preventDefault()
hash = input.user.val() + input.pass.val()
hash = CryptoJS.SHA512(hash).toString().toUpperCase()
hash = CryptoJS.SHA256(hash).toString().toUpperCase()
hash = CryptoJS.RIPEMD160(hash).toString().toUpperCase()
inp.val '' for i, inp of input
input.hash.val hash | true | $ ->
input =
user : $('#textboxUsername')
pass : PI:PASSWORD:<PASSWORD>END_PI')
pass2: $('#textboxPI:PASSWORD:<PASSWORD>END_PI')
hash : $('#hiddenUserhash')
error =
user : $('#errorUsernameLength')
pass : $('#errorPasswordPI:PASSWORD:<PASSWORD>END_PI')
pass2: $('#errorPasswordMatch')
# As we have Javascript, there's no need for HTML5 attribute
inp.removeAttr('required') for i, inp of input
$('form.register').submit (e) ->
inp.parent().removeClass('has-error') for i, inp of input
err.hide() for i, err of error
if input.user.val().length < 8
input.user.parent().addClass('has-error')
error.user.slideDown()
if input.pass.val().length < 8
input.pass.parent().addClass('has-error')
error.pass.slideDown()
if input.pass.val() isnt input.pass2.val()
input.pass2.parent().addClass('has-error')
error.pass2.slideDown()
if $(this).find('.has-error').length > 0
return e.preventDefault()
hash = input.user.val() + input.pass.val()
hash = CryptoJS.SHA512(hash).toString().toUpperCase()
hash = CryptoJS.SHA256(hash).toString().toUpperCase()
hash = CryptoJS.RIPEMD160(hash).toString().toUpperCase()
inp.val '' for i, inp of input
input.hash.val hash |
[
{
"context": "services\"\n\napp.service \"Base64\", ->\n keyStr = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\"\n encode: ( input ) ->\n output = \"\"\n ",
"end": 175,
"score": 0.9997192025184631,
"start": 109,
"tag": "KEY",
"value": "ABCDEFGHIJKLMNOPQ... | app/components/utils/base64-service.coffee | vidatio/web-app | 0 | # Base64
# ======
"use strict"
app = angular.module "app.services"
app.service "Base64", ->
keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
encode: ( input ) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
loop
chr1 = input.charCodeAt(i++)
chr2 = input.charCodeAt(i++)
chr3 = input.charCodeAt(i++)
enc1 = chr1 >> 2
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
enc4 = chr3 & 63
if isNaN(chr2)
enc3 = enc4 = 64
else enc4 = 64 if isNaN(chr3)
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4)
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
decode: (input) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
# remove all characters that are not A-Z, a-z, 0-9, +, /, or =
base64test = /[^A-Za-z0-9\+\/\=]/g
if base64test.exec(input)
alert """There were invalid base64 characters in the input text.
Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='
Expect errors in decoding."""
input = input.replace /[^A-Za-z0-9\+\/\=]/g, ""
loop
enc1 = keyStr.indexOf input.charAt( i++ )
enc2 = keyStr.indexOf input.charAt( i++ )
enc3 = keyStr.indexOf input.charAt( i++ )
enc4 = keyStr.indexOf input.charAt( i++ )
chr1 = (enc1 << 2) | (enc2 >> 4)
chr2 = ( (enc2 & 15) << 4 ) | ( enc3 >> 2 )
chr3 = ( (enc3 & 3) << 6 ) | enc4
output = output + String.fromCharCode( chr1 )
output = output + String.fromCharCode( chr2 ) unless enc3 is 64
output = output + String.fromCharCode( chr3 ) unless enc4 is 64
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
| 70960 | # Base64
# ======
"use strict"
app = angular.module "app.services"
app.service "Base64", ->
keyStr = "<KEY>
encode: ( input ) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
loop
chr1 = input.charCodeAt(i++)
chr2 = input.charCodeAt(i++)
chr3 = input.charCodeAt(i++)
enc1 = chr1 >> 2
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
enc4 = chr3 & 63
if isNaN(chr2)
enc3 = enc4 = 64
else enc4 = 64 if isNaN(chr3)
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4)
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
decode: (input) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
# remove all characters that are not A-Z, a-z, 0-9, +, /, or =
base64test = /[^A-Za-z0-9\+\/\=]/g
if base64test.exec(input)
alert """There were invalid base64 characters in the input text.
Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='
Expect errors in decoding."""
input = input.replace /[^A-Za-z0-9\+\/\=]/g, ""
loop
enc1 = keyStr.indexOf input.charAt( i++ )
enc2 = keyStr.indexOf input.charAt( i++ )
enc3 = keyStr.indexOf input.charAt( i++ )
enc4 = keyStr.indexOf input.charAt( i++ )
chr1 = (enc1 << 2) | (enc2 >> 4)
chr2 = ( (enc2 & 15) << 4 ) | ( enc3 >> 2 )
chr3 = ( (enc3 & 3) << 6 ) | enc4
output = output + String.fromCharCode( chr1 )
output = output + String.fromCharCode( chr2 ) unless enc3 is 64
output = output + String.fromCharCode( chr3 ) unless enc4 is 64
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
| true | # Base64
# ======
"use strict"
app = angular.module "app.services"
app.service "Base64", ->
keyStr = "PI:KEY:<KEY>END_PI
encode: ( input ) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
loop
chr1 = input.charCodeAt(i++)
chr2 = input.charCodeAt(i++)
chr3 = input.charCodeAt(i++)
enc1 = chr1 >> 2
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4)
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6)
enc4 = chr3 & 63
if isNaN(chr2)
enc3 = enc4 = 64
else enc4 = 64 if isNaN(chr3)
output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) + keyStr.charAt(enc3) + keyStr.charAt(enc4)
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
decode: (input) ->
output = ""
chr1 = undefined
chr2 = undefined
chr3 = ""
enc1 = undefined
enc2 = undefined
enc3 = undefined
enc4 = ""
i = 0
# remove all characters that are not A-Z, a-z, 0-9, +, /, or =
base64test = /[^A-Za-z0-9\+\/\=]/g
if base64test.exec(input)
alert """There were invalid base64 characters in the input text.
Valid base64 characters are A-Z, a-z, 0-9, '+', '/',and '='
Expect errors in decoding."""
input = input.replace /[^A-Za-z0-9\+\/\=]/g, ""
loop
enc1 = keyStr.indexOf input.charAt( i++ )
enc2 = keyStr.indexOf input.charAt( i++ )
enc3 = keyStr.indexOf input.charAt( i++ )
enc4 = keyStr.indexOf input.charAt( i++ )
chr1 = (enc1 << 2) | (enc2 >> 4)
chr2 = ( (enc2 & 15) << 4 ) | ( enc3 >> 2 )
chr3 = ( (enc3 & 3) << 6 ) | enc4
output = output + String.fromCharCode( chr1 )
output = output + String.fromCharCode( chr2 ) unless enc3 is 64
output = output + String.fromCharCode( chr3 ) unless enc4 is 64
chr1 = chr2 = chr3 = ""
enc1 = enc2 = enc3 = enc4 = ""
break unless i < input.length
output
|
[
{
"context": "\n# store = new Store()\n#\n# store.set(\"name\", \"Aron\")\n# store.get(\"name\") #=> Aron\n# store.remove",
"end": 352,
"score": 0.9825661182403564,
"start": 348,
"tag": "NAME",
"value": "Aron"
},
{
"context": "\n #\n # Examples\n #\n # store.set(\"api-k... | src/offline/store.coffee | aron/annotator.offline.js | 31 | # Helper methods for working with localStorage. Adds support for storing
# objects as serialized JSON, setting expiry times on stored keys and catching
# exceptions.
#
# Caught execeptions can be listened for by subscribing to the "error" event
# which will recieve the error object.
#
# Examples
#
# store = new Store()
#
# store.set("name", "Aron")
# store.get("name") #=> Aron
# store.remove("name")
#
# Returns a new instance of Store.
Annotator.Plugin.Offline.Store = class Store extends Annotator.Delegator
# Internal: Prefix for all keys stored by the store.
@KEY_PREFIX: "annotator.offline/"
# Internal: Delimeter used to seperate the cache time from the value.
@CACHE_DELIMITER: "--cache--"
# Internal: Reference to the global localStorage object.
@localStorage: window.localStorage
# Public: Checks to see if the current browser supports local storage.
#
# Examples
#
# store = new Store if Store.isSupported()
#
# Returns true if the browser supports local storage.
@isSupported: ->
try "localStorage" of window and window["localStorage"] isnt null
catch e then false
# Public: Get the current time as a unix timestamp in
# milliseconds.
#
# Examples
#
# Store.now() //=> 1325099398242
#
# Returns the current time in milliseconds.
@now: -> new Date().getTime()
# Public: Extracts all the values stored under the KEY_PREFIX. An additional
# partial key can be provided that will be added to the prefix.
#
# partial - A partial database key (default: "").
#
# Examples
#
# values = store.all()
# some = store.all("user") # All keys beginning with "user"
#
# Returns an array of extracted keys.
all: (partial="") ->
values = []
prefix = @prefixed(partial)
for key of localStorage when key.indexOf(prefix) is 0
value = @get(key.slice(Store.KEY_PREFIX.length))
values.push(value)
values
# Public: Gets a key from localStorage. Checks the expiry of
# the key when set, if expired returns null.
#
# key - The key String to lookup.
#
# Examples
#
# store.set("api-key", "12345")
# store.get("api-key") #=> "12345"
# store.get("non-existant") #=> null
#
# Returns the stored value or null if not found.
get: (key) ->
value = Store.localStorage.getItem(@prefixed key)
if value
value = @checkCache(value)
@remove(key) unless value
JSON.parse(value)
# Public: Sets a value for the key provided. An optional "expires" time in
# milliseconds can be provided, the key will not be accessble via #get() after
# this time.
#
# All values will be serialized with JSON.stringify() so ensure that they
# do not have recursive properties before passing them to #set().
#
# key - A key string to set.
# value - A value to set.
# time - Expiry time in milliseconds (default: null).
#
# Examples
#
# store.set("key", 12345)
# store.set("temporary", {user: 1}, 3000)
# store.get("temporary") #=> {user: 1}
# setTimeout ->
# store.get("temporary") #=> null
# , 3000
#
# Returns itself.
set: (key, value, time) ->
value = JSON.stringify value
value = (Store.now() + time) + Store.CACHE_DELIMITER + value if time
try
Store.localStorage.setItem(@prefixed(key), value)
catch error
this.publish('error', [error, this])
this
# Public: Removes the key from the localStorage.
#
# key - The key to remove.
#
# Examples
#
# store.set("name", "Aron")
# store.remove("key")
# store.get("name") #=> null
#
# Returns itself.
remove: (key) ->
Store.localStorage.removeItem(@prefixed key)
this
# Public: Removes all keys in local storage with the prefix.
#
# Examples
#
# store.clear()
#
# Returns itself.
clear: ->
localStorage = Store.localStorage
for key of localStorage when key.indexOf(Store.KEY_PREFIX) is 0
localStorage.removeItem(key)
this
# Internal: Applies the KEY_PREFIX to the provided key. This is used to
# namespace keys in localStorage.
#
# key - A user provided key to prefix.
#
# Examples
#
# store.prefixed("name") #=> "annotator.readmill/name"
#
# Returns a prefixed key.
prefixed: (key) ->
Store.KEY_PREFIX + key
# Internal: Checks the expiry period (if any) of a value extracted from
# localStorage. Returns the value if it is still valid, otherwise returns
# null.
#
# param - comment
#
# Examples
#
# store.checkCache("1325099398242--cache--\"expired\") #=> null
# store.checkCache("1325199398242--cache--\"valid\") #=> "valid"
#
# Returns extracted value or null if expired.
checkCache: (value) ->
if value.indexOf(Store.CACHE_DELIMITER) > -1
# If the expiry time has passed then return null.
cached = value.split(Store.CACHE_DELIMITER)
value = if Store.now() > cached.shift()
then null else cached.join(Store.CACHE_DELIMITER)
value
| 90658 | # Helper methods for working with localStorage. Adds support for storing
# objects as serialized JSON, setting expiry times on stored keys and catching
# exceptions.
#
# Caught execeptions can be listened for by subscribing to the "error" event
# which will recieve the error object.
#
# Examples
#
# store = new Store()
#
# store.set("name", "<NAME>")
# store.get("name") #=> Aron
# store.remove("name")
#
# Returns a new instance of Store.
Annotator.Plugin.Offline.Store = class Store extends Annotator.Delegator
# Internal: Prefix for all keys stored by the store.
@KEY_PREFIX: "annotator.offline/"
# Internal: Delimeter used to seperate the cache time from the value.
@CACHE_DELIMITER: "--cache--"
# Internal: Reference to the global localStorage object.
@localStorage: window.localStorage
# Public: Checks to see if the current browser supports local storage.
#
# Examples
#
# store = new Store if Store.isSupported()
#
# Returns true if the browser supports local storage.
@isSupported: ->
try "localStorage" of window and window["localStorage"] isnt null
catch e then false
# Public: Get the current time as a unix timestamp in
# milliseconds.
#
# Examples
#
# Store.now() //=> 1325099398242
#
# Returns the current time in milliseconds.
@now: -> new Date().getTime()
# Public: Extracts all the values stored under the KEY_PREFIX. An additional
# partial key can be provided that will be added to the prefix.
#
# partial - A partial database key (default: "").
#
# Examples
#
# values = store.all()
# some = store.all("user") # All keys beginning with "user"
#
# Returns an array of extracted keys.
all: (partial="") ->
values = []
prefix = @prefixed(partial)
for key of localStorage when key.indexOf(prefix) is 0
value = @get(key.slice(Store.KEY_PREFIX.length))
values.push(value)
values
# Public: Gets a key from localStorage. Checks the expiry of
# the key when set, if expired returns null.
#
# key - The key String to lookup.
#
# Examples
#
# store.set("api-key", "<KEY>")
# store.get("api-key") #=> "<KEY>"
# store.get("non-existant") #=> null
#
# Returns the stored value or null if not found.
get: (key) ->
value = Store.localStorage.getItem(@prefixed key)
if value
value = @checkCache(value)
@remove(key) unless value
JSON.parse(value)
# Public: Sets a value for the key provided. An optional "expires" time in
# milliseconds can be provided, the key will not be accessble via #get() after
# this time.
#
# All values will be serialized with JSON.stringify() so ensure that they
# do not have recursive properties before passing them to #set().
#
# key - A key string to set.
# value - A value to set.
# time - Expiry time in milliseconds (default: null).
#
# Examples
#
# store.set("key", <KEY>)
# store.set("temporary", {user: 1}, 3000)
# store.get("temporary") #=> {user: 1}
# setTimeout ->
# store.get("temporary") #=> null
# , 3000
#
# Returns itself.
set: (key, value, time) ->
value = JSON.stringify value
value = (Store.now() + time) + Store.CACHE_DELIMITER + value if time
try
Store.localStorage.setItem(@prefixed(key), value)
catch error
this.publish('error', [error, this])
this
# Public: Removes the key from the localStorage.
#
# key - The key to remove.
#
# Examples
#
# store.set("name", "Aron")
# store.remove("key")
# store.get("name") #=> null
#
# Returns itself.
remove: (key) ->
Store.localStorage.removeItem(@prefixed key)
this
# Public: Removes all keys in local storage with the prefix.
#
# Examples
#
# store.clear()
#
# Returns itself.
clear: ->
localStorage = Store.localStorage
for key of localStorage when key.indexOf(Store.KEY_PREFIX) is 0
localStorage.removeItem(key)
this
# Internal: Applies the KEY_PREFIX to the provided key. This is used to
# namespace keys in localStorage.
#
# key - A user provided key to prefix.
#
# Examples
#
# store.prefixed("name") #=> "annotator.readmill/name"
#
# Returns a prefixed key.
prefixed: (key) ->
Store.KEY_PREFIX + key
# Internal: Checks the expiry period (if any) of a value extracted from
# localStorage. Returns the value if it is still valid, otherwise returns
# null.
#
# param - comment
#
# Examples
#
# store.checkCache("1325099398242--cache--\"expired\") #=> null
# store.checkCache("1325199398242--cache--\"valid\") #=> "valid"
#
# Returns extracted value or null if expired.
checkCache: (value) ->
if value.indexOf(Store.CACHE_DELIMITER) > -1
# If the expiry time has passed then return null.
cached = value.split(Store.CACHE_DELIMITER)
value = if Store.now() > cached.shift()
then null else cached.join(Store.CACHE_DELIMITER)
value
| true | # Helper methods for working with localStorage. Adds support for storing
# objects as serialized JSON, setting expiry times on stored keys and catching
# exceptions.
#
# Caught execeptions can be listened for by subscribing to the "error" event
# which will recieve the error object.
#
# Examples
#
# store = new Store()
#
# store.set("name", "PI:NAME:<NAME>END_PI")
# store.get("name") #=> Aron
# store.remove("name")
#
# Returns a new instance of Store.
Annotator.Plugin.Offline.Store = class Store extends Annotator.Delegator
# Internal: Prefix for all keys stored by the store.
@KEY_PREFIX: "annotator.offline/"
# Internal: Delimeter used to seperate the cache time from the value.
@CACHE_DELIMITER: "--cache--"
# Internal: Reference to the global localStorage object.
@localStorage: window.localStorage
# Public: Checks to see if the current browser supports local storage.
#
# Examples
#
# store = new Store if Store.isSupported()
#
# Returns true if the browser supports local storage.
@isSupported: ->
try "localStorage" of window and window["localStorage"] isnt null
catch e then false
# Public: Get the current time as a unix timestamp in
# milliseconds.
#
# Examples
#
# Store.now() //=> 1325099398242
#
# Returns the current time in milliseconds.
@now: -> new Date().getTime()
# Public: Extracts all the values stored under the KEY_PREFIX. An additional
# partial key can be provided that will be added to the prefix.
#
# partial - A partial database key (default: "").
#
# Examples
#
# values = store.all()
# some = store.all("user") # All keys beginning with "user"
#
# Returns an array of extracted keys.
all: (partial="") ->
values = []
prefix = @prefixed(partial)
for key of localStorage when key.indexOf(prefix) is 0
value = @get(key.slice(Store.KEY_PREFIX.length))
values.push(value)
values
# Public: Gets a key from localStorage. Checks the expiry of
# the key when set, if expired returns null.
#
# key - The key String to lookup.
#
# Examples
#
# store.set("api-key", "PI:KEY:<KEY>END_PI")
# store.get("api-key") #=> "PI:KEY:<KEY>END_PI"
# store.get("non-existant") #=> null
#
# Returns the stored value or null if not found.
get: (key) ->
value = Store.localStorage.getItem(@prefixed key)
if value
value = @checkCache(value)
@remove(key) unless value
JSON.parse(value)
# Public: Sets a value for the key provided. An optional "expires" time in
# milliseconds can be provided, the key will not be accessble via #get() after
# this time.
#
# All values will be serialized with JSON.stringify() so ensure that they
# do not have recursive properties before passing them to #set().
#
# key - A key string to set.
# value - A value to set.
# time - Expiry time in milliseconds (default: null).
#
# Examples
#
# store.set("key", PI:KEY:<KEY>END_PI)
# store.set("temporary", {user: 1}, 3000)
# store.get("temporary") #=> {user: 1}
# setTimeout ->
# store.get("temporary") #=> null
# , 3000
#
# Returns itself.
set: (key, value, time) ->
value = JSON.stringify value
value = (Store.now() + time) + Store.CACHE_DELIMITER + value if time
try
Store.localStorage.setItem(@prefixed(key), value)
catch error
this.publish('error', [error, this])
this
# Public: Removes the key from the localStorage.
#
# key - The key to remove.
#
# Examples
#
# store.set("name", "Aron")
# store.remove("key")
# store.get("name") #=> null
#
# Returns itself.
remove: (key) ->
Store.localStorage.removeItem(@prefixed key)
this
# Public: Removes all keys in local storage with the prefix.
#
# Examples
#
# store.clear()
#
# Returns itself.
clear: ->
localStorage = Store.localStorage
for key of localStorage when key.indexOf(Store.KEY_PREFIX) is 0
localStorage.removeItem(key)
this
# Internal: Applies the KEY_PREFIX to the provided key. This is used to
# namespace keys in localStorage.
#
# key - A user provided key to prefix.
#
# Examples
#
# store.prefixed("name") #=> "annotator.readmill/name"
#
# Returns a prefixed key.
prefixed: (key) ->
Store.KEY_PREFIX + key
# Internal: Checks the expiry period (if any) of a value extracted from
# localStorage. Returns the value if it is still valid, otherwise returns
# null.
#
# param - comment
#
# Examples
#
# store.checkCache("1325099398242--cache--\"expired\") #=> null
# store.checkCache("1325199398242--cache--\"valid\") #=> "valid"
#
# Returns extracted value or null if expired.
checkCache: (value) ->
if value.indexOf(Store.CACHE_DELIMITER) > -1
# If the expiry time has passed then return null.
cached = value.split(Store.CACHE_DELIMITER)
value = if Store.now() > cached.shift()
then null else cached.join(Store.CACHE_DELIMITER)
value
|
[
{
"context": "= require 'path'\n\nmodule.exports =\n name: 'P.O.R.T.A.L'\n debug: true\n apiPrefix: '/v1'\n plugins:\n ",
"end": 62,
"score": 0.5890060663223267,
"start": 57,
"tag": "NAME",
"value": "T.A.L"
}
] | server/config/default.coffee | stevelacy/portal | 0 | {join} = require 'path'
module.exports =
name: 'P.O.R.T.A.L'
debug: true
apiPrefix: '/v1'
plugins:
path: join __dirname, '../../plugins'
namespace: 'plugins'
| 166923 | {join} = require 'path'
module.exports =
name: 'P.O.R.<NAME>'
debug: true
apiPrefix: '/v1'
plugins:
path: join __dirname, '../../plugins'
namespace: 'plugins'
| true | {join} = require 'path'
module.exports =
name: 'P.O.R.PI:NAME:<NAME>END_PI'
debug: true
apiPrefix: '/v1'
plugins:
path: join __dirname, '../../plugins'
namespace: 'plugins'
|
[
{
"context": "bject settings\n connObj.should.eql 'http://127.0.0.1:8529'\n done()\n\n it 'should create an ",
"end": 1662,
"score": 0.8183928728103638,
"start": 1653,
"tag": "IP_ADDRESS",
"value": "127.0.0.1"
},
{
"context": " database: 'rightDatabase'\n ... | test/core.test.coffee | wavepointcode/loopback-connector-arangodb | 0 | # This test written in mocha+should.js
should = require('./init');
arangojs = require 'arangojs'
qb = require 'aqb'
chance = require('chance').Chance()
arangodb = require '..'
DataSource = require('loopback-datasource-juggler').DataSource
GeoPoint = require('loopback-datasource-juggler').GeoPoint
ArangoDBConnector = arangodb.ArangoDBConnector
describe 'arangodb core functionality:', () ->
ds = null
config = null
before () ->
ds = getDataSource()
describe 'connecting:', () ->
before () ->
# get settings for db from .rc file
config = require('rc')('loopback', {}).test.arangodb
generateConnObject = arangodb.generateConnObject
simple_model = ds.define 'SimpleModel', {
name:
type: String
}
complex_model = ds.define 'ComplexModel', {
name:
type: String
money:
type: Number
birthday:
type: Date
icon:
type: Buffer
active:
type: Boolean
likes:
type: Array
address:
street:
type: String
house_number:
type: String
city:
type: String
zip:
type: String
country:
type: String
location:
type: GeoPoint
}, {
arangodb:
collection: 'Complex'
}
describe 'connection generator:', () ->
it 'should create the default connection object when called with an empty settings object', (done) ->
settings = {}
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://127.0.0.1:8529'
done()
it 'should create an connection using the connection settings when url is not set', (done) ->
settings = require('rc')('loopback').test.arangodb
settings =
host: 'right_host'
port: 32768
database: 'rightDatabase'
username: 'rightUser'
password: 'rightPassword'
promise: true
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://rightUser:rightPassword@right_host:32768'
done()
describe 'authentication:', () ->
wrongAuth = null
it "should throw an error when using wrong credentials", (done) ->
config.password = 'wrong'
wrongAuth = getDataSource config
`(function(){
wrongAuth.connector.query('FOR year in 2010..2013 RETURN year', function (err, cursor){
if (err)
throw err;
});
}).should.throw();`
done()
describe 'exposed properties:', () ->
it 'should expose a property "db" to access the driver directly', (done) ->
ds.connector.db.should.be.not.null
ds.connector.db.should.be.Object
ds.connector.db.should.be.arangojs
done()
it 'should expose a property "qb" to access the query builder directly', (done) ->
ds.connector.qb.should.not.be.null
ds.connector.qb.should.be.qb
done()
it 'should expose a property "api" to access the HTTP API directly', (done) ->
ds.connector.api.should.not.be.null
ds.connector.api.should.be.Object
done()
it 'should expose a function "version" which callsback with the version of the database', (done) ->
ds.connector.getVersion (err, result) ->
done err if err
result.should.exist
result.should.have.keys ['server', 'version']
result.version.should.match /[0-9]+\.[0-9]+\.[0-9]+/
done()
describe 'connector details:', () ->
it 'should provide a function "getTypes" which returns the array ["db", "nosql", "arangodb"]', (done) ->
types = ds.connector.getTypes()
types.should.not.be.null
types.should.be.Array
types.length.should.be.above(2)
types.should.eql ['db', 'nosql', 'arangodb']
done()
it 'should provide a function "getDefaultIdType" that returns String', (done) ->
defaultIdType = ds.connector.getDefaultIdType()
defaultIdType.should.not.be.null
defaultIdType.should.be.a.class
done()
it "should convert ArangoDB Types to the respective Loopback Data Types", (done) ->
firstName = chance.first()
lastName = chance.last()
birthdate = chance.birthday({american: false})
money = chance.integer {min: 100, max: 1000}
lat = chance.latitude()
lng = chance.longitude()
fromDB =
name:
first: firstName
last: lastName
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20').toJSON()
active: true
likes: ['nodejs', 'loopback']
location:
lat: lat
lng: lng
jsonData = ds.connector.fromDatabase 'ComplexModel', fromDB
expected =
name:
first: firstName
last: lastName
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20')
active: true
likes: ['nodejs', 'loopback']
location: new GeoPoint {lat: lat, lng: lng}
jsonData.should.eql expected
done()
describe 'connector access', () ->
it "should get the collection name from the name of the model", (done) ->
simpleCollection = ds.connector.getCollectionName 'SimpleModel'
simpleCollection.should.not.be.null
simpleCollection.should.be.a.String
simpleCollection.should.eql 'SimpleModel'
done()
it "should get the collection name from the 'name' property on the 'arangodb' property", (done) ->
complexCollection = ds.connector.getCollectionName 'ComplexModel'
complexCollection.should.not.be.null
complexCollection.should.be.a.String
complexCollection.should.eql 'Complex'
done()
describe 'querying', () ->
it "should execute a AQL query with no variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" RETURN year"
].join("\n")
ds.connector.db.query aql_query_string, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" LET following_year = year + @difference",
" RETURN { year: year, following: following_year }"
].join("\n")
ds.connector.db.query aql_query_string, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
it "should execute a AQL query with no variables provided using the query builder object", (done) ->
aql_query_object = ds.connector.qb.for('year').in('2010..2013').return('year')
ds.connector.db.query aql_query_object, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided using the query builder object", (done) ->
qb = ds.connector.qb
aql = qb.for('year').in('2010..2013')
aql = aql.let 'following', qb.add(qb.ref('year'), qb.ref('@difference'))
aql = aql.return {
year: qb.ref('year'),
following: qb.ref('following')
}
ds.connector.db.query aql, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
| 153801 | # This test written in mocha+should.js
should = require('./init');
arangojs = require 'arangojs'
qb = require 'aqb'
chance = require('chance').Chance()
arangodb = require '..'
DataSource = require('loopback-datasource-juggler').DataSource
GeoPoint = require('loopback-datasource-juggler').GeoPoint
ArangoDBConnector = arangodb.ArangoDBConnector
describe 'arangodb core functionality:', () ->
ds = null
config = null
before () ->
ds = getDataSource()
describe 'connecting:', () ->
before () ->
# get settings for db from .rc file
config = require('rc')('loopback', {}).test.arangodb
generateConnObject = arangodb.generateConnObject
simple_model = ds.define 'SimpleModel', {
name:
type: String
}
complex_model = ds.define 'ComplexModel', {
name:
type: String
money:
type: Number
birthday:
type: Date
icon:
type: Buffer
active:
type: Boolean
likes:
type: Array
address:
street:
type: String
house_number:
type: String
city:
type: String
zip:
type: String
country:
type: String
location:
type: GeoPoint
}, {
arangodb:
collection: 'Complex'
}
describe 'connection generator:', () ->
it 'should create the default connection object when called with an empty settings object', (done) ->
settings = {}
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://127.0.0.1:8529'
done()
it 'should create an connection using the connection settings when url is not set', (done) ->
settings = require('rc')('loopback').test.arangodb
settings =
host: 'right_host'
port: 32768
database: 'rightDatabase'
username: 'rightUser'
password: '<PASSWORD>'
promise: true
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://rightUser:rightPassword@right_host:32768'
done()
describe 'authentication:', () ->
wrongAuth = null
it "should throw an error when using wrong credentials", (done) ->
config.password = '<PASSWORD>'
wrongAuth = getDataSource config
`(function(){
wrongAuth.connector.query('FOR year in 2010..2013 RETURN year', function (err, cursor){
if (err)
throw err;
});
}).should.throw();`
done()
describe 'exposed properties:', () ->
it 'should expose a property "db" to access the driver directly', (done) ->
ds.connector.db.should.be.not.null
ds.connector.db.should.be.Object
ds.connector.db.should.be.arangojs
done()
it 'should expose a property "qb" to access the query builder directly', (done) ->
ds.connector.qb.should.not.be.null
ds.connector.qb.should.be.qb
done()
it 'should expose a property "api" to access the HTTP API directly', (done) ->
ds.connector.api.should.not.be.null
ds.connector.api.should.be.Object
done()
it 'should expose a function "version" which callsback with the version of the database', (done) ->
ds.connector.getVersion (err, result) ->
done err if err
result.should.exist
result.should.have.keys ['server', 'version']
result.version.should.match /[0-9]+\.[0-9]+\.[0-9]+/
done()
describe 'connector details:', () ->
it 'should provide a function "getTypes" which returns the array ["db", "nosql", "arangodb"]', (done) ->
types = ds.connector.getTypes()
types.should.not.be.null
types.should.be.Array
types.length.should.be.above(2)
types.should.eql ['db', 'nosql', 'arangodb']
done()
it 'should provide a function "getDefaultIdType" that returns String', (done) ->
defaultIdType = ds.connector.getDefaultIdType()
defaultIdType.should.not.be.null
defaultIdType.should.be.a.class
done()
it "should convert ArangoDB Types to the respective Loopback Data Types", (done) ->
firstName = chance.first()
lastName = chance.last()
birthdate = chance.birthday({american: false})
money = chance.integer {min: 100, max: 1000}
lat = chance.latitude()
lng = chance.longitude()
fromDB =
name:
first: <NAME>
last: <NAME>
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20').toJSON()
active: true
likes: ['nodejs', 'loopback']
location:
lat: lat
lng: lng
jsonData = ds.connector.fromDatabase 'ComplexModel', fromDB
expected =
name:
first: <NAME>
last: <NAME>
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20')
active: true
likes: ['nodejs', 'loopback']
location: new GeoPoint {lat: lat, lng: lng}
jsonData.should.eql expected
done()
describe 'connector access', () ->
it "should get the collection name from the name of the model", (done) ->
simpleCollection = ds.connector.getCollectionName 'SimpleModel'
simpleCollection.should.not.be.null
simpleCollection.should.be.a.String
simpleCollection.should.eql 'SimpleModel'
done()
it "should get the collection name from the 'name' property on the 'arangodb' property", (done) ->
complexCollection = ds.connector.getCollectionName 'ComplexModel'
complexCollection.should.not.be.null
complexCollection.should.be.a.String
complexCollection.should.eql 'Complex'
done()
describe 'querying', () ->
it "should execute a AQL query with no variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" RETURN year"
].join("\n")
ds.connector.db.query aql_query_string, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" LET following_year = year + @difference",
" RETURN { year: year, following: following_year }"
].join("\n")
ds.connector.db.query aql_query_string, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
it "should execute a AQL query with no variables provided using the query builder object", (done) ->
aql_query_object = ds.connector.qb.for('year').in('2010..2013').return('year')
ds.connector.db.query aql_query_object, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided using the query builder object", (done) ->
qb = ds.connector.qb
aql = qb.for('year').in('2010..2013')
aql = aql.let 'following', qb.add(qb.ref('year'), qb.ref('@difference'))
aql = aql.return {
year: qb.ref('year'),
following: qb.ref('following')
}
ds.connector.db.query aql, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
| true | # This test written in mocha+should.js
should = require('./init');
arangojs = require 'arangojs'
qb = require 'aqb'
chance = require('chance').Chance()
arangodb = require '..'
DataSource = require('loopback-datasource-juggler').DataSource
GeoPoint = require('loopback-datasource-juggler').GeoPoint
ArangoDBConnector = arangodb.ArangoDBConnector
describe 'arangodb core functionality:', () ->
ds = null
config = null
before () ->
ds = getDataSource()
describe 'connecting:', () ->
before () ->
# get settings for db from .rc file
config = require('rc')('loopback', {}).test.arangodb
generateConnObject = arangodb.generateConnObject
simple_model = ds.define 'SimpleModel', {
name:
type: String
}
complex_model = ds.define 'ComplexModel', {
name:
type: String
money:
type: Number
birthday:
type: Date
icon:
type: Buffer
active:
type: Boolean
likes:
type: Array
address:
street:
type: String
house_number:
type: String
city:
type: String
zip:
type: String
country:
type: String
location:
type: GeoPoint
}, {
arangodb:
collection: 'Complex'
}
describe 'connection generator:', () ->
it 'should create the default connection object when called with an empty settings object', (done) ->
settings = {}
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://127.0.0.1:8529'
done()
it 'should create an connection using the connection settings when url is not set', (done) ->
settings = require('rc')('loopback').test.arangodb
settings =
host: 'right_host'
port: 32768
database: 'rightDatabase'
username: 'rightUser'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
promise: true
connObj = arangodb.generateConnObject settings
connObj.should.eql 'http://rightUser:rightPassword@right_host:32768'
done()
describe 'authentication:', () ->
wrongAuth = null
it "should throw an error when using wrong credentials", (done) ->
config.password = 'PI:PASSWORD:<PASSWORD>END_PI'
wrongAuth = getDataSource config
`(function(){
wrongAuth.connector.query('FOR year in 2010..2013 RETURN year', function (err, cursor){
if (err)
throw err;
});
}).should.throw();`
done()
describe 'exposed properties:', () ->
it 'should expose a property "db" to access the driver directly', (done) ->
ds.connector.db.should.be.not.null
ds.connector.db.should.be.Object
ds.connector.db.should.be.arangojs
done()
it 'should expose a property "qb" to access the query builder directly', (done) ->
ds.connector.qb.should.not.be.null
ds.connector.qb.should.be.qb
done()
it 'should expose a property "api" to access the HTTP API directly', (done) ->
ds.connector.api.should.not.be.null
ds.connector.api.should.be.Object
done()
it 'should expose a function "version" which callsback with the version of the database', (done) ->
ds.connector.getVersion (err, result) ->
done err if err
result.should.exist
result.should.have.keys ['server', 'version']
result.version.should.match /[0-9]+\.[0-9]+\.[0-9]+/
done()
describe 'connector details:', () ->
it 'should provide a function "getTypes" which returns the array ["db", "nosql", "arangodb"]', (done) ->
types = ds.connector.getTypes()
types.should.not.be.null
types.should.be.Array
types.length.should.be.above(2)
types.should.eql ['db', 'nosql', 'arangodb']
done()
it 'should provide a function "getDefaultIdType" that returns String', (done) ->
defaultIdType = ds.connector.getDefaultIdType()
defaultIdType.should.not.be.null
defaultIdType.should.be.a.class
done()
it "should convert ArangoDB Types to the respective Loopback Data Types", (done) ->
firstName = chance.first()
lastName = chance.last()
birthdate = chance.birthday({american: false})
money = chance.integer {min: 100, max: 1000}
lat = chance.latitude()
lng = chance.longitude()
fromDB =
name:
first: PI:NAME:<NAME>END_PI
last: PI:NAME:<NAME>END_PI
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20').toJSON()
active: true
likes: ['nodejs', 'loopback']
location:
lat: lat
lng: lng
jsonData = ds.connector.fromDatabase 'ComplexModel', fromDB
expected =
name:
first: PI:NAME:<NAME>END_PI
last: PI:NAME:<NAME>END_PI
profession: 'Node Developer'
money: money
birthday: birthdate
icon: new Buffer('a20')
active: true
likes: ['nodejs', 'loopback']
location: new GeoPoint {lat: lat, lng: lng}
jsonData.should.eql expected
done()
describe 'connector access', () ->
it "should get the collection name from the name of the model", (done) ->
simpleCollection = ds.connector.getCollectionName 'SimpleModel'
simpleCollection.should.not.be.null
simpleCollection.should.be.a.String
simpleCollection.should.eql 'SimpleModel'
done()
it "should get the collection name from the 'name' property on the 'arangodb' property", (done) ->
complexCollection = ds.connector.getCollectionName 'ComplexModel'
complexCollection.should.not.be.null
complexCollection.should.be.a.String
complexCollection.should.eql 'Complex'
done()
describe 'querying', () ->
it "should execute a AQL query with no variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" RETURN year"
].join("\n")
ds.connector.db.query aql_query_string, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided as a string", (done) ->
aql_query_string = [
"/* Returns the sequence of integers between 2010 and 2013 (including) */",
"FOR year IN 2010..2013",
" LET following_year = year + @difference",
" RETURN { year: year, following: following_year }"
].join("\n")
ds.connector.db.query aql_query_string, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
it "should execute a AQL query with no variables provided using the query builder object", (done) ->
aql_query_object = ds.connector.qb.for('year').in('2010..2013').return('year')
ds.connector.db.query aql_query_object, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [2010, 2011, 2012, 2013]
done()
it "should execute a AQL query with bound variables provided using the query builder object", (done) ->
qb = ds.connector.qb
aql = qb.for('year').in('2010..2013')
aql = aql.let 'following', qb.add(qb.ref('year'), qb.ref('@difference'))
aql = aql.return {
year: qb.ref('year'),
following: qb.ref('following')
}
ds.connector.db.query aql, {difference: 1}, (err, cursor) ->
done err if err
cursor.should.exist
cursor.all (err, values) ->
done err if err
values.should.not.be.null
values.should.be.a.Array
values.should.eql [{year: 2010, following: 2011}, {year: 2011, following: 2012},
{year: 2012, following: 2013}, {year: 2013, following: 2014}]
done()
|
[
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)\n# MIT Licensed\n###\n\nmongo = r",
"end": 44,
"score": 0.9998345375061035,
"start": 36,
"tag": "NAME",
"value": "Jae Kwon"
},
{
"context": "###\n# YCatalyst\n# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.... | logic/records.coffee | jaekwon/YCatalyst | 3 | ###
# YCatalyst
# Copyright(c) 2011 Jae Kwon (jae@ycatalyst.com)
# MIT Licensed
###
mongo = require '../mongo'
utils = require '../utils'
rec = require '../static/record'
exports.get_records = (root_id, level, fn) ->
now = new Date()
mongo.records.findOne _id: root_id, (err, root) ->
all = {}
if not root?
fn(err, null)
return
all[root_id] = new rec.Record(root)
tofetch = [root_id]
fetchmore = (i) ->
# NOTE: http://talklikeaduck.denhaven2.com/2009/04/15/ordered-hashes-in-ruby-1-9-and-javascript
# and http://ejohn.org/blog/javascript-in-chrome/
# The side effect of sorting here is that the dangle method will automagically sort the children by score.
mongo.records.find {parent_id: {$in: tofetch}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
tofetch = []
for record in records
tofetch.push(record._id)
all[record._id] = new rec.Record(record)
if i > 1
fetchmore(i-1)
else
console.log "get_records in #{new Date() - now}"
fn(err, all)
fetchmore(level)
exports.get_one_record = (rid, fn) ->
mongo.records.findOne _id: rid, (err, recdata) ->
if recdata
fn(err, new rec.Record(recdata))
else
fn(err, null)
# given a record object, return an object we can return to the client
# any time you need to send a record to the client through ajax,
# scrub it here
exports.scrubbed_recdata = (record) ->
object = utils.deep_clone(record.recdata)
delete object.upvoters
return object
# given a record, rescores the record
exports.score_record = (record) ->
# constants
newness_factor = 0.5 # how important is newness in hours?
gravity = 1.8
timebase_hours = 2.0
# variables
t = record.recdata.created_at.getTime()
h = t / (60*60*1000)
d_h = ((new Date()) - record.recdata.created_at) / (60*60*1000)
points = record.recdata.points
score = h*newness_factor + (points-1) / (Math.pow((d_h+timebase_hours),gravity))
# console.log "t: #{t} h: #{h} d_h: #{d_h} points: #{points} score: #{score}"
record.recdata.score = score
# recdata: the record data object
# parent: the data object for the parent, may be null or undefined
# returns: a new Record object
exports.create_record = (recdata, parent) ->
parents = []
if parent?
if not recdata.parent_id?
recdata.parent_id = parent.recdata._id
if parent.recdata.parents?
parents = [parent.recdata._id].concat(parent.recdata.parents[0..5])
else
parents = [parent.recdata._id]
recdata.parent_followers = parent.recdata.followers if parent.recdata.followers
else
recdata.parent_id = null # need this for mongodb indexing
if not recdata._id?
recdata._id = utils.randid()
recdata.created_at = new Date()
recdata.parents = parents
recdata.points = if recdata.upvoters then recdata.upvoters.length else 0
record = new rec.Record(recdata)
record.is_new = true
exports.score_record(record)
return record
# given a bunch of records and the root, organize it into a tree
# returns the root, and children can be accessed w/ .children
exports.dangle = (records, root_id) ->
root = records[root_id]
for id, record of records
parent = records[record.recdata.parent_id]
if parent
if not parent.children
parent.children = []
parent.children.push(record)
# we now have the root...
# pull out poll items and put them in a different spot.
if root.recdata.type == 'poll'
orig_children = root.children
root.children = []
root.choices = []
for child in orig_children
if child.recdata.type == 'choice'
root.choices.push(child)
else
root.children.push(child)
return root
# follow or unfollow the given record...
exports.follow = (rid, user, do_follow, cb) ->
if do_follow
update_operation = {$addToSet: {followers: user._id}}
else
update_operation = {$pull: {followers: user._id}}
mongo.records.update {_id: rid}, update_operation, cb
| 212392 | ###
# YCatalyst
# Copyright(c) 2011 <NAME> (<EMAIL>)
# MIT Licensed
###
mongo = require '../mongo'
utils = require '../utils'
rec = require '../static/record'
exports.get_records = (root_id, level, fn) ->
now = new Date()
mongo.records.findOne _id: root_id, (err, root) ->
all = {}
if not root?
fn(err, null)
return
all[root_id] = new rec.Record(root)
tofetch = [root_id]
fetchmore = (i) ->
# NOTE: http://talklikeaduck.denhaven2.com/2009/04/15/ordered-hashes-in-ruby-1-9-and-javascript
# and http://ejohn.org/blog/javascript-in-chrome/
# The side effect of sorting here is that the dangle method will automagically sort the children by score.
mongo.records.find {parent_id: {$in: tofetch}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
tofetch = []
for record in records
tofetch.push(record._id)
all[record._id] = new rec.Record(record)
if i > 1
fetchmore(i-1)
else
console.log "get_records in #{new Date() - now}"
fn(err, all)
fetchmore(level)
exports.get_one_record = (rid, fn) ->
mongo.records.findOne _id: rid, (err, recdata) ->
if recdata
fn(err, new rec.Record(recdata))
else
fn(err, null)
# given a record object, return an object we can return to the client
# any time you need to send a record to the client through ajax,
# scrub it here
exports.scrubbed_recdata = (record) ->
object = utils.deep_clone(record.recdata)
delete object.upvoters
return object
# given a record, rescores the record
exports.score_record = (record) ->
# constants
newness_factor = 0.5 # how important is newness in hours?
gravity = 1.8
timebase_hours = 2.0
# variables
t = record.recdata.created_at.getTime()
h = t / (60*60*1000)
d_h = ((new Date()) - record.recdata.created_at) / (60*60*1000)
points = record.recdata.points
score = h*newness_factor + (points-1) / (Math.pow((d_h+timebase_hours),gravity))
# console.log "t: #{t} h: #{h} d_h: #{d_h} points: #{points} score: #{score}"
record.recdata.score = score
# recdata: the record data object
# parent: the data object for the parent, may be null or undefined
# returns: a new Record object
exports.create_record = (recdata, parent) ->
parents = []
if parent?
if not recdata.parent_id?
recdata.parent_id = parent.recdata._id
if parent.recdata.parents?
parents = [parent.recdata._id].concat(parent.recdata.parents[0..5])
else
parents = [parent.recdata._id]
recdata.parent_followers = parent.recdata.followers if parent.recdata.followers
else
recdata.parent_id = null # need this for mongodb indexing
if not recdata._id?
recdata._id = utils.randid()
recdata.created_at = new Date()
recdata.parents = parents
recdata.points = if recdata.upvoters then recdata.upvoters.length else 0
record = new rec.Record(recdata)
record.is_new = true
exports.score_record(record)
return record
# given a bunch of records and the root, organize it into a tree
# returns the root, and children can be accessed w/ .children
exports.dangle = (records, root_id) ->
root = records[root_id]
for id, record of records
parent = records[record.recdata.parent_id]
if parent
if not parent.children
parent.children = []
parent.children.push(record)
# we now have the root...
# pull out poll items and put them in a different spot.
if root.recdata.type == 'poll'
orig_children = root.children
root.children = []
root.choices = []
for child in orig_children
if child.recdata.type == 'choice'
root.choices.push(child)
else
root.children.push(child)
return root
# follow or unfollow the given record...
exports.follow = (rid, user, do_follow, cb) ->
if do_follow
update_operation = {$addToSet: {followers: user._id}}
else
update_operation = {$pull: {followers: user._id}}
mongo.records.update {_id: rid}, update_operation, cb
| true | ###
# YCatalyst
# Copyright(c) 2011 PI:NAME:<NAME>END_PI (PI:EMAIL:<EMAIL>END_PI)
# MIT Licensed
###
mongo = require '../mongo'
utils = require '../utils'
rec = require '../static/record'
exports.get_records = (root_id, level, fn) ->
now = new Date()
mongo.records.findOne _id: root_id, (err, root) ->
all = {}
if not root?
fn(err, null)
return
all[root_id] = new rec.Record(root)
tofetch = [root_id]
fetchmore = (i) ->
# NOTE: http://talklikeaduck.denhaven2.com/2009/04/15/ordered-hashes-in-ruby-1-9-and-javascript
# and http://ejohn.org/blog/javascript-in-chrome/
# The side effect of sorting here is that the dangle method will automagically sort the children by score.
mongo.records.find {parent_id: {$in: tofetch}}, {sort: [['score', -1]]}, (err, cursor) ->
cursor.toArray (err, records) ->
tofetch = []
for record in records
tofetch.push(record._id)
all[record._id] = new rec.Record(record)
if i > 1
fetchmore(i-1)
else
console.log "get_records in #{new Date() - now}"
fn(err, all)
fetchmore(level)
exports.get_one_record = (rid, fn) ->
mongo.records.findOne _id: rid, (err, recdata) ->
if recdata
fn(err, new rec.Record(recdata))
else
fn(err, null)
# given a record object, return an object we can return to the client
# any time you need to send a record to the client through ajax,
# scrub it here
exports.scrubbed_recdata = (record) ->
object = utils.deep_clone(record.recdata)
delete object.upvoters
return object
# given a record, rescores the record
exports.score_record = (record) ->
# constants
newness_factor = 0.5 # how important is newness in hours?
gravity = 1.8
timebase_hours = 2.0
# variables
t = record.recdata.created_at.getTime()
h = t / (60*60*1000)
d_h = ((new Date()) - record.recdata.created_at) / (60*60*1000)
points = record.recdata.points
score = h*newness_factor + (points-1) / (Math.pow((d_h+timebase_hours),gravity))
# console.log "t: #{t} h: #{h} d_h: #{d_h} points: #{points} score: #{score}"
record.recdata.score = score
# recdata: the record data object
# parent: the data object for the parent, may be null or undefined
# returns: a new Record object
exports.create_record = (recdata, parent) ->
parents = []
if parent?
if not recdata.parent_id?
recdata.parent_id = parent.recdata._id
if parent.recdata.parents?
parents = [parent.recdata._id].concat(parent.recdata.parents[0..5])
else
parents = [parent.recdata._id]
recdata.parent_followers = parent.recdata.followers if parent.recdata.followers
else
recdata.parent_id = null # need this for mongodb indexing
if not recdata._id?
recdata._id = utils.randid()
recdata.created_at = new Date()
recdata.parents = parents
recdata.points = if recdata.upvoters then recdata.upvoters.length else 0
record = new rec.Record(recdata)
record.is_new = true
exports.score_record(record)
return record
# given a bunch of records and the root, organize it into a tree
# returns the root, and children can be accessed w/ .children
exports.dangle = (records, root_id) ->
root = records[root_id]
for id, record of records
parent = records[record.recdata.parent_id]
if parent
if not parent.children
parent.children = []
parent.children.push(record)
# we now have the root...
# pull out poll items and put them in a different spot.
if root.recdata.type == 'poll'
orig_children = root.children
root.children = []
root.choices = []
for child in orig_children
if child.recdata.type == 'choice'
root.choices.push(child)
else
root.children.push(child)
return root
# follow or unfollow the given record...
exports.follow = (rid, user, do_follow, cb) ->
if do_follow
update_operation = {$addToSet: {followers: user._id}}
else
update_operation = {$pull: {followers: user._id}}
mongo.records.update {_id: rid}, update_operation, cb
|
[
{
"context": "{\n title: 'Bad Saarow'\n mobileLink: 'Menü'\n back_text: 'zurück'\n ",
"end": 24,
"score": 0.9938292503356934,
"start": 14,
"tag": "NAME",
"value": "Bad Saarow"
}
] | src/pages/navigation.coffee | bad-saarow/website | 0 | {
title: 'Bad Saarow'
mobileLink: 'Menü'
back_text: 'zurück'
menu: [
{'Gemeinde':
[
{'Aktuelles'}
{'Gemeinde entdecken'}
{'Freiwillige Feuerfehr'}
{'Kommunalpolitik'}
]
}
{'Stadtentwicklung':
[
{'Wohnen'}
{'Straßen & Verkehr'}
{_divider: true}
{_section: 'Überschrift'}
{'Stadtplanung':
[
{'Stadterneuerung'}
{'Bauleitplanung'}
{'Umwelt- und Freiraumplanung'}
]
}
]
}
{'Bilderung & Familie':
[
{'Schulen'}
]
}
{'Freizeit & Tourismus':
[
{'Sport'}
{'Freizeitangebote'}
{'Vereine'}
{'Kultur'}
]
}
{'Wirtschaft':
[
{'Gewerbegebiete'}
]
}
]
} | 46288 | {
title: '<NAME>'
mobileLink: 'Menü'
back_text: 'zurück'
menu: [
{'Gemeinde':
[
{'Aktuelles'}
{'Gemeinde entdecken'}
{'Freiwillige Feuerfehr'}
{'Kommunalpolitik'}
]
}
{'Stadtentwicklung':
[
{'Wohnen'}
{'Straßen & Verkehr'}
{_divider: true}
{_section: 'Überschrift'}
{'Stadtplanung':
[
{'Stadterneuerung'}
{'Bauleitplanung'}
{'Umwelt- und Freiraumplanung'}
]
}
]
}
{'Bilderung & Familie':
[
{'Schulen'}
]
}
{'Freizeit & Tourismus':
[
{'Sport'}
{'Freizeitangebote'}
{'Vereine'}
{'Kultur'}
]
}
{'Wirtschaft':
[
{'Gewerbegebiete'}
]
}
]
} | true | {
title: 'PI:NAME:<NAME>END_PI'
mobileLink: 'Menü'
back_text: 'zurück'
menu: [
{'Gemeinde':
[
{'Aktuelles'}
{'Gemeinde entdecken'}
{'Freiwillige Feuerfehr'}
{'Kommunalpolitik'}
]
}
{'Stadtentwicklung':
[
{'Wohnen'}
{'Straßen & Verkehr'}
{_divider: true}
{_section: 'Überschrift'}
{'Stadtplanung':
[
{'Stadterneuerung'}
{'Bauleitplanung'}
{'Umwelt- und Freiraumplanung'}
]
}
]
}
{'Bilderung & Familie':
[
{'Schulen'}
]
}
{'Freizeit & Tourismus':
[
{'Sport'}
{'Freizeitangebote'}
{'Vereine'}
{'Kultur'}
]
}
{'Wirtschaft':
[
{'Gewerbegebiete'}
]
}
]
} |
[
{
"context": "nimation)\n\n toData :()->\n obj = \n name : @name\n pass : @pass\n skills: @skills.toD",
"end": 5545,
"score": 0.7642853856086731,
"start": 5545,
"tag": "NAME",
"value": ""
},
{
"context": ":()->\n obj = \n name : @name\n pass : @pas... | src/char.coffee | mizchi-sandbox/ws-netgame | 1 | # manual backup
Skill = require('./skills')
{Weapons} = require('./equip')
{random,sqrt,min,max,sin,cos} = Math
{Sprite} = require('./sprites')
{ObjectId} = require('./ObjectId')
{randint} = require('./Util')
{SkillBox} = require './skills'
Skills = require './skills'
{ItemBox} = require './ItemBox'
seq = ['one','two','three','four','five','six','seven','eight','nine','zero']
class Character extends Sprite
constructor: (@scene , @x=0,@y=0,@group=ObjectId.Enemy ,status={}) ->
@pass = ''
super @x, @y
@keys = {}
@target = null
@dir = 0
@id = ~~(random() * 1000)
@cnt = ~~(random() * 60)
@items = new ItemBox
@animation = []
@_path = []
update:(objs)->
@cnt++
if @is_alive()
@affected()
target = @recognize(objs)
@action(target)
affected:()->
@check(@status)
@regenerate() if @cnt%30 == 0
recognize: (objs)->
@search objs
@select_skill()
return objs
action:(target)->
@move()
for i in seq
@skills.sets[i].charge(false) if @skills.sets[i]
@selected_skill.charge(true) #update(target)
@selected_skill.exec(target) #update(target)
# affected
check:(st)->
st.hp = st.HP if st.hp > st.HP
st.hp = 0 if st.hp < 0
if @is_alive()
if @target?.is_dead()
@target = null
else
@target = null
regenerate: ()->
r = (if @target then 2 else 1)
if @status.hp < @status.HP
@status.hp += 1
# recognize
search : (objs)->
range = (if @target then @status.trace_range else @status.active_range)
enemies = @find_obj(ObjectId.get_enemy(@),objs,range)
if @target
if @target.is_dead() or @get_distance(@target) > @status.trace_range
console.log "#{@name} lost track of #{@target.name}"
@target = null
else if enemies.length is 1
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
else if enemies.length > 1
enemies.sort (a,b)=>
@get_distance(a) - @get_distance(b)
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
select_skill: ()->
@selected_skill = new Skill.Atack(@)
onHealed : (amount)->
update_path : (fp ,tp )->
[fx ,fy] = fp
from = [~~(fx),~~(fy)]
[tx ,ty] = tp
to = [~~(tx),~~(ty)]
@_path = @scene.search_path( from ,to )
@_path = @_path.map (i)=> @scene.get_point i[0],i[1]
@to = @_path.shift()
wander : ()->
[tx,ty] = @scene.get_point(@x,@y)
@to = [tx+randint(-1,1),ty+randint(-1,1)]
step_forward: (to_x , to_y, wide)->
@set_dir(to_x,to_y)
[
@x + wide * cos(@dir)
@y + wide * sin(@dir)
]
onDamaged : (amount)->
is_waiting : ()->
if @target
@set_dir(@target.x,@target.y)
return true if @get_distance(@target) < @selected_skill.range
else if @group isnt ObjectId.Player
return true if @cnt%60 < 15
return false
move: ()->
if @_on_going_destination
if @target
@set_dir(@target.x,@target.y)
return if @get_distance(@target) < @selected_skill.range
else
return if @is_waiting()
if @destination
@update_path( [~~(@x),~~(@y)],[~~(@destination.x),~~(@destination.y)] )
@to = @_path.shift()
@destination = null
@_on_going_destination = true
unless @to
# 優先度 destination(人為設定) > target(ターゲット) > follow(リーダー)
if @target
@update_path( [~~(@x),~~(@y)],[~~(@target.x),~~(@target.y)] )
else if @follow
@update_path( [~~(@x),~~(@y)],[~~(@follow.x),~~(@follow.y)] )
else
@wander()
else
wide = @status.speed
[dx,dy] = @to
[nx,ny] = @step_forward( dx , dy ,wide)
if dx-wide<nx<dx+wide and dy-wide<ny<dy+wide
if @_path.length > 0
@to = @_path.shift()
else
@to = null
@_on_going_detination = false
# 衝突判定
unless @scene.collide( nx,ny )
@x = nx if nx?
@y = ny if ny?
# 引っかかってる場合
if @x is @_lx_ and @y is @_ly_
@wander()
@_lx_ = @x
@_ly_ = @y
die : (actor)->
@cnt = 0
actor.status.gold += ~~(random()*100)
actor.status.get_exp(@status.lv*10)
console.log "#{@name} is killed by #{actor.name}." if actor
shift_target:(targets)->
if @target and targets.length > 0
if not @target in targets
@target = targets[0]
return
else if targets.length == 1
@target = targets[0]
return
if targets.length > 1
cur = targets.indexOf @target
if cur+1 >= targets.length
cur = 0
else
cur += 1
@target = targets[cur]
equip_item : (item)->
if item.at in (k for k,v of @equipment)
@equipment[item.at] = item
false
get_item:(item)->
null
# @items.push(item)
use_item:(item)->
# @items.remove(item)
get_param:(param)->
0
# (item?[param] or 0 for at,item of @equipment).reduce (x,y)-> x+y
add_damage : (actor, amount)->
before = @is_alive()
@status.hp -= amount
unless @target
if @get_distance(actor) < @status.trace_range
@target = actor
@die(actor) if @is_dead() and before
return @is_alive()
is_alive:()-> @status.hp > 1
is_dead:()-> ! @is_alive()
set_pos : (@x=0,@y=0)->
set_dir: (x,y)->
rx = x - @x
ry = y - @y
if rx >= 0
@dir = Math.atan( ry / rx )
else
@dir = Math.PI - Math.atan( ry / - rx )
add_animation:(animation)->
@animation.push(animation)
toData :()->
obj =
name : @name
pass : @pass
skills: @skills.toData()
status: @status.toData()
equipment : @equipment.toData()
items : @items.toData()
exports.Character = Character
| 223724 | # manual backup
Skill = require('./skills')
{Weapons} = require('./equip')
{random,sqrt,min,max,sin,cos} = Math
{Sprite} = require('./sprites')
{ObjectId} = require('./ObjectId')
{randint} = require('./Util')
{SkillBox} = require './skills'
Skills = require './skills'
{ItemBox} = require './ItemBox'
seq = ['one','two','three','four','five','six','seven','eight','nine','zero']
class Character extends Sprite
constructor: (@scene , @x=0,@y=0,@group=ObjectId.Enemy ,status={}) ->
@pass = ''
super @x, @y
@keys = {}
@target = null
@dir = 0
@id = ~~(random() * 1000)
@cnt = ~~(random() * 60)
@items = new ItemBox
@animation = []
@_path = []
update:(objs)->
@cnt++
if @is_alive()
@affected()
target = @recognize(objs)
@action(target)
affected:()->
@check(@status)
@regenerate() if @cnt%30 == 0
recognize: (objs)->
@search objs
@select_skill()
return objs
action:(target)->
@move()
for i in seq
@skills.sets[i].charge(false) if @skills.sets[i]
@selected_skill.charge(true) #update(target)
@selected_skill.exec(target) #update(target)
# affected
check:(st)->
st.hp = st.HP if st.hp > st.HP
st.hp = 0 if st.hp < 0
if @is_alive()
if @target?.is_dead()
@target = null
else
@target = null
regenerate: ()->
r = (if @target then 2 else 1)
if @status.hp < @status.HP
@status.hp += 1
# recognize
search : (objs)->
range = (if @target then @status.trace_range else @status.active_range)
enemies = @find_obj(ObjectId.get_enemy(@),objs,range)
if @target
if @target.is_dead() or @get_distance(@target) > @status.trace_range
console.log "#{@name} lost track of #{@target.name}"
@target = null
else if enemies.length is 1
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
else if enemies.length > 1
enemies.sort (a,b)=>
@get_distance(a) - @get_distance(b)
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
select_skill: ()->
@selected_skill = new Skill.Atack(@)
onHealed : (amount)->
update_path : (fp ,tp )->
[fx ,fy] = fp
from = [~~(fx),~~(fy)]
[tx ,ty] = tp
to = [~~(tx),~~(ty)]
@_path = @scene.search_path( from ,to )
@_path = @_path.map (i)=> @scene.get_point i[0],i[1]
@to = @_path.shift()
wander : ()->
[tx,ty] = @scene.get_point(@x,@y)
@to = [tx+randint(-1,1),ty+randint(-1,1)]
step_forward: (to_x , to_y, wide)->
@set_dir(to_x,to_y)
[
@x + wide * cos(@dir)
@y + wide * sin(@dir)
]
onDamaged : (amount)->
is_waiting : ()->
if @target
@set_dir(@target.x,@target.y)
return true if @get_distance(@target) < @selected_skill.range
else if @group isnt ObjectId.Player
return true if @cnt%60 < 15
return false
move: ()->
if @_on_going_destination
if @target
@set_dir(@target.x,@target.y)
return if @get_distance(@target) < @selected_skill.range
else
return if @is_waiting()
if @destination
@update_path( [~~(@x),~~(@y)],[~~(@destination.x),~~(@destination.y)] )
@to = @_path.shift()
@destination = null
@_on_going_destination = true
unless @to
# 優先度 destination(人為設定) > target(ターゲット) > follow(リーダー)
if @target
@update_path( [~~(@x),~~(@y)],[~~(@target.x),~~(@target.y)] )
else if @follow
@update_path( [~~(@x),~~(@y)],[~~(@follow.x),~~(@follow.y)] )
else
@wander()
else
wide = @status.speed
[dx,dy] = @to
[nx,ny] = @step_forward( dx , dy ,wide)
if dx-wide<nx<dx+wide and dy-wide<ny<dy+wide
if @_path.length > 0
@to = @_path.shift()
else
@to = null
@_on_going_detination = false
# 衝突判定
unless @scene.collide( nx,ny )
@x = nx if nx?
@y = ny if ny?
# 引っかかってる場合
if @x is @_lx_ and @y is @_ly_
@wander()
@_lx_ = @x
@_ly_ = @y
die : (actor)->
@cnt = 0
actor.status.gold += ~~(random()*100)
actor.status.get_exp(@status.lv*10)
console.log "#{@name} is killed by #{actor.name}." if actor
shift_target:(targets)->
if @target and targets.length > 0
if not @target in targets
@target = targets[0]
return
else if targets.length == 1
@target = targets[0]
return
if targets.length > 1
cur = targets.indexOf @target
if cur+1 >= targets.length
cur = 0
else
cur += 1
@target = targets[cur]
equip_item : (item)->
if item.at in (k for k,v of @equipment)
@equipment[item.at] = item
false
get_item:(item)->
null
# @items.push(item)
use_item:(item)->
# @items.remove(item)
get_param:(param)->
0
# (item?[param] or 0 for at,item of @equipment).reduce (x,y)-> x+y
add_damage : (actor, amount)->
before = @is_alive()
@status.hp -= amount
unless @target
if @get_distance(actor) < @status.trace_range
@target = actor
@die(actor) if @is_dead() and before
return @is_alive()
is_alive:()-> @status.hp > 1
is_dead:()-> ! @is_alive()
set_pos : (@x=0,@y=0)->
set_dir: (x,y)->
rx = x - @x
ry = y - @y
if rx >= 0
@dir = Math.atan( ry / rx )
else
@dir = Math.PI - Math.atan( ry / - rx )
add_animation:(animation)->
@animation.push(animation)
toData :()->
obj =
name :<NAME> @name
pass : <PASSWORD>
skills: @skills.toData()
status: @status.toData()
equipment : @equipment.toData()
items : @items.toData()
exports.Character = Character
| true | # manual backup
Skill = require('./skills')
{Weapons} = require('./equip')
{random,sqrt,min,max,sin,cos} = Math
{Sprite} = require('./sprites')
{ObjectId} = require('./ObjectId')
{randint} = require('./Util')
{SkillBox} = require './skills'
Skills = require './skills'
{ItemBox} = require './ItemBox'
seq = ['one','two','three','four','five','six','seven','eight','nine','zero']
class Character extends Sprite
constructor: (@scene , @x=0,@y=0,@group=ObjectId.Enemy ,status={}) ->
@pass = ''
super @x, @y
@keys = {}
@target = null
@dir = 0
@id = ~~(random() * 1000)
@cnt = ~~(random() * 60)
@items = new ItemBox
@animation = []
@_path = []
update:(objs)->
@cnt++
if @is_alive()
@affected()
target = @recognize(objs)
@action(target)
affected:()->
@check(@status)
@regenerate() if @cnt%30 == 0
recognize: (objs)->
@search objs
@select_skill()
return objs
action:(target)->
@move()
for i in seq
@skills.sets[i].charge(false) if @skills.sets[i]
@selected_skill.charge(true) #update(target)
@selected_skill.exec(target) #update(target)
# affected
check:(st)->
st.hp = st.HP if st.hp > st.HP
st.hp = 0 if st.hp < 0
if @is_alive()
if @target?.is_dead()
@target = null
else
@target = null
regenerate: ()->
r = (if @target then 2 else 1)
if @status.hp < @status.HP
@status.hp += 1
# recognize
search : (objs)->
range = (if @target then @status.trace_range else @status.active_range)
enemies = @find_obj(ObjectId.get_enemy(@),objs,range)
if @target
if @target.is_dead() or @get_distance(@target) > @status.trace_range
console.log "#{@name} lost track of #{@target.name}"
@target = null
else if enemies.length is 1
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
else if enemies.length > 1
enemies.sort (a,b)=>
@get_distance(a) - @get_distance(b)
@target = enemies[0]
console.log "#{@name} find #{@target.name}"
select_skill: ()->
@selected_skill = new Skill.Atack(@)
onHealed : (amount)->
update_path : (fp ,tp )->
[fx ,fy] = fp
from = [~~(fx),~~(fy)]
[tx ,ty] = tp
to = [~~(tx),~~(ty)]
@_path = @scene.search_path( from ,to )
@_path = @_path.map (i)=> @scene.get_point i[0],i[1]
@to = @_path.shift()
wander : ()->
[tx,ty] = @scene.get_point(@x,@y)
@to = [tx+randint(-1,1),ty+randint(-1,1)]
step_forward: (to_x , to_y, wide)->
@set_dir(to_x,to_y)
[
@x + wide * cos(@dir)
@y + wide * sin(@dir)
]
onDamaged : (amount)->
is_waiting : ()->
if @target
@set_dir(@target.x,@target.y)
return true if @get_distance(@target) < @selected_skill.range
else if @group isnt ObjectId.Player
return true if @cnt%60 < 15
return false
move: ()->
if @_on_going_destination
if @target
@set_dir(@target.x,@target.y)
return if @get_distance(@target) < @selected_skill.range
else
return if @is_waiting()
if @destination
@update_path( [~~(@x),~~(@y)],[~~(@destination.x),~~(@destination.y)] )
@to = @_path.shift()
@destination = null
@_on_going_destination = true
unless @to
# 優先度 destination(人為設定) > target(ターゲット) > follow(リーダー)
if @target
@update_path( [~~(@x),~~(@y)],[~~(@target.x),~~(@target.y)] )
else if @follow
@update_path( [~~(@x),~~(@y)],[~~(@follow.x),~~(@follow.y)] )
else
@wander()
else
wide = @status.speed
[dx,dy] = @to
[nx,ny] = @step_forward( dx , dy ,wide)
if dx-wide<nx<dx+wide and dy-wide<ny<dy+wide
if @_path.length > 0
@to = @_path.shift()
else
@to = null
@_on_going_detination = false
# 衝突判定
unless @scene.collide( nx,ny )
@x = nx if nx?
@y = ny if ny?
# 引っかかってる場合
if @x is @_lx_ and @y is @_ly_
@wander()
@_lx_ = @x
@_ly_ = @y
die : (actor)->
@cnt = 0
actor.status.gold += ~~(random()*100)
actor.status.get_exp(@status.lv*10)
console.log "#{@name} is killed by #{actor.name}." if actor
shift_target:(targets)->
if @target and targets.length > 0
if not @target in targets
@target = targets[0]
return
else if targets.length == 1
@target = targets[0]
return
if targets.length > 1
cur = targets.indexOf @target
if cur+1 >= targets.length
cur = 0
else
cur += 1
@target = targets[cur]
equip_item : (item)->
if item.at in (k for k,v of @equipment)
@equipment[item.at] = item
false
get_item:(item)->
null
# @items.push(item)
use_item:(item)->
# @items.remove(item)
get_param:(param)->
0
# (item?[param] or 0 for at,item of @equipment).reduce (x,y)-> x+y
add_damage : (actor, amount)->
before = @is_alive()
@status.hp -= amount
unless @target
if @get_distance(actor) < @status.trace_range
@target = actor
@die(actor) if @is_dead() and before
return @is_alive()
is_alive:()-> @status.hp > 1
is_dead:()-> ! @is_alive()
set_pos : (@x=0,@y=0)->
set_dir: (x,y)->
rx = x - @x
ry = y - @y
if rx >= 0
@dir = Math.atan( ry / rx )
else
@dir = Math.PI - Math.atan( ry / - rx )
add_animation:(animation)->
@animation.push(animation)
toData :()->
obj =
name :PI:NAME:<NAME>END_PI @name
pass : PI:PASSWORD:<PASSWORD>END_PI
skills: @skills.toData()
status: @status.toData()
equipment : @equipment.toData()
items : @items.toData()
exports.Character = Character
|
[
{
"context": "ategory views\n#\n# Nodize CMS\n# https://github.com/nodize/nodizecms\n#\n# Copyright 2012, Hypee\n# http://hype",
"end": 59,
"score": 0.9994057416915894,
"start": 53,
"tag": "USERNAME",
"value": "nodize"
},
{
"context": "://github.com/nodize/nodizecms\n#\n# Copyright 2... | modules/backend/inline_views/view_category.coffee | nodize/nodizecms | 32 | # Category views
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Return categories in select, used on deletion
# TODO: see if it's useful, probably can be removed
#
@view backend_categorySelect: ->
select '.select', name:'categories[]', multiple:"multiple", ->
for category in @categories
option value:category.id_category, -> category.name
#
# Displaying category settings tab
#
@view backend_category: ->
html ->
ul '#categoryList.mb20.sortable-container', ->
for category in @categories
li "#category_#{category.id_category}.sortme.category#{category.id_category}", rel: category.id_category, ->
a class: 'icon delete right', rel: category.id_category
img '.icon.left drag pr5', src: "#{@settings.assetsPath}/images/icon_16_ordering.png"
a class: 'left pl5 title', rel: category.id_category, ->
text category.name
coffeescript ->
#
# Categories list itemManager
#
categoriesManager = new ION.ItemManager(
element: "category"
container: "categoryList"
)
categoriesManager.makeSortable()
#
# Make all categories editable
#
$$("#categoryList .title").each (item, idx) ->
rel = item.getProperty("rel")
item.addEvent "click", (e) ->
ION.formWindow "category" + rel, "categoryForm" + rel, Lang.get("ionize_title_category_edit"), "category\/\/edit/" + rel
| 187053 | # Category views
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Return categories in select, used on deletion
# TODO: see if it's useful, probably can be removed
#
@view backend_categorySelect: ->
select '.select', name:'categories[]', multiple:"multiple", ->
for category in @categories
option value:category.id_category, -> category.name
#
# Displaying category settings tab
#
@view backend_category: ->
html ->
ul '#categoryList.mb20.sortable-container', ->
for category in @categories
li "#category_#{category.id_category}.sortme.category#{category.id_category}", rel: category.id_category, ->
a class: 'icon delete right', rel: category.id_category
img '.icon.left drag pr5', src: "#{@settings.assetsPath}/images/icon_16_ordering.png"
a class: 'left pl5 title', rel: category.id_category, ->
text category.name
coffeescript ->
#
# Categories list itemManager
#
categoriesManager = new ION.ItemManager(
element: "category"
container: "categoryList"
)
categoriesManager.makeSortable()
#
# Make all categories editable
#
$$("#categoryList .title").each (item, idx) ->
rel = item.getProperty("rel")
item.addEvent "click", (e) ->
ION.formWindow "category" + rel, "categoryForm" + rel, Lang.get("ionize_title_category_edit"), "category\/\/edit/" + rel
| true | # Category views
#
# Nodize CMS
# https://github.com/nodize/nodizecms
#
# Copyright 2012, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
@include = ->
#
# Return categories in select, used on deletion
# TODO: see if it's useful, probably can be removed
#
@view backend_categorySelect: ->
select '.select', name:'categories[]', multiple:"multiple", ->
for category in @categories
option value:category.id_category, -> category.name
#
# Displaying category settings tab
#
@view backend_category: ->
html ->
ul '#categoryList.mb20.sortable-container', ->
for category in @categories
li "#category_#{category.id_category}.sortme.category#{category.id_category}", rel: category.id_category, ->
a class: 'icon delete right', rel: category.id_category
img '.icon.left drag pr5', src: "#{@settings.assetsPath}/images/icon_16_ordering.png"
a class: 'left pl5 title', rel: category.id_category, ->
text category.name
coffeescript ->
#
# Categories list itemManager
#
categoriesManager = new ION.ItemManager(
element: "category"
container: "categoryList"
)
categoriesManager.makeSortable()
#
# Make all categories editable
#
$$("#categoryList .title").each (item, idx) ->
rel = item.getProperty("rel")
item.addEvent "click", (e) ->
ION.formWindow "category" + rel, "categoryForm" + rel, Lang.get("ionize_title_category_edit"), "category\/\/edit/" + rel
|
[
{
"context": "mfabrik GmbH\n * MIT Licence\n * https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org\n#",
"end": 166,
"score": 0.9862642288208008,
"start": 152,
"tag": "USERNAME",
"value": "programmfabrik"
},
{
"context": "\t# this reaches the panels direc... | src/elements/Pane/SimplePane.coffee | programmfabrik/coffeescript-ui | 10 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Pane with Header and Footer
class CUI.SimplePane extends CUI.Pane
# @param [Object] options for pane creation
# @option options [Array, Element, jQuery] header_left access the "left" of the PaneHeader
# @option options [Array, Element, jQuery] header_center access the "center" of the PaneHeader
# @option options [Array, Element, jQuery] header_right access the "right" of the PaneHeader
# @option options [Array, Element, jQuery] footer_left access the "left" of the PaneFooter
# @option options [Array, Element, jQuery] footer_right access the "right" of the PaneFooter
__init: ->
super()
for k in [
"header_left"
"header_center"
"header_right"
"footer_left"
"footer_center"
"footer_right"
]
value = @["_#{k}"]
if not value
continue
@append(value, k)
if @_title
@append(new CUI.Label(text: @_title), "header_left")
if not CUI.__ng__
@addClass("cui-simple-pane")
initOpts: ->
super()
@addOpts
title: {}
header_right: {}
header_center: {}
header_left: {}
footer_left: {}
footer_center: {}
footer_right: {}
content: {}
force_header:
mandatory: true
check: Boolean
default: false
force_footer:
mandatory: true
check: Boolean
default: false
@removeOpt("top")
@removeOpt("bottom")
@removeOpt("center")
@
readOpts: ->
# Skip readOpts from Pane as it sets defaults in top and bottom
# which is not allowed in our initOpts
CUI.VerticalLayout::readOpts.call(@)
if @_title
CUI.util.assert(not @_header_left, "new CUI.SimplePane", "opts.header_left conflicts with opts.title", opts: @opts)
if @forceHeader() or
not (CUI.util.isUndef(@_header_left) and CUI.util.isUndef(@_header_center) and CUI.util.isUndef(@_header_right)) or
@_title
@__pane_header = new CUI.PaneHeader()
@_top =
content: @__pane_header
if @forceFooter() or not (CUI.util.isUndef(@_footer_left) and CUI.util.isUndef(@_footer_center) and CUI.util.isUndef(@_footer_right))
@__pane_footer = new CUI.PaneFooter()
@_bottom =
content: @__pane_footer
@_center =
content: @_content
@
forceHeader: ->
@_force_header
forceFooter: ->
@_force_footer
hasHeader: ->
!!@__pane_header
hasFooter: ->
!!@__pane_footer
destroy: ->
@__pane_header?.destroy()
@__pane_header = null
@__pane_footer?.destroy()
@__pane_footer = null
super()
getPaneAndKey: (key) ->
# this reaches the panels directly
if key in ["center", "top", "bottom"]
[ @getLayout(), key ]
else if key == "content"
[ @getLayout(), "center" ]
else
m = key.match(/^(.*?)_(.*)$/)
CUI.util.assert(m?.length==3, "SimplePane.getPaneAndKey", "key #{key} not matched.", matched: m)
pn = "__pane_#{m?[1]}"
pane = @[pn]
CUI.util.assert(pane, "SimplePane.getPaneAndKey", "pane #{pn} not found.")
[ pane, m[2] ]
empty: (key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.empty(_key)
@
append: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.append(content, _key)
@
replace: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.replace(content, _key)
@
| 24920 | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Pane with Header and Footer
class CUI.SimplePane extends CUI.Pane
# @param [Object] options for pane creation
# @option options [Array, Element, jQuery] header_left access the "left" of the PaneHeader
# @option options [Array, Element, jQuery] header_center access the "center" of the PaneHeader
# @option options [Array, Element, jQuery] header_right access the "right" of the PaneHeader
# @option options [Array, Element, jQuery] footer_left access the "left" of the PaneFooter
# @option options [Array, Element, jQuery] footer_right access the "right" of the PaneFooter
__init: ->
super()
for k in [
"header_left"
"header_center"
"header_right"
"footer_left"
"footer_center"
"footer_right"
]
value = @["_#{k}"]
if not value
continue
@append(value, k)
if @_title
@append(new CUI.Label(text: @_title), "header_left")
if not CUI.__ng__
@addClass("cui-simple-pane")
initOpts: ->
super()
@addOpts
title: {}
header_right: {}
header_center: {}
header_left: {}
footer_left: {}
footer_center: {}
footer_right: {}
content: {}
force_header:
mandatory: true
check: Boolean
default: false
force_footer:
mandatory: true
check: Boolean
default: false
@removeOpt("top")
@removeOpt("bottom")
@removeOpt("center")
@
readOpts: ->
# Skip readOpts from Pane as it sets defaults in top and bottom
# which is not allowed in our initOpts
CUI.VerticalLayout::readOpts.call(@)
if @_title
CUI.util.assert(not @_header_left, "new CUI.SimplePane", "opts.header_left conflicts with opts.title", opts: @opts)
if @forceHeader() or
not (CUI.util.isUndef(@_header_left) and CUI.util.isUndef(@_header_center) and CUI.util.isUndef(@_header_right)) or
@_title
@__pane_header = new CUI.PaneHeader()
@_top =
content: @__pane_header
if @forceFooter() or not (CUI.util.isUndef(@_footer_left) and CUI.util.isUndef(@_footer_center) and CUI.util.isUndef(@_footer_right))
@__pane_footer = new CUI.PaneFooter()
@_bottom =
content: @__pane_footer
@_center =
content: @_content
@
forceHeader: ->
@_force_header
forceFooter: ->
@_force_footer
hasHeader: ->
!!@__pane_header
hasFooter: ->
!!@__pane_footer
destroy: ->
@__pane_header?.destroy()
@__pane_header = null
@__pane_footer?.destroy()
@__pane_footer = null
super()
getPaneAndKey: (key) ->
# this reaches the panels directly
if key in ["<KEY>", "<KEY>", "<KEY>"]
[ @getLayout(), key ]
else if key == "content"
[ @getLayout(), "center" ]
else
m = key.match(/^(.*?)_(.*)$/)
CUI.util.assert(m?.length==3, "SimplePane.getPaneAndKey", "key #{key} not matched.", matched: m)
pn = "__pane_#{m?[1]}"
pane = @[pn]
CUI.util.assert(pane, "SimplePane.getPaneAndKey", "pane #{pn} not found.")
[ pane, m[2] ]
empty: (key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.empty(_key)
@
append: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.append(content, _key)
@
replace: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.replace(content, _key)
@
| true | ###
* coffeescript-ui - Coffeescript User Interface System (CUI)
* Copyright (c) 2013 - 2016 Programmfabrik GmbH
* MIT Licence
* https://github.com/programmfabrik/coffeescript-ui, http://www.coffeescript-ui.org
###
# Pane with Header and Footer
class CUI.SimplePane extends CUI.Pane
# @param [Object] options for pane creation
# @option options [Array, Element, jQuery] header_left access the "left" of the PaneHeader
# @option options [Array, Element, jQuery] header_center access the "center" of the PaneHeader
# @option options [Array, Element, jQuery] header_right access the "right" of the PaneHeader
# @option options [Array, Element, jQuery] footer_left access the "left" of the PaneFooter
# @option options [Array, Element, jQuery] footer_right access the "right" of the PaneFooter
__init: ->
super()
for k in [
"header_left"
"header_center"
"header_right"
"footer_left"
"footer_center"
"footer_right"
]
value = @["_#{k}"]
if not value
continue
@append(value, k)
if @_title
@append(new CUI.Label(text: @_title), "header_left")
if not CUI.__ng__
@addClass("cui-simple-pane")
initOpts: ->
super()
@addOpts
title: {}
header_right: {}
header_center: {}
header_left: {}
footer_left: {}
footer_center: {}
footer_right: {}
content: {}
force_header:
mandatory: true
check: Boolean
default: false
force_footer:
mandatory: true
check: Boolean
default: false
@removeOpt("top")
@removeOpt("bottom")
@removeOpt("center")
@
readOpts: ->
# Skip readOpts from Pane as it sets defaults in top and bottom
# which is not allowed in our initOpts
CUI.VerticalLayout::readOpts.call(@)
if @_title
CUI.util.assert(not @_header_left, "new CUI.SimplePane", "opts.header_left conflicts with opts.title", opts: @opts)
if @forceHeader() or
not (CUI.util.isUndef(@_header_left) and CUI.util.isUndef(@_header_center) and CUI.util.isUndef(@_header_right)) or
@_title
@__pane_header = new CUI.PaneHeader()
@_top =
content: @__pane_header
if @forceFooter() or not (CUI.util.isUndef(@_footer_left) and CUI.util.isUndef(@_footer_center) and CUI.util.isUndef(@_footer_right))
@__pane_footer = new CUI.PaneFooter()
@_bottom =
content: @__pane_footer
@_center =
content: @_content
@
forceHeader: ->
@_force_header
forceFooter: ->
@_force_footer
hasHeader: ->
!!@__pane_header
hasFooter: ->
!!@__pane_footer
destroy: ->
@__pane_header?.destroy()
@__pane_header = null
@__pane_footer?.destroy()
@__pane_footer = null
super()
getPaneAndKey: (key) ->
# this reaches the panels directly
if key in ["PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI", "PI:KEY:<KEY>END_PI"]
[ @getLayout(), key ]
else if key == "content"
[ @getLayout(), "center" ]
else
m = key.match(/^(.*?)_(.*)$/)
CUI.util.assert(m?.length==3, "SimplePane.getPaneAndKey", "key #{key} not matched.", matched: m)
pn = "__pane_#{m?[1]}"
pane = @[pn]
CUI.util.assert(pane, "SimplePane.getPaneAndKey", "pane #{pn} not found.")
[ pane, m[2] ]
empty: (key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.empty(_key)
@
append: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.append(content, _key)
@
replace: (content, key="center") ->
[ pane, _key ] = @getPaneAndKey(key)
pane.replace(content, _key)
@
|
[
{
"context": "edirectUrl?\n # username = this.readCookie('username')\n # password = this.readCookie('password'",
"end": 477,
"score": 0.9521163702011108,
"start": 469,
"tag": "USERNAME",
"value": "username"
},
{
"context": "rname, password) ->\n user =\n use... | client/src/login/login-view.coffee | Studyokee/studyokee-youtube | 0 | define [
'backbone',
'handlebars',
'purl',
'templates'
], (Backbone, Handlebars, Purl) ->
LoginView = Backbone.View.extend(
className: "container"
initialize: () ->
render: () ->
this.$el.html(Handlebars.templates['login'](this.model.toJSON()))
# if this is a redirect, try logging in from cookies and redirect
params = $.url(document.location).param()
# if params.redirectUrl?
# username = this.readCookie('username')
# password = this.readCookie('password')
# if username? and password?
# this.$('.mask').show()
# this.login(username, password)
this.$('#login').on('submit', (event) =>
username = this.$('#username').val()
password = this.$('#password').val()
this.login(username, password)
event.preventDefault()
)
return this
login: (username, password) ->
user =
username: username
password: password
$.ajax(
type: 'POST'
url: '/login'
data: user
success: (response) =>
console.log('Success!')
params = $.url(document.location).param()
redirectUrl = '/classrooms/language/es/en'
if params.redirectUrl?
redirectUrl = params.redirectUrl + document.location.hash
this.setCookie('username', username)
this.setCookie('password', password)
document.location = redirectUrl
error: (err) =>
console.log('Error: ' + err.responseText)
this.$('.login-mask').hide()
)
readCookie: (name) ->
nameEQ = name + '='
ca = document.cookie.split(';')
for c in ca
while c.charAt(0) is ' '
c = c.substring(1,c.length)
if c.indexOf(nameEQ) is 0
return c.substring(nameEQ.length,c.length)
return null
setCookie: (name, value) ->
document.cookie = name + '=' + value + '; Path=/;'
deleteCookie: (name) ->
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
)
return LoginView | 164100 | define [
'backbone',
'handlebars',
'purl',
'templates'
], (Backbone, Handlebars, Purl) ->
LoginView = Backbone.View.extend(
className: "container"
initialize: () ->
render: () ->
this.$el.html(Handlebars.templates['login'](this.model.toJSON()))
# if this is a redirect, try logging in from cookies and redirect
params = $.url(document.location).param()
# if params.redirectUrl?
# username = this.readCookie('username')
# password = this.readCookie('password')
# if username? and password?
# this.$('.mask').show()
# this.login(username, password)
this.$('#login').on('submit', (event) =>
username = this.$('#username').val()
password = this.$('#password').val()
this.login(username, password)
event.preventDefault()
)
return this
login: (username, password) ->
user =
username: username
password: <PASSWORD>
$.ajax(
type: 'POST'
url: '/login'
data: user
success: (response) =>
console.log('Success!')
params = $.url(document.location).param()
redirectUrl = '/classrooms/language/es/en'
if params.redirectUrl?
redirectUrl = params.redirectUrl + document.location.hash
this.setCookie('username', username)
this.setCookie('password', <PASSWORD>)
document.location = redirectUrl
error: (err) =>
console.log('Error: ' + err.responseText)
this.$('.login-mask').hide()
)
readCookie: (name) ->
nameEQ = name + '='
ca = document.cookie.split(';')
for c in ca
while c.charAt(0) is ' '
c = c.substring(1,c.length)
if c.indexOf(nameEQ) is 0
return c.substring(nameEQ.length,c.length)
return null
setCookie: (name, value) ->
document.cookie = name + '=' + value + '; Path=/;'
deleteCookie: (name) ->
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
)
return LoginView | true | define [
'backbone',
'handlebars',
'purl',
'templates'
], (Backbone, Handlebars, Purl) ->
LoginView = Backbone.View.extend(
className: "container"
initialize: () ->
render: () ->
this.$el.html(Handlebars.templates['login'](this.model.toJSON()))
# if this is a redirect, try logging in from cookies and redirect
params = $.url(document.location).param()
# if params.redirectUrl?
# username = this.readCookie('username')
# password = this.readCookie('password')
# if username? and password?
# this.$('.mask').show()
# this.login(username, password)
this.$('#login').on('submit', (event) =>
username = this.$('#username').val()
password = this.$('#password').val()
this.login(username, password)
event.preventDefault()
)
return this
login: (username, password) ->
user =
username: username
password: PI:PASSWORD:<PASSWORD>END_PI
$.ajax(
type: 'POST'
url: '/login'
data: user
success: (response) =>
console.log('Success!')
params = $.url(document.location).param()
redirectUrl = '/classrooms/language/es/en'
if params.redirectUrl?
redirectUrl = params.redirectUrl + document.location.hash
this.setCookie('username', username)
this.setCookie('password', PI:PASSWORD:<PASSWORD>END_PI)
document.location = redirectUrl
error: (err) =>
console.log('Error: ' + err.responseText)
this.$('.login-mask').hide()
)
readCookie: (name) ->
nameEQ = name + '='
ca = document.cookie.split(';')
for c in ca
while c.charAt(0) is ' '
c = c.substring(1,c.length)
if c.indexOf(nameEQ) is 0
return c.substring(nameEQ.length,c.length)
return null
setCookie: (name, value) ->
document.cookie = name + '=' + value + '; Path=/;'
deleteCookie: (name) ->
document.cookie = name +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;'
)
return LoginView |
[
{
"context": "kflows-for-dev-only').create\n display_name: 'Test workflow'\n tasks:\n cool:\n ty",
"end": 6662,
"score": 0.5608497858047485,
"start": 6658,
"tag": "NAME",
"value": "Test"
}
] | app/components/workflow-tasks-editor.cjsx | mbiesiad/Panoptes-Front-End | 72 | React = require 'react'
createReactClass = require 'create-react-class'
ChangeListener = require './change-listener'
handleInputChange = require('../lib/handle-input-change').default
AnswerEditor = createReactClass
displayName: 'AnswerEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.label" value={@props.answer.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
{if @props.task.type is 'single'
<span>
<label>
{nextValue = @props.answer.next ? JSON.stringify(@props.answer.next) ? 'undefined'; null}
Next task <select name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.next" value={nextValue} onChange={handleInputChange.bind @props.workflow}>
<option value="undefined" data-delete-value>(Next in line)</option>
{for key, task of @props.workflow.tasks
<option key={key} value={key}>{"#{task.question ? task.instruction || '· · ·'} (#{key})"}</option>}
<option value="null" data-json-value>(End classification)</option>
</select>
</label>
</span>}
</div>
</div>
QuestionTaskEditor = createReactClass
displayName: 'QuestionTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Question</span>
<br />
<textarea name="tasks.#{@props.taskKey}.question" value={@props.task.question} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Answers</span>
<label className="inline-input">
<input type="checkbox" checked={@props.task.type is 'multiple' || null} onChange={@handleChangeMultiple} />
Allow multiple
</label>
<br />
<div className="answers-list">
{for answer, i in @props.task.answers ? []
<AnswerEditor key={i} {...@props} answerIndex={i} answer={answer} remove={@removeAnswer.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addAnswer}>Add a new answer</button>
</div>
</div>
</div>
handleChangeMultiple: (e) ->
@props.task.type = if e.target.checked
'multiple'
else
'single'
@props.workflow.update 'tasks'
addAnswer: ->
@props.task.answers ?= []
@props.task.answers.push
label: ''
next: null
@props.workflow.update 'tasks'
removeAnswer: (index) ->
@props.task.answers.splice index, 1
@props.workflow.update 'tasks'
ToolEditor = createReactClass
displayName: 'ToolEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.label" value={@props.tool.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
<span>
<label>
Shape <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.shape" value={@props.tool.shape} onChange={handleInputChange.bind @props.workflow}>
<option value="point">Point</option>
<option value="ellipse">Ellipse</option>
</select>
</label>
</span>
<span>
<label>
Color <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.color" value={@props.tool.color} onChange={handleInputChange.bind @props.workflow}>
<option value="">(Default)</option>
<option value="#f00">Red</option>
<option value="#ff0">Yellow</option>
<option value="#0f0">Green</option>
<option value="#0ff">Cyan</option>
<option value="#00f">Blue</option>
<option value="#f0f">Magenta</option>
</select>
</label>
</span>
</div>
</div>
DrawingTaskEditor = createReactClass
displayName: 'DrawingTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Instruction</span>
<br />
<textarea name="tasks.#{@props.taskKey}.instruction" value={@props.task.instruction} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Features to mark</span>
<br />
<div className="answers-list">
{for tool, i in @props.task.tools ? []
<ToolEditor key={i} {...@props} toolIndex={i} tool={tool} remove={@removeTool.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addTool}>Add a new tool</button>
</div>
</div>
</div>
addTool: ->
@props.task.tools ?= []
@props.task.tools.push
label: ''
shape: 'point'
color: null
@props.workflow.update 'tasks'
removeTool: (index) ->
@props.task.tools.splice index, 1
@props.workflow.update 'tasks'
TaskEditor = createReactClass
displayName: 'TaskEditor'
render: ->
task = @props.workflow.tasks[@props.taskKey]
TaskComponent = switch task.type
when 'single', 'multiple' then QuestionTaskEditor
when 'drawing' then DrawingTaskEditor
<div className="task">
<div className="controls">
{@props.taskKey} <button type="button" onClick={@props.remove}>×</button>
</div>
<TaskComponent {...@props} task={task} />
</div>
module.exports = createReactClass
displayName: 'WorkflowEditor'
statics:
willTransitionFrom: (transition, component) ->
if component.props.workflow.hasUnsavedChanges()
transition.abort()
if confirm 'You have unsaved changes that will be lost forever. Do you really want to leave the workflow editor?'
transition.retry()
getDefaultProps: ->
apiClient = require 'panoptes-client/lib/api-client'
workflow: apiClient.type('workflows-for-dev-only').create
display_name: 'Test workflow'
tasks:
cool:
type: 'single'
question: 'Cool?'
answers: [
label: 'Yep'
]
first_task: 'cool'
getInitialState: ->
view: 'editor'
render: ->
<ChangeListener target={@props.workflow} eventName="change" handler={@renderWorkflow} />
renderWorkflow: ->
window.workflow = @props.workflow
view = switch @state.view
when 'editor' then @renderEditor
when 'code' then @renderCode
<div className="workflow-editor-container">
<div className="controls">
<button onClick={@setState.bind this, view: 'editor', null}><i className="fa fa-pencil fa-fw"></i></button>
<button onClick={@setState.bind this, view: 'code', null}><i className="fa fa-code fa-fw"></i></button>
</div>
<br />
{view()}
</div>
renderEditor: ->
<div className="workflow-editor">
<div className="task-list">
{for taskKey in @getTaskKeysInOrder()
<TaskEditor key={taskKey} taskKey={taskKey} workflow={@props.workflow} remove={@removeTask.bind this, taskKey} />}
</div>
<span className="field-label">Add a new task</span>
<br />
<div className="adder-container">
<button type="button" className="adder" onClick={@addNewTask.bind this, 'single'}>Question</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'drawing'}>Marking</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'survey'} disabled>Image survey</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'flexibleSurvey'} disabled>Flexible Image Survey</button>
</div>
</div>
renderCode: ->
<div className="workflow-editor-code-view">
<pre>{JSON.stringify @props.workflow.tasks, null, 2}</pre>
</div>
getTaskKeysInOrder: ->
order = []
key = @props.workflow.first_task
while key?
order.push key
key = @props.workflow.tasks[key].next
order
addNewTask: (type) ->
lastTaskKey = @getTaskKeysInOrder().pop()
newTaskKey = Math.random().toString(16).split('.')[1]
@props.workflow.tasks ?= {}
@props.workflow.tasks[newTaskKey] = {type}
if lastTaskKey?
@props.workflow.tasks[lastTaskKey].next = newTaskKey
else
@props.workflow.first_task = newTaskKey
@props.workflow.update 'tasks'
removeTask: (taskKey) ->
for key, task of @props.workflow.tasks
# Remove the task from any task that declares it the next.
if task.next is taskKey
delete task.next
if task.answers?
# Remove the task from any answer that declares it the next.
for answer in task.answers when answer.next is taskKey
delete answer.next
# Find a new first task, if we're removing the current one.
if taskKey is @props.workflow.first_task
@props.workflow.update first_task: @props.workflow.tasks[taskKey].next ? Object.keys(@props.workflow.tasks)[0]
delete @props.workflow.tasks[taskKey]
@props.workflow.update 'tasks'
| 123130 | React = require 'react'
createReactClass = require 'create-react-class'
ChangeListener = require './change-listener'
handleInputChange = require('../lib/handle-input-change').default
AnswerEditor = createReactClass
displayName: 'AnswerEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.label" value={@props.answer.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
{if @props.task.type is 'single'
<span>
<label>
{nextValue = @props.answer.next ? JSON.stringify(@props.answer.next) ? 'undefined'; null}
Next task <select name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.next" value={nextValue} onChange={handleInputChange.bind @props.workflow}>
<option value="undefined" data-delete-value>(Next in line)</option>
{for key, task of @props.workflow.tasks
<option key={key} value={key}>{"#{task.question ? task.instruction || '· · ·'} (#{key})"}</option>}
<option value="null" data-json-value>(End classification)</option>
</select>
</label>
</span>}
</div>
</div>
QuestionTaskEditor = createReactClass
displayName: 'QuestionTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Question</span>
<br />
<textarea name="tasks.#{@props.taskKey}.question" value={@props.task.question} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Answers</span>
<label className="inline-input">
<input type="checkbox" checked={@props.task.type is 'multiple' || null} onChange={@handleChangeMultiple} />
Allow multiple
</label>
<br />
<div className="answers-list">
{for answer, i in @props.task.answers ? []
<AnswerEditor key={i} {...@props} answerIndex={i} answer={answer} remove={@removeAnswer.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addAnswer}>Add a new answer</button>
</div>
</div>
</div>
handleChangeMultiple: (e) ->
@props.task.type = if e.target.checked
'multiple'
else
'single'
@props.workflow.update 'tasks'
addAnswer: ->
@props.task.answers ?= []
@props.task.answers.push
label: ''
next: null
@props.workflow.update 'tasks'
removeAnswer: (index) ->
@props.task.answers.splice index, 1
@props.workflow.update 'tasks'
ToolEditor = createReactClass
displayName: 'ToolEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.label" value={@props.tool.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
<span>
<label>
Shape <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.shape" value={@props.tool.shape} onChange={handleInputChange.bind @props.workflow}>
<option value="point">Point</option>
<option value="ellipse">Ellipse</option>
</select>
</label>
</span>
<span>
<label>
Color <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.color" value={@props.tool.color} onChange={handleInputChange.bind @props.workflow}>
<option value="">(Default)</option>
<option value="#f00">Red</option>
<option value="#ff0">Yellow</option>
<option value="#0f0">Green</option>
<option value="#0ff">Cyan</option>
<option value="#00f">Blue</option>
<option value="#f0f">Magenta</option>
</select>
</label>
</span>
</div>
</div>
DrawingTaskEditor = createReactClass
displayName: 'DrawingTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Instruction</span>
<br />
<textarea name="tasks.#{@props.taskKey}.instruction" value={@props.task.instruction} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Features to mark</span>
<br />
<div className="answers-list">
{for tool, i in @props.task.tools ? []
<ToolEditor key={i} {...@props} toolIndex={i} tool={tool} remove={@removeTool.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addTool}>Add a new tool</button>
</div>
</div>
</div>
addTool: ->
@props.task.tools ?= []
@props.task.tools.push
label: ''
shape: 'point'
color: null
@props.workflow.update 'tasks'
removeTool: (index) ->
@props.task.tools.splice index, 1
@props.workflow.update 'tasks'
TaskEditor = createReactClass
displayName: 'TaskEditor'
render: ->
task = @props.workflow.tasks[@props.taskKey]
TaskComponent = switch task.type
when 'single', 'multiple' then QuestionTaskEditor
when 'drawing' then DrawingTaskEditor
<div className="task">
<div className="controls">
{@props.taskKey} <button type="button" onClick={@props.remove}>×</button>
</div>
<TaskComponent {...@props} task={task} />
</div>
module.exports = createReactClass
displayName: 'WorkflowEditor'
statics:
willTransitionFrom: (transition, component) ->
if component.props.workflow.hasUnsavedChanges()
transition.abort()
if confirm 'You have unsaved changes that will be lost forever. Do you really want to leave the workflow editor?'
transition.retry()
getDefaultProps: ->
apiClient = require 'panoptes-client/lib/api-client'
workflow: apiClient.type('workflows-for-dev-only').create
display_name: '<NAME> workflow'
tasks:
cool:
type: 'single'
question: 'Cool?'
answers: [
label: 'Yep'
]
first_task: 'cool'
getInitialState: ->
view: 'editor'
render: ->
<ChangeListener target={@props.workflow} eventName="change" handler={@renderWorkflow} />
renderWorkflow: ->
window.workflow = @props.workflow
view = switch @state.view
when 'editor' then @renderEditor
when 'code' then @renderCode
<div className="workflow-editor-container">
<div className="controls">
<button onClick={@setState.bind this, view: 'editor', null}><i className="fa fa-pencil fa-fw"></i></button>
<button onClick={@setState.bind this, view: 'code', null}><i className="fa fa-code fa-fw"></i></button>
</div>
<br />
{view()}
</div>
renderEditor: ->
<div className="workflow-editor">
<div className="task-list">
{for taskKey in @getTaskKeysInOrder()
<TaskEditor key={taskKey} taskKey={taskKey} workflow={@props.workflow} remove={@removeTask.bind this, taskKey} />}
</div>
<span className="field-label">Add a new task</span>
<br />
<div className="adder-container">
<button type="button" className="adder" onClick={@addNewTask.bind this, 'single'}>Question</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'drawing'}>Marking</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'survey'} disabled>Image survey</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'flexibleSurvey'} disabled>Flexible Image Survey</button>
</div>
</div>
renderCode: ->
<div className="workflow-editor-code-view">
<pre>{JSON.stringify @props.workflow.tasks, null, 2}</pre>
</div>
getTaskKeysInOrder: ->
order = []
key = @props.workflow.first_task
while key?
order.push key
key = @props.workflow.tasks[key].next
order
addNewTask: (type) ->
lastTaskKey = @getTaskKeysInOrder().pop()
newTaskKey = Math.random().toString(16).split('.')[1]
@props.workflow.tasks ?= {}
@props.workflow.tasks[newTaskKey] = {type}
if lastTaskKey?
@props.workflow.tasks[lastTaskKey].next = newTaskKey
else
@props.workflow.first_task = newTaskKey
@props.workflow.update 'tasks'
removeTask: (taskKey) ->
for key, task of @props.workflow.tasks
# Remove the task from any task that declares it the next.
if task.next is taskKey
delete task.next
if task.answers?
# Remove the task from any answer that declares it the next.
for answer in task.answers when answer.next is taskKey
delete answer.next
# Find a new first task, if we're removing the current one.
if taskKey is @props.workflow.first_task
@props.workflow.update first_task: @props.workflow.tasks[taskKey].next ? Object.keys(@props.workflow.tasks)[0]
delete @props.workflow.tasks[taskKey]
@props.workflow.update 'tasks'
| true | React = require 'react'
createReactClass = require 'create-react-class'
ChangeListener = require './change-listener'
handleInputChange = require('../lib/handle-input-change').default
AnswerEditor = createReactClass
displayName: 'AnswerEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.label" value={@props.answer.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
{if @props.task.type is 'single'
<span>
<label>
{nextValue = @props.answer.next ? JSON.stringify(@props.answer.next) ? 'undefined'; null}
Next task <select name="tasks.#{@props.taskKey}.answers.#{@props.answerIndex}.next" value={nextValue} onChange={handleInputChange.bind @props.workflow}>
<option value="undefined" data-delete-value>(Next in line)</option>
{for key, task of @props.workflow.tasks
<option key={key} value={key}>{"#{task.question ? task.instruction || '· · ·'} (#{key})"}</option>}
<option value="null" data-json-value>(End classification)</option>
</select>
</label>
</span>}
</div>
</div>
QuestionTaskEditor = createReactClass
displayName: 'QuestionTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Question</span>
<br />
<textarea name="tasks.#{@props.taskKey}.question" value={@props.task.question} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Answers</span>
<label className="inline-input">
<input type="checkbox" checked={@props.task.type is 'multiple' || null} onChange={@handleChangeMultiple} />
Allow multiple
</label>
<br />
<div className="answers-list">
{for answer, i in @props.task.answers ? []
<AnswerEditor key={i} {...@props} answerIndex={i} answer={answer} remove={@removeAnswer.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addAnswer}>Add a new answer</button>
</div>
</div>
</div>
handleChangeMultiple: (e) ->
@props.task.type = if e.target.checked
'multiple'
else
'single'
@props.workflow.update 'tasks'
addAnswer: ->
@props.task.answers ?= []
@props.task.answers.push
label: ''
next: null
@props.workflow.update 'tasks'
removeAnswer: (index) ->
@props.task.answers.splice index, 1
@props.workflow.update 'tasks'
ToolEditor = createReactClass
displayName: 'ToolEditor'
render: ->
<div className="answer">
<div className="controls">
<button type="button" className="delete-answer" onClick={@props.remove}>×</button>
</div>
<label>
<span className="field-label">Label</span>
<br />
<textarea name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.label" value={@props.tool.label} onChange={handleInputChange.bind @props.workflow} rows="1" style={width: '100%'} />
</label>
<br />
<div className="answer-properties">
<span>
<label>
Shape <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.shape" value={@props.tool.shape} onChange={handleInputChange.bind @props.workflow}>
<option value="point">Point</option>
<option value="ellipse">Ellipse</option>
</select>
</label>
</span>
<span>
<label>
Color <select name="tasks.#{@props.taskKey}.tools.#{@props.toolIndex}.color" value={@props.tool.color} onChange={handleInputChange.bind @props.workflow}>
<option value="">(Default)</option>
<option value="#f00">Red</option>
<option value="#ff0">Yellow</option>
<option value="#0f0">Green</option>
<option value="#0ff">Cyan</option>
<option value="#00f">Blue</option>
<option value="#f0f">Magenta</option>
</select>
</label>
</span>
</div>
</div>
DrawingTaskEditor = createReactClass
displayName: 'DrawingTaskEditor'
render: ->
<div>
<label>
<span className="field-label">Instruction</span>
<br />
<textarea name="tasks.#{@props.taskKey}.instruction" value={@props.task.instruction} onChange={handleInputChange.bind @props.workflow} rows="2" style={width: '100%'} />
</label>
<br />
<span className="field-label">Features to mark</span>
<br />
<div className="answers-list">
{for tool, i in @props.task.tools ? []
<ToolEditor key={i} {...@props} toolIndex={i} tool={tool} remove={@removeTool.bind this, i} />}
<div className="adder-container">
<button type="button" className="adder" onClick={@addTool}>Add a new tool</button>
</div>
</div>
</div>
addTool: ->
@props.task.tools ?= []
@props.task.tools.push
label: ''
shape: 'point'
color: null
@props.workflow.update 'tasks'
removeTool: (index) ->
@props.task.tools.splice index, 1
@props.workflow.update 'tasks'
TaskEditor = createReactClass
displayName: 'TaskEditor'
render: ->
task = @props.workflow.tasks[@props.taskKey]
TaskComponent = switch task.type
when 'single', 'multiple' then QuestionTaskEditor
when 'drawing' then DrawingTaskEditor
<div className="task">
<div className="controls">
{@props.taskKey} <button type="button" onClick={@props.remove}>×</button>
</div>
<TaskComponent {...@props} task={task} />
</div>
module.exports = createReactClass
displayName: 'WorkflowEditor'
statics:
willTransitionFrom: (transition, component) ->
if component.props.workflow.hasUnsavedChanges()
transition.abort()
if confirm 'You have unsaved changes that will be lost forever. Do you really want to leave the workflow editor?'
transition.retry()
getDefaultProps: ->
apiClient = require 'panoptes-client/lib/api-client'
workflow: apiClient.type('workflows-for-dev-only').create
display_name: 'PI:NAME:<NAME>END_PI workflow'
tasks:
cool:
type: 'single'
question: 'Cool?'
answers: [
label: 'Yep'
]
first_task: 'cool'
getInitialState: ->
view: 'editor'
render: ->
<ChangeListener target={@props.workflow} eventName="change" handler={@renderWorkflow} />
renderWorkflow: ->
window.workflow = @props.workflow
view = switch @state.view
when 'editor' then @renderEditor
when 'code' then @renderCode
<div className="workflow-editor-container">
<div className="controls">
<button onClick={@setState.bind this, view: 'editor', null}><i className="fa fa-pencil fa-fw"></i></button>
<button onClick={@setState.bind this, view: 'code', null}><i className="fa fa-code fa-fw"></i></button>
</div>
<br />
{view()}
</div>
renderEditor: ->
<div className="workflow-editor">
<div className="task-list">
{for taskKey in @getTaskKeysInOrder()
<TaskEditor key={taskKey} taskKey={taskKey} workflow={@props.workflow} remove={@removeTask.bind this, taskKey} />}
</div>
<span className="field-label">Add a new task</span>
<br />
<div className="adder-container">
<button type="button" className="adder" onClick={@addNewTask.bind this, 'single'}>Question</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'drawing'}>Marking</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'survey'} disabled>Image survey</button>
<button type="button" className="adder" onClick={@addNewTask.bind this, 'flexibleSurvey'} disabled>Flexible Image Survey</button>
</div>
</div>
renderCode: ->
<div className="workflow-editor-code-view">
<pre>{JSON.stringify @props.workflow.tasks, null, 2}</pre>
</div>
getTaskKeysInOrder: ->
order = []
key = @props.workflow.first_task
while key?
order.push key
key = @props.workflow.tasks[key].next
order
addNewTask: (type) ->
lastTaskKey = @getTaskKeysInOrder().pop()
newTaskKey = Math.random().toString(16).split('.')[1]
@props.workflow.tasks ?= {}
@props.workflow.tasks[newTaskKey] = {type}
if lastTaskKey?
@props.workflow.tasks[lastTaskKey].next = newTaskKey
else
@props.workflow.first_task = newTaskKey
@props.workflow.update 'tasks'
removeTask: (taskKey) ->
for key, task of @props.workflow.tasks
# Remove the task from any task that declares it the next.
if task.next is taskKey
delete task.next
if task.answers?
# Remove the task from any answer that declares it the next.
for answer in task.answers when answer.next is taskKey
delete answer.next
# Find a new first task, if we're removing the current one.
if taskKey is @props.workflow.first_task
@props.workflow.update first_task: @props.workflow.tasks[taskKey].next ? Object.keys(@props.workflow.tasks)[0]
delete @props.workflow.tasks[taskKey]
@props.workflow.update 'tasks'
|
[
{
"context": "STORAGE_KEY = 'hypothesis.privacy'\n\n###*\n# @ngdoc service\n# @name Permissions\n#\n# ",
"end": 33,
"score": 0.9861322045326233,
"start": 15,
"tag": "KEY",
"value": "hypothesis.privacy"
}
] | h/static/scripts/permissions.coffee | noscripter/h | 0 | STORAGE_KEY = 'hypothesis.privacy'
###*
# @ngdoc service
# @name Permissions
#
# @description
# This service can set default permissions to annotations properly and
# offers some utility functions regarding those.
###
module.exports = ['session', 'localStorage', (session, localStorage) ->
ALL_PERMISSIONS = {}
GROUP_WORLD = 'group:__world__'
ADMIN_PARTY = [{
allow: true
principal: GROUP_WORLD
action: ALL_PERMISSIONS
}]
# Creates access control list from context.permissions
_acl = (context) ->
parts =
for action, roles of context.permissions or []
for role in roles
allow: true
principal: role
action: action
if parts.length
Array::concat parts...
else
ADMIN_PARTY
###*
# @ngdoc method
# @name permissions#private
#
# Sets permissions for a private annotation
# Typical use: annotation.permissions = permissions.private()
###
private: ->
if not session.state.userid
return null
else
return {
read: [session.state.userid]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
###*
# @ngdoc method
# @name permissions#shared
#
# @param {String} [group] Group to make annotation shared in.
#
# Sets permissions for a shared annotation
# Typical use: annotation.permissions = permissions.shared(group)
###
shared: (group) ->
if not session.state.userid
return null
if group?
group = 'group:' + group
else
group = GROUP_WORLD
return {
read: [group]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
# Return the initial permissions for a new annotation in the given group.
default: (group) ->
defaultLevel = localStorage.getItem(STORAGE_KEY);
if (defaultLevel != 'private') and (defaultLevel != 'shared')
defaultLevel = 'shared';
if defaultLevel == 'private'
return this.private()
else
return this.shared(group)
# Set the default initial permissions for new annotations (that will be
# returned by default() above) to "private" or "shared" permissions.
#
# @param {string} private_or_shared "private" to make default() return the
# necessary permissions for private annotations, "shared" to make it
# return those for shared annotations.
setDefault: (private_or_shared) ->
localStorage.setItem(STORAGE_KEY, private_or_shared);
###*
# @ngdoc method
# @name permissions#isShared
#
# @param {Object} permissions
# @param {String} [group]
#
# This function determines whether the permissions allow shared visibility
###
isShared: (permissions, group) ->
if group?
group = 'group:' + group
else
group = GROUP_WORLD
group in (permissions?.read or [])
###*
# @ngdoc method
# @name permissions#isPrivate
#
# @param {Object} permissions
# @param {String} user
#
# @returns {boolean} True if the annotation is private to the user.
###
isPrivate: (permissions, user) ->
user and angular.equals(permissions?.read or [], [user])
###*
# @ngdoc method
# @name permissions#permits
#
# @param {String} action action to authorize (read|update|delete|admin)
# @param {Object} context to permit action on it or not
# @param {String} user the userId
#
# User access-level-control function
# TODO: this should move to the auth service and take multiple principals
###
permits: (action, context, user) ->
acl = _acl context
for ace in acl
if ace.principal not in [user, GROUP_WORLD]
continue
if ace.action not in [action, ALL_PERMISSIONS]
continue
return ace.allow
false
]
| 7025 | STORAGE_KEY = '<KEY>'
###*
# @ngdoc service
# @name Permissions
#
# @description
# This service can set default permissions to annotations properly and
# offers some utility functions regarding those.
###
module.exports = ['session', 'localStorage', (session, localStorage) ->
ALL_PERMISSIONS = {}
GROUP_WORLD = 'group:__world__'
ADMIN_PARTY = [{
allow: true
principal: GROUP_WORLD
action: ALL_PERMISSIONS
}]
# Creates access control list from context.permissions
_acl = (context) ->
parts =
for action, roles of context.permissions or []
for role in roles
allow: true
principal: role
action: action
if parts.length
Array::concat parts...
else
ADMIN_PARTY
###*
# @ngdoc method
# @name permissions#private
#
# Sets permissions for a private annotation
# Typical use: annotation.permissions = permissions.private()
###
private: ->
if not session.state.userid
return null
else
return {
read: [session.state.userid]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
###*
# @ngdoc method
# @name permissions#shared
#
# @param {String} [group] Group to make annotation shared in.
#
# Sets permissions for a shared annotation
# Typical use: annotation.permissions = permissions.shared(group)
###
shared: (group) ->
if not session.state.userid
return null
if group?
group = 'group:' + group
else
group = GROUP_WORLD
return {
read: [group]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
# Return the initial permissions for a new annotation in the given group.
default: (group) ->
defaultLevel = localStorage.getItem(STORAGE_KEY);
if (defaultLevel != 'private') and (defaultLevel != 'shared')
defaultLevel = 'shared';
if defaultLevel == 'private'
return this.private()
else
return this.shared(group)
# Set the default initial permissions for new annotations (that will be
# returned by default() above) to "private" or "shared" permissions.
#
# @param {string} private_or_shared "private" to make default() return the
# necessary permissions for private annotations, "shared" to make it
# return those for shared annotations.
setDefault: (private_or_shared) ->
localStorage.setItem(STORAGE_KEY, private_or_shared);
###*
# @ngdoc method
# @name permissions#isShared
#
# @param {Object} permissions
# @param {String} [group]
#
# This function determines whether the permissions allow shared visibility
###
isShared: (permissions, group) ->
if group?
group = 'group:' + group
else
group = GROUP_WORLD
group in (permissions?.read or [])
###*
# @ngdoc method
# @name permissions#isPrivate
#
# @param {Object} permissions
# @param {String} user
#
# @returns {boolean} True if the annotation is private to the user.
###
isPrivate: (permissions, user) ->
user and angular.equals(permissions?.read or [], [user])
###*
# @ngdoc method
# @name permissions#permits
#
# @param {String} action action to authorize (read|update|delete|admin)
# @param {Object} context to permit action on it or not
# @param {String} user the userId
#
# User access-level-control function
# TODO: this should move to the auth service and take multiple principals
###
permits: (action, context, user) ->
acl = _acl context
for ace in acl
if ace.principal not in [user, GROUP_WORLD]
continue
if ace.action not in [action, ALL_PERMISSIONS]
continue
return ace.allow
false
]
| true | STORAGE_KEY = 'PI:KEY:<KEY>END_PI'
###*
# @ngdoc service
# @name Permissions
#
# @description
# This service can set default permissions to annotations properly and
# offers some utility functions regarding those.
###
module.exports = ['session', 'localStorage', (session, localStorage) ->
ALL_PERMISSIONS = {}
GROUP_WORLD = 'group:__world__'
ADMIN_PARTY = [{
allow: true
principal: GROUP_WORLD
action: ALL_PERMISSIONS
}]
# Creates access control list from context.permissions
_acl = (context) ->
parts =
for action, roles of context.permissions or []
for role in roles
allow: true
principal: role
action: action
if parts.length
Array::concat parts...
else
ADMIN_PARTY
###*
# @ngdoc method
# @name permissions#private
#
# Sets permissions for a private annotation
# Typical use: annotation.permissions = permissions.private()
###
private: ->
if not session.state.userid
return null
else
return {
read: [session.state.userid]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
###*
# @ngdoc method
# @name permissions#shared
#
# @param {String} [group] Group to make annotation shared in.
#
# Sets permissions for a shared annotation
# Typical use: annotation.permissions = permissions.shared(group)
###
shared: (group) ->
if not session.state.userid
return null
if group?
group = 'group:' + group
else
group = GROUP_WORLD
return {
read: [group]
update: [session.state.userid]
delete: [session.state.userid]
admin: [session.state.userid]
}
# Return the initial permissions for a new annotation in the given group.
default: (group) ->
defaultLevel = localStorage.getItem(STORAGE_KEY);
if (defaultLevel != 'private') and (defaultLevel != 'shared')
defaultLevel = 'shared';
if defaultLevel == 'private'
return this.private()
else
return this.shared(group)
# Set the default initial permissions for new annotations (that will be
# returned by default() above) to "private" or "shared" permissions.
#
# @param {string} private_or_shared "private" to make default() return the
# necessary permissions for private annotations, "shared" to make it
# return those for shared annotations.
setDefault: (private_or_shared) ->
localStorage.setItem(STORAGE_KEY, private_or_shared);
###*
# @ngdoc method
# @name permissions#isShared
#
# @param {Object} permissions
# @param {String} [group]
#
# This function determines whether the permissions allow shared visibility
###
isShared: (permissions, group) ->
if group?
group = 'group:' + group
else
group = GROUP_WORLD
group in (permissions?.read or [])
###*
# @ngdoc method
# @name permissions#isPrivate
#
# @param {Object} permissions
# @param {String} user
#
# @returns {boolean} True if the annotation is private to the user.
###
isPrivate: (permissions, user) ->
user and angular.equals(permissions?.read or [], [user])
###*
# @ngdoc method
# @name permissions#permits
#
# @param {String} action action to authorize (read|update|delete|admin)
# @param {Object} context to permit action on it or not
# @param {String} user the userId
#
# User access-level-control function
# TODO: this should move to the auth service and take multiple principals
###
permits: (action, context, user) ->
acl = _acl context
for ace in acl
if ace.principal not in [user, GROUP_WORLD]
continue
if ace.action not in [action, ALL_PERMISSIONS]
continue
return ace.allow
false
]
|
[
{
"context": "reate-member'\n scope.profile.password = '888888'\n #创建成员成功后1.关闭弹窗 2.更新本地数据. 3.添加该成员到这个项目中",
"end": 1743,
"score": 0.9993040561676025,
"start": 1737,
"tag": "PASSWORD",
"value": "888888"
}
] | src/js/member/member-directives.coffee | Kiteam/kiteam-angular | 0 | define [
'../ng-module'
'../utils'
'./views/member-all.html'
'../../package/jquery.autocomplete/jquery.autocomplete'
'imports?jQuery=jquery!../vendor/jquery.modal'
], (_module, _utils, _template, _autocomplete) ->
_module.directiveModule
.directive('memberSetting', ['$rootScope', 'API', ($rootScope, API)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-setting', _template
link: (scope, element, attr)->
scope.activeIndex = 0
$o = $(element)
#接收事件后,加载数据并显示
$rootScope.$on 'member:setting:show', (event, index)->
scope.activeIndex = index
$o.modal showClose: false
scope.$broadcast "member:setting:bindAll"
scope.$broadcast "member:notification:bindAll"
$rootScope.$on 'member:setting:hide', ()->
$.modal.close()
])
.directive('memberProfile', ['$location', 'API', 'NOTIFY', '$rootScope',
($location, API, NOTIFY, $rootScope)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-profile', _template
link: (scope, element, attr)->
#定义下属组件的上下文名称
scope.contextName = 'memberProfile'
scope.bean = setGits: (data)-> scope.gits = data
scope.onClickSave = ()->
scope.profile.gits = scope.gits
return NOTIFY.warn '请输入您的邮箱' if not scope.profile.email
return NOTIFY.warn '用户名必需输入' if not scope.profile.username
if attr.action is 'account-profile'
API.account().profile().update(scope.profile).then(()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
)
if attr.action is 'create-member'
scope.profile.password = '888888'
#创建成员成功后1.关闭弹窗 2.更新本地数据. 3.添加该成员到这个项目中
API.member().create(scope.profile).then((result)->
NOTIFY.success '创建成员成功!'
#1.关闭弹窗
scope.$emit 'member:creator:hide'
#2.更新本地数据
$rootScope.$broadcast 'lookup:update'
#3.添加该成员到这个项目中
$rootScope.$broadcast 'member:created:save', result.id
)
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.$on 'member:setting:bindAll', ()->
API.account().profile().retrieve().then((result)->
scope.profile = result
scope.gits = _.map(result.gits, (item)-> item.git)
scope.$broadcast("gitList:load", scope.gits)
)
scope.$on('member:creator:bindAll', (event, data)->
scope.profile = data
scope.$apply()
return
)
])
.directive('memberChangePassword', ['$location', 'API', 'NOTIFY',
($location, API, NOTIFY)->
restrict: 'E'
replace: true
scope: true
template: _utils.extractTemplate '#tmpl-member-change-password', _template
link: (scope, element, attr)->
scope.profile = {}
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSave = ()->
if scope.profile.new_password isnt scope.profile.new_password2
NOTIFY.warn '您两次输入的密码不一致'
return
API.account().changePassword().update(scope.profile).then(()->
NOTIFY.success '您的密码修改成功!'
scope.profile = {}
scope.onClickCancel()
)
return
])
.directive('memberNotification', ['$location', 'API', '$stateParams', 'NOTIFY',
($location, API, $stateParams, NOTIFY)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-notification', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
scope.onClickSave = ()->
scope.profile.notification = JSON.stringify scope.profile.notification
API.account().profile().update(scope.profile).then ()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
scope.$on 'member:notification:bindAll', ()->
API.account().profile().retrieve().then (result)->
scope.profile = result
scope.profile.notification = JSON.parse result.notification if result.notification
scope.profile.notification.weixin = 1 if scope.profile.notification && !scope.profile.notification.weixin?
scope.profile.notification.realtime = 1 if scope.profile.notification && !scope.profile.notification.realtime?
scope.profile.notification.email = 1 if scope.profile.notification && !scope.profile.notification.email?
scope.profile.notification.client = 1 if scope.profile.notification && !scope.profile.notification.client?
])
#微信
.directive('memberWeixin', ['API', 'NOTIFY',
(API, NOTIFY)->
scope: {}
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-weixin', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSaveWeixin = ->
API.account().weixin().create({weixin: scope.weixin}).then(()->
NOTIFY.success '微信绑定成功!'
scope.onClickCancel()
)
return
])
#自动完成
.directive('membersLookup', ['$stateParams', 'API', 'STORE',
($stateParams, API, STORE)->
restrict: 'AC'
link: (scope, element, attrs)->
$this = $(element)
memberAPI = API.project($stateParams.project_id).member() if $stateParams.project_id
memberAPI = API.team($stateParams.team_id).member() if $stateParams.team_id
# API.get "project/#{$stateParams.project_id}"/member (result)->
#保存成员
addMember = (member_id)->
data = {member_id: member_id, role: "d",status: 0}
memberAPI.create(data).then ()->
$this.val("")
scope.selectSuggestion = ""
scope.$emit 'project:member:request' if $stateParams.project_id
scope.$emit 'team:member:request' if $stateParams.team_id
initLookup()
#创建成员
createMember = ()->
value = $this.val()
$this.val("")
scope.$emit('member:creator:toshow', value)
#回车事件
$this.on "keyup", (event)->
if event.keyCode is 13 and scope.selectSuggestion then addMember(scope.selectSuggestion)
if event.keyCode is 13 and not scope.selectSuggestion then createMember()
options =
lookup: []
showNoSuggestionNotice: true
noSuggestionNotice: '未找到该用户,按回车键添加该用户'
onSelect: (suggestion)->
scope.selectSuggestion = suggestion.data
#处理 lookup 数据
buildLookupData = (list) ->
memberAPI.retrieve().then (projectMemberList)->
_.remove(list, (item)->
result = _.findIndex(projectMemberList, (pItem)->
item.id is pItem.member_id) >= 0
if not result
item.value = "#{item.realname} -> #{item.username || '未设置'} -> #{item.email}"
item.data = item.id
delete item.realname
delete item.username
delete item.id
delete item.role
result
)
return list
#初始化lookup
initLookup = ()->
API.member().retrieve(pageSize: 9999).then (result)->
options.lookup = buildLookupData(result.items)
$this.autocomplete(options)
#当创建新成员后 初始化 lookup
scope.$on "lookup:update", ()->
initLookup()
#当创建新成员后,添加这个成员到该项目
scope.$on('member:created:save', (event, data)->
addMember(data)
)
#进入的时候初始化lookup
initLookup()
])
# 添加项目成员
.directive('memberCreatorModel', ['$location', 'API', ($location, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-creator', _template
link: (scope, element, attr)->
$o = $(element)
#接收事件后,加载数据并显示
scope.$on "member:creator:show", (event, data)->
scope.$broadcast('member:creator:bindAll', {username: data, realname: data})
$o.modal showClose: false
scope.$on 'member:creator:hide', ()->
$.modal.close()
])
#项目成员item project-member-item #api/project/39/member/1
.directive('projectMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-item', _template
link:(scope,element,attr)->
scope.removeProjectMember = (member)->
API.project($stateParams.project_id).member(member.member_id).delete().then ()->
scope.$emit 'project:member:request'
])
#项目成员角色 project-member-item #api/project/39/member/1/
.directive('projectMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'project-member-item' is name
API.project($stateParams.project_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'project:member:request'
])
#团队成员item team-member-item #api/project/39/member/1
.directive('teamMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-item', _template
link:(scope,element,attr)->
scope.removeTeamMember = (member)->
API.team($stateParams.team_id).member(member.member_id).delete().then ()->
scope.$emit 'team:member:request'
])
#团队成员角色 team-member-item #api/project/39/member/1/
.directive('teamMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'team-member-item' is name
API.team($stateParams.team_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'team:member:request'
])
#读取用户的消息
.directive('memberMessageNotifier', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-message-notifier', _template
link:(scope, element, attr)->
$dropdown = $(element).find 'div.message-list'
$dropdown.bind 'click', (event)-> event.stopPropagation()
$dropdown.bind 'mouseleave', -> scope.onCloseNotifier()
scope.onCloseNotifier = -> $dropdown.fadeOut()
scope.onClickNotifier = (event)->
event.stopPropagation()
$dropdown.fadeIn()
$('body').one 'click', -> scope.onCloseNotifier()
return
scope.onClickItem = (item, hide)->
scope.onCloseNotifier() if hide
API.message(item.id).update().then -> loadMessage()
scope.onClickReadAll = ()->
scope.onCloseNotifier()
API.message().update().then -> loadMessage()
#加载消息
loadMessage = ()->
API.message().retrieve(pageSize: 10, status: 'new').then (result)->
scope.message = result
#加载用户离线通知的事件
scope.$on 'member:message:reload', -> loadMessage()
loadMessage()
]) | 139546 | define [
'../ng-module'
'../utils'
'./views/member-all.html'
'../../package/jquery.autocomplete/jquery.autocomplete'
'imports?jQuery=jquery!../vendor/jquery.modal'
], (_module, _utils, _template, _autocomplete) ->
_module.directiveModule
.directive('memberSetting', ['$rootScope', 'API', ($rootScope, API)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-setting', _template
link: (scope, element, attr)->
scope.activeIndex = 0
$o = $(element)
#接收事件后,加载数据并显示
$rootScope.$on 'member:setting:show', (event, index)->
scope.activeIndex = index
$o.modal showClose: false
scope.$broadcast "member:setting:bindAll"
scope.$broadcast "member:notification:bindAll"
$rootScope.$on 'member:setting:hide', ()->
$.modal.close()
])
.directive('memberProfile', ['$location', 'API', 'NOTIFY', '$rootScope',
($location, API, NOTIFY, $rootScope)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-profile', _template
link: (scope, element, attr)->
#定义下属组件的上下文名称
scope.contextName = 'memberProfile'
scope.bean = setGits: (data)-> scope.gits = data
scope.onClickSave = ()->
scope.profile.gits = scope.gits
return NOTIFY.warn '请输入您的邮箱' if not scope.profile.email
return NOTIFY.warn '用户名必需输入' if not scope.profile.username
if attr.action is 'account-profile'
API.account().profile().update(scope.profile).then(()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
)
if attr.action is 'create-member'
scope.profile.password = '<PASSWORD>'
#创建成员成功后1.关闭弹窗 2.更新本地数据. 3.添加该成员到这个项目中
API.member().create(scope.profile).then((result)->
NOTIFY.success '创建成员成功!'
#1.关闭弹窗
scope.$emit 'member:creator:hide'
#2.更新本地数据
$rootScope.$broadcast 'lookup:update'
#3.添加该成员到这个项目中
$rootScope.$broadcast 'member:created:save', result.id
)
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.$on 'member:setting:bindAll', ()->
API.account().profile().retrieve().then((result)->
scope.profile = result
scope.gits = _.map(result.gits, (item)-> item.git)
scope.$broadcast("gitList:load", scope.gits)
)
scope.$on('member:creator:bindAll', (event, data)->
scope.profile = data
scope.$apply()
return
)
])
.directive('memberChangePassword', ['$location', 'API', 'NOTIFY',
($location, API, NOTIFY)->
restrict: 'E'
replace: true
scope: true
template: _utils.extractTemplate '#tmpl-member-change-password', _template
link: (scope, element, attr)->
scope.profile = {}
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSave = ()->
if scope.profile.new_password isnt scope.profile.new_password2
NOTIFY.warn '您两次输入的密码不一致'
return
API.account().changePassword().update(scope.profile).then(()->
NOTIFY.success '您的密码修改成功!'
scope.profile = {}
scope.onClickCancel()
)
return
])
.directive('memberNotification', ['$location', 'API', '$stateParams', 'NOTIFY',
($location, API, $stateParams, NOTIFY)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-notification', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
scope.onClickSave = ()->
scope.profile.notification = JSON.stringify scope.profile.notification
API.account().profile().update(scope.profile).then ()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
scope.$on 'member:notification:bindAll', ()->
API.account().profile().retrieve().then (result)->
scope.profile = result
scope.profile.notification = JSON.parse result.notification if result.notification
scope.profile.notification.weixin = 1 if scope.profile.notification && !scope.profile.notification.weixin?
scope.profile.notification.realtime = 1 if scope.profile.notification && !scope.profile.notification.realtime?
scope.profile.notification.email = 1 if scope.profile.notification && !scope.profile.notification.email?
scope.profile.notification.client = 1 if scope.profile.notification && !scope.profile.notification.client?
])
#微信
.directive('memberWeixin', ['API', 'NOTIFY',
(API, NOTIFY)->
scope: {}
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-weixin', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSaveWeixin = ->
API.account().weixin().create({weixin: scope.weixin}).then(()->
NOTIFY.success '微信绑定成功!'
scope.onClickCancel()
)
return
])
#自动完成
.directive('membersLookup', ['$stateParams', 'API', 'STORE',
($stateParams, API, STORE)->
restrict: 'AC'
link: (scope, element, attrs)->
$this = $(element)
memberAPI = API.project($stateParams.project_id).member() if $stateParams.project_id
memberAPI = API.team($stateParams.team_id).member() if $stateParams.team_id
# API.get "project/#{$stateParams.project_id}"/member (result)->
#保存成员
addMember = (member_id)->
data = {member_id: member_id, role: "d",status: 0}
memberAPI.create(data).then ()->
$this.val("")
scope.selectSuggestion = ""
scope.$emit 'project:member:request' if $stateParams.project_id
scope.$emit 'team:member:request' if $stateParams.team_id
initLookup()
#创建成员
createMember = ()->
value = $this.val()
$this.val("")
scope.$emit('member:creator:toshow', value)
#回车事件
$this.on "keyup", (event)->
if event.keyCode is 13 and scope.selectSuggestion then addMember(scope.selectSuggestion)
if event.keyCode is 13 and not scope.selectSuggestion then createMember()
options =
lookup: []
showNoSuggestionNotice: true
noSuggestionNotice: '未找到该用户,按回车键添加该用户'
onSelect: (suggestion)->
scope.selectSuggestion = suggestion.data
#处理 lookup 数据
buildLookupData = (list) ->
memberAPI.retrieve().then (projectMemberList)->
_.remove(list, (item)->
result = _.findIndex(projectMemberList, (pItem)->
item.id is pItem.member_id) >= 0
if not result
item.value = "#{item.realname} -> #{item.username || '未设置'} -> #{item.email}"
item.data = item.id
delete item.realname
delete item.username
delete item.id
delete item.role
result
)
return list
#初始化lookup
initLookup = ()->
API.member().retrieve(pageSize: 9999).then (result)->
options.lookup = buildLookupData(result.items)
$this.autocomplete(options)
#当创建新成员后 初始化 lookup
scope.$on "lookup:update", ()->
initLookup()
#当创建新成员后,添加这个成员到该项目
scope.$on('member:created:save', (event, data)->
addMember(data)
)
#进入的时候初始化lookup
initLookup()
])
# 添加项目成员
.directive('memberCreatorModel', ['$location', 'API', ($location, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-creator', _template
link: (scope, element, attr)->
$o = $(element)
#接收事件后,加载数据并显示
scope.$on "member:creator:show", (event, data)->
scope.$broadcast('member:creator:bindAll', {username: data, realname: data})
$o.modal showClose: false
scope.$on 'member:creator:hide', ()->
$.modal.close()
])
#项目成员item project-member-item #api/project/39/member/1
.directive('projectMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-item', _template
link:(scope,element,attr)->
scope.removeProjectMember = (member)->
API.project($stateParams.project_id).member(member.member_id).delete().then ()->
scope.$emit 'project:member:request'
])
#项目成员角色 project-member-item #api/project/39/member/1/
.directive('projectMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'project-member-item' is name
API.project($stateParams.project_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'project:member:request'
])
#团队成员item team-member-item #api/project/39/member/1
.directive('teamMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-item', _template
link:(scope,element,attr)->
scope.removeTeamMember = (member)->
API.team($stateParams.team_id).member(member.member_id).delete().then ()->
scope.$emit 'team:member:request'
])
#团队成员角色 team-member-item #api/project/39/member/1/
.directive('teamMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'team-member-item' is name
API.team($stateParams.team_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'team:member:request'
])
#读取用户的消息
.directive('memberMessageNotifier', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-message-notifier', _template
link:(scope, element, attr)->
$dropdown = $(element).find 'div.message-list'
$dropdown.bind 'click', (event)-> event.stopPropagation()
$dropdown.bind 'mouseleave', -> scope.onCloseNotifier()
scope.onCloseNotifier = -> $dropdown.fadeOut()
scope.onClickNotifier = (event)->
event.stopPropagation()
$dropdown.fadeIn()
$('body').one 'click', -> scope.onCloseNotifier()
return
scope.onClickItem = (item, hide)->
scope.onCloseNotifier() if hide
API.message(item.id).update().then -> loadMessage()
scope.onClickReadAll = ()->
scope.onCloseNotifier()
API.message().update().then -> loadMessage()
#加载消息
loadMessage = ()->
API.message().retrieve(pageSize: 10, status: 'new').then (result)->
scope.message = result
#加载用户离线通知的事件
scope.$on 'member:message:reload', -> loadMessage()
loadMessage()
]) | true | define [
'../ng-module'
'../utils'
'./views/member-all.html'
'../../package/jquery.autocomplete/jquery.autocomplete'
'imports?jQuery=jquery!../vendor/jquery.modal'
], (_module, _utils, _template, _autocomplete) ->
_module.directiveModule
.directive('memberSetting', ['$rootScope', 'API', ($rootScope, API)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-setting', _template
link: (scope, element, attr)->
scope.activeIndex = 0
$o = $(element)
#接收事件后,加载数据并显示
$rootScope.$on 'member:setting:show', (event, index)->
scope.activeIndex = index
$o.modal showClose: false
scope.$broadcast "member:setting:bindAll"
scope.$broadcast "member:notification:bindAll"
$rootScope.$on 'member:setting:hide', ()->
$.modal.close()
])
.directive('memberProfile', ['$location', 'API', 'NOTIFY', '$rootScope',
($location, API, NOTIFY, $rootScope)->
restrict: 'E'
replace: true
scope: {}
template: _utils.extractTemplate '#tmpl-member-profile', _template
link: (scope, element, attr)->
#定义下属组件的上下文名称
scope.contextName = 'memberProfile'
scope.bean = setGits: (data)-> scope.gits = data
scope.onClickSave = ()->
scope.profile.gits = scope.gits
return NOTIFY.warn '请输入您的邮箱' if not scope.profile.email
return NOTIFY.warn '用户名必需输入' if not scope.profile.username
if attr.action is 'account-profile'
API.account().profile().update(scope.profile).then(()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
)
if attr.action is 'create-member'
scope.profile.password = 'PI:PASSWORD:<PASSWORD>END_PI'
#创建成员成功后1.关闭弹窗 2.更新本地数据. 3.添加该成员到这个项目中
API.member().create(scope.profile).then((result)->
NOTIFY.success '创建成员成功!'
#1.关闭弹窗
scope.$emit 'member:creator:hide'
#2.更新本地数据
$rootScope.$broadcast 'lookup:update'
#3.添加该成员到这个项目中
$rootScope.$broadcast 'member:created:save', result.id
)
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.$on 'member:setting:bindAll', ()->
API.account().profile().retrieve().then((result)->
scope.profile = result
scope.gits = _.map(result.gits, (item)-> item.git)
scope.$broadcast("gitList:load", scope.gits)
)
scope.$on('member:creator:bindAll', (event, data)->
scope.profile = data
scope.$apply()
return
)
])
.directive('memberChangePassword', ['$location', 'API', 'NOTIFY',
($location, API, NOTIFY)->
restrict: 'E'
replace: true
scope: true
template: _utils.extractTemplate '#tmpl-member-change-password', _template
link: (scope, element, attr)->
scope.profile = {}
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSave = ()->
if scope.profile.new_password isnt scope.profile.new_password2
NOTIFY.warn '您两次输入的密码不一致'
return
API.account().changePassword().update(scope.profile).then(()->
NOTIFY.success '您的密码修改成功!'
scope.profile = {}
scope.onClickCancel()
)
return
])
.directive('memberNotification', ['$location', 'API', '$stateParams', 'NOTIFY',
($location, API, $stateParams, NOTIFY)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-notification', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
scope.onClickSave = ()->
scope.profile.notification = JSON.stringify scope.profile.notification
API.account().profile().update(scope.profile).then ()->
NOTIFY.success '保存成功!'
scope.$emit 'member:setting:hide'
scope.$on 'member:notification:bindAll', ()->
API.account().profile().retrieve().then (result)->
scope.profile = result
scope.profile.notification = JSON.parse result.notification if result.notification
scope.profile.notification.weixin = 1 if scope.profile.notification && !scope.profile.notification.weixin?
scope.profile.notification.realtime = 1 if scope.profile.notification && !scope.profile.notification.realtime?
scope.profile.notification.email = 1 if scope.profile.notification && !scope.profile.notification.email?
scope.profile.notification.client = 1 if scope.profile.notification && !scope.profile.notification.client?
])
#微信
.directive('memberWeixin', ['API', 'NOTIFY',
(API, NOTIFY)->
scope: {}
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-weixin', _template
link: (scope, element, attr)->
scope.onClickCancel = ()->
scope.$emit 'member:setting:hide'
return
scope.onClickSaveWeixin = ->
API.account().weixin().create({weixin: scope.weixin}).then(()->
NOTIFY.success '微信绑定成功!'
scope.onClickCancel()
)
return
])
#自动完成
.directive('membersLookup', ['$stateParams', 'API', 'STORE',
($stateParams, API, STORE)->
restrict: 'AC'
link: (scope, element, attrs)->
$this = $(element)
memberAPI = API.project($stateParams.project_id).member() if $stateParams.project_id
memberAPI = API.team($stateParams.team_id).member() if $stateParams.team_id
# API.get "project/#{$stateParams.project_id}"/member (result)->
#保存成员
addMember = (member_id)->
data = {member_id: member_id, role: "d",status: 0}
memberAPI.create(data).then ()->
$this.val("")
scope.selectSuggestion = ""
scope.$emit 'project:member:request' if $stateParams.project_id
scope.$emit 'team:member:request' if $stateParams.team_id
initLookup()
#创建成员
createMember = ()->
value = $this.val()
$this.val("")
scope.$emit('member:creator:toshow', value)
#回车事件
$this.on "keyup", (event)->
if event.keyCode is 13 and scope.selectSuggestion then addMember(scope.selectSuggestion)
if event.keyCode is 13 and not scope.selectSuggestion then createMember()
options =
lookup: []
showNoSuggestionNotice: true
noSuggestionNotice: '未找到该用户,按回车键添加该用户'
onSelect: (suggestion)->
scope.selectSuggestion = suggestion.data
#处理 lookup 数据
buildLookupData = (list) ->
memberAPI.retrieve().then (projectMemberList)->
_.remove(list, (item)->
result = _.findIndex(projectMemberList, (pItem)->
item.id is pItem.member_id) >= 0
if not result
item.value = "#{item.realname} -> #{item.username || '未设置'} -> #{item.email}"
item.data = item.id
delete item.realname
delete item.username
delete item.id
delete item.role
result
)
return list
#初始化lookup
initLookup = ()->
API.member().retrieve(pageSize: 9999).then (result)->
options.lookup = buildLookupData(result.items)
$this.autocomplete(options)
#当创建新成员后 初始化 lookup
scope.$on "lookup:update", ()->
initLookup()
#当创建新成员后,添加这个成员到该项目
scope.$on('member:created:save', (event, data)->
addMember(data)
)
#进入的时候初始化lookup
initLookup()
])
# 添加项目成员
.directive('memberCreatorModel', ['$location', 'API', ($location, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-creator', _template
link: (scope, element, attr)->
$o = $(element)
#接收事件后,加载数据并显示
scope.$on "member:creator:show", (event, data)->
scope.$broadcast('member:creator:bindAll', {username: data, realname: data})
$o.modal showClose: false
scope.$on 'member:creator:hide', ()->
$.modal.close()
])
#项目成员item project-member-item #api/project/39/member/1
.directive('projectMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-item', _template
link:(scope,element,attr)->
scope.removeProjectMember = (member)->
API.project($stateParams.project_id).member(member.member_id).delete().then ()->
scope.$emit 'project:member:request'
])
#项目成员角色 project-member-item #api/project/39/member/1/
.directive('projectMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-project-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'project-member-item' is name
API.project($stateParams.project_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'project:member:request'
])
#团队成员item team-member-item #api/project/39/member/1
.directive('teamMemberItem', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-item', _template
link:(scope,element,attr)->
scope.removeTeamMember = (member)->
API.team($stateParams.team_id).member(member.member_id).delete().then ()->
scope.$emit 'team:member:request'
])
#团队成员角色 team-member-item #api/project/39/member/1/
.directive('teamMemberRoleDropdown', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'AE'
replace: true
template: _utils.extractTemplate '#tmpl-team-member-role-dropdown', _template
link:(scope,element,attr)->
scope.$on 'dropdown:selected', (event,name,value)->
if 'team-member-item' is name
API.team($stateParams.team_id).member(scope.member.member_id).update(role: value).then ()->
scope.$emit 'team:member:request'
])
#读取用户的消息
.directive('memberMessageNotifier', ['$stateParams', 'API', ($stateParams, API)->
restrict: 'E'
replace: true
template: _utils.extractTemplate '#tmpl-member-message-notifier', _template
link:(scope, element, attr)->
$dropdown = $(element).find 'div.message-list'
$dropdown.bind 'click', (event)-> event.stopPropagation()
$dropdown.bind 'mouseleave', -> scope.onCloseNotifier()
scope.onCloseNotifier = -> $dropdown.fadeOut()
scope.onClickNotifier = (event)->
event.stopPropagation()
$dropdown.fadeIn()
$('body').one 'click', -> scope.onCloseNotifier()
return
scope.onClickItem = (item, hide)->
scope.onCloseNotifier() if hide
API.message(item.id).update().then -> loadMessage()
scope.onClickReadAll = ()->
scope.onCloseNotifier()
API.message().update().then -> loadMessage()
#加载消息
loadMessage = ()->
API.message().retrieve(pageSize: 10, status: 'new').then (result)->
scope.message = result
#加载用户离线通知的事件
scope.$on 'member:message:reload', -> loadMessage()
loadMessage()
]) |
[
{
"context": "artist: fabricate 'artist', { id: 'bitty', name: 'Bitty Z' }\n bittyArtwork2 = fabricate 'artwork', pub",
"end": 1412,
"score": 0.9655153155326843,
"start": 1405,
"tag": "NAME",
"value": "Bitty Z"
},
{
"context": "artist: fabricate 'artist', { id: 'bitty', name: 'B... | apps/notifications/test/client/index.coffee | xtina-starr/microgravity | 1 | _ = require 'underscore'
Q = require 'bluebird-q'
benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Notifications = require '../../../../collections/notifications.coffee'
Artworks = require '../../../../collections/artworks.coffee'
Artist = require '../../../../models/artist.coffee'
NotificationsView = benv.requireWithJadeify require.resolve('../../client/view'), [
'template'
'artworkColumnsTemplate'
'emptyTemplate'
]
describe 'NotificationsView', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require 'jquery'
$.onInfiniteScroll = sinon.stub()
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach ->
sinon.stub(Backbone, 'sync').returns Q.resolve()
afterEach ->
Backbone.sync.restore()
describe 'without artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
@view = new NotificationsView el: $('body')
done()
it 'makes the right API call', ->
_.last(Backbone.sync.args)[2].url.should.containEql '/api/v1/me/notifications'
_.last(Backbone.sync.args)[2].data.page.should.equal 1
it 'groups and renders properly', ->
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'Bitty Z' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'Bitty Z' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: 'percy', name: 'Percy Z' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 2 # One for Bitty, One for Percy
@view.$el.html().should.containEql 'Bitty Z'
@view.$el.html().should.containEql 'Percy Z'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
describe 'no notifications', ->
it 'renders the empty notice', ->
_.last(Backbone.sync.args)[2].success []
@view.$el.html().should.containEql 'Nothing here yet'
describe 'with artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
sinon.stub(NotificationsView::, 'params').returns artist_id: 'emile-ajar'
@view = new NotificationsView el: $('body')
done()
afterEach ->
@view.params.restore()
it 'makes the right API calls', ->
Backbone.sync.args[0][1].url.should.containEql 'api/v1/artist/emile-ajar/artworks'
it 'groups and renders properly', ->
Backbone.sync.args[0][2].success([fabricate 'artwork', id: 'emile-ajar-artwork', artist: name: 'Émile Ajar'])
@view.$el.html().should.containEql 'Émile Ajar'
@view.$el.html().should.containEql 'emile-ajar-artwork'
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'Bitty Z' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'Bitty Z' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: 'percy', name: 'Percy Z' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 3 # One for Émile, Bitty, One for Percy
@view.$el.html().should.containEql 'Bitty Z'
@view.$el.html().should.containEql 'Percy Z'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
| 208184 | _ = require 'underscore'
Q = require 'bluebird-q'
benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Notifications = require '../../../../collections/notifications.coffee'
Artworks = require '../../../../collections/artworks.coffee'
Artist = require '../../../../models/artist.coffee'
NotificationsView = benv.requireWithJadeify require.resolve('../../client/view'), [
'template'
'artworkColumnsTemplate'
'emptyTemplate'
]
describe 'NotificationsView', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require 'jquery'
$.onInfiniteScroll = sinon.stub()
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach ->
sinon.stub(Backbone, 'sync').returns Q.resolve()
afterEach ->
Backbone.sync.restore()
describe 'without artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
@view = new NotificationsView el: $('body')
done()
it 'makes the right API call', ->
_.last(Backbone.sync.args)[2].url.should.containEql '/api/v1/me/notifications'
_.last(Backbone.sync.args)[2].data.page.should.equal 1
it 'groups and renders properly', ->
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: '<NAME>' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: '<NAME>' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: 'percy', name: '<NAME>' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 2 # One for Bitty, One for Percy
@view.$el.html().should.containEql 'Bitty Z'
@view.$el.html().should.containEql 'Percy Z'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
describe 'no notifications', ->
it 'renders the empty notice', ->
_.last(Backbone.sync.args)[2].success []
@view.$el.html().should.containEql 'Nothing here yet'
describe 'with artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
sinon.stub(NotificationsView::, 'params').returns artist_id: 'emile-ajar'
@view = new NotificationsView el: $('body')
done()
afterEach ->
@view.params.restore()
it 'makes the right API calls', ->
Backbone.sync.args[0][1].url.should.containEql 'api/v1/artist/emile-ajar/artworks'
it 'groups and renders properly', ->
Backbone.sync.args[0][2].success([fabricate 'artwork', id: 'emile-ajar-artwork', artist: name: '<NAME>'])
@view.$el.html().should.containEql '<NAME>'
@view.$el.html().should.containEql 'emile-ajar-artwork'
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: '<NAME>', name: '<NAME>' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: '<NAME>', name: '<NAME>' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: '<NAME>cy', name: '<NAME>' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 3 # One for <NAME>, <NAME>, One for <NAME>
@view.$el.html().should.containEql '<NAME>'
@view.$el.html().should.containEql '<NAME>'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
| true | _ = require 'underscore'
Q = require 'bluebird-q'
benv = require 'benv'
sinon = require 'sinon'
Backbone = require 'backbone'
{ fabricate } = require 'antigravity'
Notifications = require '../../../../collections/notifications.coffee'
Artworks = require '../../../../collections/artworks.coffee'
Artist = require '../../../../models/artist.coffee'
NotificationsView = benv.requireWithJadeify require.resolve('../../client/view'), [
'template'
'artworkColumnsTemplate'
'emptyTemplate'
]
describe 'NotificationsView', ->
before (done) ->
benv.setup ->
benv.expose $: benv.require 'jquery'
$.onInfiniteScroll = sinon.stub()
Backbone.$ = $
done()
after ->
benv.teardown()
beforeEach ->
sinon.stub(Backbone, 'sync').returns Q.resolve()
afterEach ->
Backbone.sync.restore()
describe 'without artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
@view = new NotificationsView el: $('body')
done()
it 'makes the right API call', ->
_.last(Backbone.sync.args)[2].url.should.containEql '/api/v1/me/notifications'
_.last(Backbone.sync.args)[2].data.page.should.equal 1
it 'groups and renders properly', ->
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'PI:NAME:<NAME>END_PI' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'bitty', name: 'PI:NAME:<NAME>END_PI' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: 'percy', name: 'PI:NAME:<NAME>END_PI' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 2 # One for Bitty, One for Percy
@view.$el.html().should.containEql 'Bitty Z'
@view.$el.html().should.containEql 'Percy Z'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
describe 'no notifications', ->
it 'renders the empty notice', ->
_.last(Backbone.sync.args)[2].success []
@view.$el.html().should.containEql 'Nothing here yet'
describe 'with artist_id', ->
beforeEach (done) ->
benv.render require.resolve('../../templates/index.jade'), { sd: {} }, =>
sinon.stub(NotificationsView::, 'params').returns artist_id: 'emile-ajar'
@view = new NotificationsView el: $('body')
done()
afterEach ->
@view.params.restore()
it 'makes the right API calls', ->
Backbone.sync.args[0][1].url.should.containEql 'api/v1/artist/emile-ajar/artworks'
it 'groups and renders properly', ->
Backbone.sync.args[0][2].success([fabricate 'artwork', id: 'emile-ajar-artwork', artist: name: 'PI:NAME:<NAME>END_PI'])
@view.$el.html().should.containEql 'PI:NAME:<NAME>END_PI'
@view.$el.html().should.containEql 'emile-ajar-artwork'
bittyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'PI:NAME:<NAME>END_PI', name: 'PI:NAME:<NAME>END_PI' }
bittyArtwork2 = fabricate 'artwork', published_changed_at: '2012-05-07T04:00:00+00:00', artist: fabricate 'artist', { id: 'PI:NAME:<NAME>END_PI', name: 'PI:NAME:<NAME>END_PI' }
percyArtwork1 = fabricate 'artwork', published_changed_at: '2012-05-06T04:00:00+00:00', artist: fabricate 'artist', { id: 'PI:NAME:<NAME>END_PIcy', name: 'PI:NAME:<NAME>END_PI' }
_.last(Backbone.sync.args)[2].success [bittyArtwork1, bittyArtwork2, percyArtwork1]
@view.$el.find('.notifications-list-item').length.should.equal 3 # One for PI:NAME:<NAME>END_PI, PI:NAME:<NAME>END_PI, One for PI:NAME:<NAME>END_PI
@view.$el.html().should.containEql 'PI:NAME:<NAME>END_PI'
@view.$el.html().should.containEql 'PI:NAME:<NAME>END_PI'
@view.$el.html().should.containEql '/artist/bitty'
@view.$el.html().should.containEql '/artist/percy'
@view.$el.html().should.containEql '2 works added'
@view.$el.html().should.containEql '1 work added'
|
[
{
"context": "s\n\nexportObj.fightersCommon = ->\n\t[\n\t\t{\n\t\t\tname: \"Severin Steelheart\"\n\t\t\twarband: \"Steelheart's Champions\"\n\t\t\tcaptain:",
"end": 94,
"score": 0.9998542666435242,
"start": 76,
"tag": "NAME",
"value": "Severin Steelheart"
},
{
"context": "%\" }\n\t\t... | src/data/fighters.coffee | Steveh15/underworlds-deck-builder | 0 |
exportObj = exports ? this
exportObj.fightersCommon = ->
[
{
name: "Severin Steelheart"
warband: "Steelheart's Champions"
captain: true
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Broadsword"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "Steelheart Inspired"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Broadsword"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
{
name: "Mighty Swing"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
text: "<div><strong> Mighty Swing</strong><div> Targets all adjacent enemies. Roll for each."
}
}
{
name: "Angharad Brightshield"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Hammer"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "Brightshield Inspired"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Hammer"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
{
name: "Furious Parry"
range: 1
value: 2
char: "%HAMMER%"
dmg: 1
}
]
text: "<strong> <div>Furious Parry<div>Reaction: </strong> During an Attack action that targets this fighter and has failed, this fighter cannot be driven back and you can make this Attack action. It must target the attacker."
}
}
{
name: "Obryn the Bold"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Grandhammer"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "Obryn Inspired"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Sigmarite Grandhammer"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
{
name: "Overhead Strike"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "Garrek Gorebeard"
warband: "Garrek's Reavers"
captain: true
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Blooddrinker Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "Garrek Inspired"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Awakened Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
}
}
{
name: "Karsus the Chained"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 1
}
{
name: "Brutal Chop"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "Karsus Inspired"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 2
}
{
name: "Savage Whirl"
range: 1
value: 2
char: "%SWORDS%"
dmg: 2
}
]
text: "<div><strong>Savage Whirl</strong></div> Targets all adjacent enemies - roll for each."
}
}
{
name: "Blooded Saek"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "Saek Inspired"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "Targor"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "Targor Inspired"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
}
}
{
name: "Arnulf"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
inspiredVersion: {
name: "Arnulf Inspired"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 3
char: "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
}
}
{
name: "Averon Stormsire"
warband: "Stormsire's Cursebreakers"
captain: true
magic: 2
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter successfully casts a spell."
inspiredVersion: {
name: "Stormsire Inspired"
warband: "Stormsire's Cursebreakers"
magic: 2
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 2
}
]
}
}
{
name: "Vortemis the All-Seeing"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter makes a successful Attack action with a Range of 3 or more"
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
inspiredVersion: {
name: "Vortemis the All-Seeing"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 2, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 2
}
]
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
}
}
{
name: "Brimstone Horrors"
warband: "Eyes of the Nine"
movement: 3
defence: { value: 1, char: "%DODGE%" }
wounds: 1
attacks: [
{
name: "Magical Flames"
range: 3
value: 2
char : "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Magical Flames</strong><div> <strong>Reaction :</strong> After the first time this fighter makes this Attack action in a phase, make another Attack action with this fighter. Do not place this fighter during set up. This fighter cannot be given Attack action upgrades, and cannot be Inspired. If this fighter is taken out of action, flip this fighter card over. It keeps any upgrades."
}
]
exportObj.fighters = () ->
data = exportObj.fightersCommon()
for index, fighter of data
fighter.defence.char = fighter.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.defence.char = fighter.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
if fighter.inspiredVersion?
fighter.inspire_cond = fighter.inspire_cond.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspire_cond = fighter.inspire_cond.replace(/%CRIT%/g, "<span class = 'testclass'><strong class='icon-crit'></strong></span>")
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.inspiredVersion.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
return data
| 116855 |
exportObj = exports ? this
exportObj.fightersCommon = ->
[
{
name: "<NAME>"
warband: "Steelheart's Champions"
captain: true
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>word"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "<NAME>"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>word"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
{
name: "<NAME>"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
text: "<div><strong> Mighty Swing</strong><div> Targets all adjacent enemies. Roll for each."
}
}
{
name: "<NAME>"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "B<NAME>shield In<NAME>"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
{
name: "<NAME>"
range: 1
value: 2
char: "%HAMMER%"
dmg: 1
}
]
text: "<strong> <div>Furious Parry<div>Reaction: </strong> During an Attack action that targets this fighter and has failed, this fighter cannot be driven back and you can make this Attack action. It must target the attacker."
}
}
{
name: "<NAME>"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "<NAME>"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "<NAME>"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
{
name: "Overhead Strike"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "<NAME>"
warband: "Garrek's Reavers"
captain: true
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Blooddrinker Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Awakened Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
}
}
{
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 1
}
{
name: "Brutal Chop"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 2
}
{
name: "<NAME>"
range: 1
value: 2
char: "%SWORDS%"
dmg: 2
}
]
text: "<div><strong>Savage Whirl</strong></div> Targets all adjacent enemies - roll for each."
}
}
{
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
}
}
{
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
inspiredVersion: {
name: "<NAME>"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 3
char: "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
}
}
{
name: "<NAME>"
warband: "Stormsire's Cursebreakers"
captain: true
magic: 2
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter successfully casts a spell."
inspiredVersion: {
name: "<NAME>"
warband: "Stormsire's Cursebreakers"
magic: 2
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 2
}
]
}
}
{
name: "<NAME>"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter makes a successful Attack action with a Range of 3 or more"
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
inspiredVersion: {
name: "<NAME>"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 2, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 2
}
]
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
}
}
{
name: "<NAME>"
warband: "Eyes of the Nine"
movement: 3
defence: { value: 1, char: "%DODGE%" }
wounds: 1
attacks: [
{
name: "<NAME>"
range: 3
value: 2
char : "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Magical Flames</strong><div> <strong>Reaction :</strong> After the first time this fighter makes this Attack action in a phase, make another Attack action with this fighter. Do not place this fighter during set up. This fighter cannot be given Attack action upgrades, and cannot be Inspired. If this fighter is taken out of action, flip this fighter card over. It keeps any upgrades."
}
]
exportObj.fighters = () ->
data = exportObj.fightersCommon()
for index, fighter of data
fighter.defence.char = fighter.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.defence.char = fighter.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
if fighter.inspiredVersion?
fighter.inspire_cond = fighter.inspire_cond.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspire_cond = fighter.inspire_cond.replace(/%CRIT%/g, "<span class = 'testclass'><strong class='icon-crit'></strong></span>")
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.inspiredVersion.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
return data
| true |
exportObj = exports ? this
exportObj.fightersCommon = ->
[
{
name: "PI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
captain: true
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PIword"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PIword"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
text: "<div><strong> Mighty Swing</strong><div> Targets all adjacent enemies. Roll for each."
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "BPI:NAME:<NAME>END_PIshield InPI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 3
char: "%HAMMER%"
dmg: 2
}
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 2
char: "%HAMMER%"
dmg: 1
}
]
text: "<strong> <div>Furious Parry<div>Reaction: </strong> During an Attack action that targets this fighter and has failed, this fighter cannot be driven back and you can make this Attack action. It must target the attacker."
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
]
inspire_cond: "This fighter rolls a %SHIELD% or a %CRIT% when the target of an attack."
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Steelheart's Champions"
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Knockback 1"
}
{
name: "Overhead Strike"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
captain: true
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Blooddrinker Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Awakened Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 1
}
{
name: "Brutal Chop"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Chained Axe"
range: 2
value: 3
char: "%SWORDS%"
dmg: 2
}
{
name: "PI:NAME:<NAME>END_PI"
range: 1
value: 2
char: "%SWORDS%"
dmg: 2
}
]
text: "<div><strong>Savage Whirl</strong></div> Targets all adjacent enemies - roll for each."
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 3
attacks: [
{
name: "Great Axe"
range: 1
value: 2
char: "%HAMMER%"
dmg: 3
text: "Cleave"
}
]
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Gore-Axe and Blade"
range: 1
value: 3
char: "%SWORDS%"
dmg: 2
}
]
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 2
char: "%SWORDS%"
dmg: 1
}
]
inspire_cond: "At least three fighters are out of action"
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Garrek's Reavers"
movement: 5
defence: { value: 1, char: "%DODGE%" }
wounds: 2
attacks: [
{
name: "Piercing Blade and Axe"
range: 1
value: 3
char: "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Piercing Blade and Axe</strong></div> On a critical hit, this Attack action deals 1 extra damage."
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Stormsire's Cursebreakers"
captain: true
magic: 2
movement: 3
defence: { value: 1, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter successfully casts a spell."
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Stormsire's Cursebreakers"
magic: 2
movement: 3
defence: { value: 2, char: "%SHIELD%" }
wounds: 4
attacks: [
{
name: "Incantor's Staff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Fulmination"
range: 3
dmg: 2
}
]
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 1, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 1
}
]
inspire_cond: "This fighter makes a successful Attack action with a Range of 3 or more"
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
inspiredVersion: {
name: "PI:NAME:<NAME>END_PI"
warband: "Eyes of the Nine"
captain: true
magic: 2
movement: 4
defence: { value: 2, char: "%DODGE%" }
wounds: 4
attacks: [
{
name: "Tzeentchain Runestaff"
range: 2
value: 2
char: "%HAMMER%"
dmg: 2
}
]
spells: [
{
name: "Bolt of Change"
range: 3
dmg: 2
}
]
text: "<div><strong>Action:</strong><div> If there is no friendly Blue Horror or Brimstone Horrors on the battlefield, place a friendly Blue Horror on any starting hex."
}
}
{
name: "PI:NAME:<NAME>END_PI"
warband: "Eyes of the Nine"
movement: 3
defence: { value: 1, char: "%DODGE%" }
wounds: 1
attacks: [
{
name: "PI:NAME:<NAME>END_PI"
range: 3
value: 2
char : "%SWORDS%"
dmg: 1
}
]
text: "<div><strong>Magical Flames</strong><div> <strong>Reaction :</strong> After the first time this fighter makes this Attack action in a phase, make another Attack action with this fighter. Do not place this fighter during set up. This fighter cannot be given Attack action upgrades, and cannot be Inspired. If this fighter is taken out of action, flip this fighter card over. It keeps any upgrades."
}
]
exportObj.fighters = () ->
data = exportObj.fightersCommon()
for index, fighter of data
fighter.defence.char = fighter.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.defence.char = fighter.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
if fighter.inspiredVersion?
fighter.inspire_cond = fighter.inspire_cond.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspire_cond = fighter.inspire_cond.replace(/%CRIT%/g, "<span class = 'testclass'><strong class='icon-crit'></strong></span>")
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%SHIELD%/g, '<i class="icon-shield"></i>')
fighter.inspiredVersion.defence.char = fighter.inspiredVersion.defence.char.replace(/%DODGE%/g, '<i class="icon-dodge"></i>')
for index, attack of fighter.inspiredVersion.attacks
attack.char = attack.char.replace(/%SWORDS%/g, '<i class="icon-sword"></i>')
attack.char = attack.char.replace(/%HAMMER%/g, '<i class="icon-hammer"></i>')
return data
|
[
{
"context": " service = new HttpMicroService\n name: \"testApi\"\n host: \"localhost\"\n port: 3000\n\n ",
"end": 553,
"score": 0.5953220129013062,
"start": 546,
"tag": "USERNAME",
"value": "testApi"
},
{
"context": " port: 3000\n\n service.name.should... | spec/HttpMicroService.spec.coffee | veacks/microservices-restfull | 0 | # Assertion and mock frameworks
chai = require "chai"
should = chai.should()
sinon = require "sinon"
sinonChai = require "sinon-chai"
chai.use sinonChai
nock = require "nock"
http = require "http"
https = require "https"
HttpMicroService = require "../build/HttpMicroService"
describe "HttpMicroService", ->
describe "Create a Microservice", ->
service = {}
# Test the micro service constructor
it "Should create an HTTPS Microservice Object with default values", (done) ->
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.name.should.be.equal "testApi"
service.host.should.be.equal "localhost"
service.port.should.be.equal 3000
service.type.should.be.equal "https"
service.commonHeaders.should.be.eql { "Content-Type": "application/json" }
done()
it "Should create an HTTP MicroService Object with custom header", (done) ->
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "http"
headers: {
"Foo": "bar"
}
service.type.should.be.equal "http"
service.commonHeaders.should.be.eql { "Foo": "bar" }
done()
describe "Common request check", ->
# Check host
# Check port
# Check action
# Check wrong type
describe "GET", ->
it "Should perform an Https GET request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
query = service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
query
.catch (err) ->
should.not.exits err
done()
.then (body) ->
body.should.be.eql { key: "value" }
done()
it "Should perform an Http GET request", (done) ->
nock "http://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "http"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
it "Should not perform HTTPS if the type is wrong", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "wrong"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "HEAD", ->
it "Should perform an Https HEAD request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.head "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.head
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "POST", ->
it "Should perform an Https POST request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.post "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.post
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PUT", ->
it "Should perform an Https PUT request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.put "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.put
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PATCH", ->
it "Should perform an Https PATCH request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.patch "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.patch
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "DELETE", ->
it "Should perform an Https DELETE request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.delete "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.delete
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
| 991 | # Assertion and mock frameworks
chai = require "chai"
should = chai.should()
sinon = require "sinon"
sinonChai = require "sinon-chai"
chai.use sinonChai
nock = require "nock"
http = require "http"
https = require "https"
HttpMicroService = require "../build/HttpMicroService"
describe "HttpMicroService", ->
describe "Create a Microservice", ->
service = {}
# Test the micro service constructor
it "Should create an HTTPS Microservice Object with default values", (done) ->
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.name.should.be.equal "testApi"
service.host.should.be.equal "localhost"
service.port.should.be.equal 3000
service.type.should.be.equal "https"
service.commonHeaders.should.be.eql { "Content-Type": "application/json" }
done()
it "Should create an HTTP MicroService Object with custom header", (done) ->
service = new HttpMicroService
name: "<NAME>Api"
host: "localhost"
port: 3000
type: "http"
headers: {
"Foo": "bar"
}
service.type.should.be.equal "http"
service.commonHeaders.should.be.eql { "Foo": "bar" }
done()
describe "Common request check", ->
# Check host
# Check port
# Check action
# Check wrong type
describe "GET", ->
it "Should perform an Https GET request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "<NAME>Api"
host: "localhost"
port: 3000
query = service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
query
.catch (err) ->
should.not.exits err
done()
.then (body) ->
body.should.be.eql { key: "value" }
done()
it "Should perform an Http GET request", (done) ->
nock "http://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "http"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
it "Should not perform HTTPS if the type is wrong", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "wrong"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "HEAD", ->
it "Should perform an Https HEAD request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.head "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.head
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "POST", ->
it "Should perform an Https POST request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.post "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.post
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PUT", ->
it "Should perform an Https PUT request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.put "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.put
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PATCH", ->
it "Should perform an Https PATCH request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.patch "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.patch
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "DELETE", ->
it "Should perform an Https DELETE request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.delete "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.delete
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
| true | # Assertion and mock frameworks
chai = require "chai"
should = chai.should()
sinon = require "sinon"
sinonChai = require "sinon-chai"
chai.use sinonChai
nock = require "nock"
http = require "http"
https = require "https"
HttpMicroService = require "../build/HttpMicroService"
describe "HttpMicroService", ->
describe "Create a Microservice", ->
service = {}
# Test the micro service constructor
it "Should create an HTTPS Microservice Object with default values", (done) ->
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.name.should.be.equal "testApi"
service.host.should.be.equal "localhost"
service.port.should.be.equal 3000
service.type.should.be.equal "https"
service.commonHeaders.should.be.eql { "Content-Type": "application/json" }
done()
it "Should create an HTTP MicroService Object with custom header", (done) ->
service = new HttpMicroService
name: "PI:NAME:<NAME>END_PIApi"
host: "localhost"
port: 3000
type: "http"
headers: {
"Foo": "bar"
}
service.type.should.be.equal "http"
service.commonHeaders.should.be.eql { "Foo": "bar" }
done()
describe "Common request check", ->
# Check host
# Check port
# Check action
# Check wrong type
describe "GET", ->
it "Should perform an Https GET request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "PI:NAME:<NAME>END_PIApi"
host: "localhost"
port: 3000
query = service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
query
.catch (err) ->
should.not.exits err
done()
.then (body) ->
body.should.be.eql { key: "value" }
done()
it "Should perform an Http GET request", (done) ->
nock "http://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "http"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
it "Should not perform HTTPS if the type is wrong", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.get "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
type: "wrong"
service.get
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "HEAD", ->
it "Should perform an Https HEAD request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.head "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.head
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
describe "POST", ->
it "Should perform an Https POST request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.post "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.post
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PUT", ->
it "Should perform an Https PUT request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.put "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.put
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "PATCH", ->
it "Should perform an Https PATCH request", (done) ->
datasToPost = { foo: "bar" }
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.matchHeader('Content-Length', Buffer.byteLength(JSON.stringify(datasToPost)))
.filteringRequestBody (body) ->
body.should.be.equal JSON.stringify(datasToPost)
return body
.patch "/controller"
.reply 200, { id: "0123456789" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.patch
action: "/controller"
data: datasToPost
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { id: "0123456789" }
done()
describe "DELETE", ->
it "Should perform an Https DELETE request", (done) ->
nock "https://localhost:3000"
.matchHeader('Content-Type', 'application/json')
.matchHeader('Foo', "Bar")
.delete "/controller/page?foo=bar"
.reply 200, { key: "value" }, {
'Content-Type': 'application/json'
}
service = new HttpMicroService
name: "testApi"
host: "localhost"
port: 3000
service.delete
action: "/controller/page"
data:
foo: "bar"
headers:
"Foo": "Bar"
.catch (err) ->
should.not.exits err
done()
.then (resp) ->
resp.should.be.eql { key: "value" }
done()
|
[
{
"context": "aScript event loop.\n#\n# :copyright: (c) 2013 by Zaur Nasibov.\n# :license: MIT, see LICENSE for more details",
"end": 233,
"score": 0.9998879432678223,
"start": 221,
"tag": "NAME",
"value": "Zaur Nasibov"
}
] | kaylee/client/klajax.coffee | BasicWolf/archived-kaylee | 2 | ###
# klajax.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains a small AJAX library used in a browser's
# main JavaScript event loop.
#
# :copyright: (c) 2013 by Zaur Nasibov.
# :license: MIT, see LICENSE for more details.
###
kl.ajax = (url, method, data, success=(()->), fail=(()->)) ->
req = new XMLHttpRequest();
switch method
when "POST"
data = {} if not data?
data = JSON.stringify(data)
req.open('POST', url, true);
req.setRequestHeader('Content-type', 'application/json; charset=utf-8');
when "GET"
if data?
dl = []
for key, val of data
dl.push(key + '=' + encodeURIComponent(val))
url += '?' + dl.join('&')
req.open("GET", url, true);
req.onreadystatechange = () ->
if req.readyState == 4
if req.status == 200 and req.responseText?
response = JSON.parse(req.responseText);
if response.error?
fail(response.error)
else
success(response)
else if !response?
fail('INVALID_STATE_ERR')
else
fail(response)
return
req.send(data);
return
kl.post = (url, data, success, fail) ->
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'POST', data, _success, fail)
return
kl.get = (url, data, success, fail) ->
# remap the arguments in case that the first argument is
# the success callback.
if arguments.length >= 2
if kl.util.is_function(data)
fail = success
success = data
data = null
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'GET', data, _success, fail)
return
_dom_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
count = urls.length
sc = 0 # loaded scripts and stylesheets counter
failed = false # indicates whether the inclusion process failed or not
for url in urls
doc = document.getElementsByTagName('head')[0]
onload = () ->
sc += 1
if sc == count and not failed
success?()
onerror = (msg) ->
failed = true
fail?(msg)
if util.ends_with(url, '.js')
js = document.createElement('script')
js.setAttribute('type', 'text/javascript')
js.setAttribute('src', url)
js.onload = onload
js.onerror = onerror
doc.appendChild(js)
else if util.ends_with(url, '.css')
if fail?
kl.exception('Kaylee is not able to invoke the fail()
callback of kl.include(..) when loading stylesheets.')
failed = true
return
css = document.createElement("link")
css.rel = 'stylesheet'
css.type = 'text/css'
css.href = url
css.onload = onload
doc.appendChild(css)
return
_worker_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
error_message = ''
all_imported = true
for url in urls
try
importScripts(url)
catch error
all_imported = false
error_message = "Error importing #{url}: #{error.message}"
break
if all_imported
success?()
else
fail?(error_message)
kl.include = (urls, success, fail) ->
# bind appropriate include function as kl.include
if __DEFINE_WORKER?
_worker_include(urls, success, fail)
else
_dom_include(urls, success, fail)
| 21225 | ###
# klajax.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains a small AJAX library used in a browser's
# main JavaScript event loop.
#
# :copyright: (c) 2013 by <NAME>.
# :license: MIT, see LICENSE for more details.
###
kl.ajax = (url, method, data, success=(()->), fail=(()->)) ->
req = new XMLHttpRequest();
switch method
when "POST"
data = {} if not data?
data = JSON.stringify(data)
req.open('POST', url, true);
req.setRequestHeader('Content-type', 'application/json; charset=utf-8');
when "GET"
if data?
dl = []
for key, val of data
dl.push(key + '=' + encodeURIComponent(val))
url += '?' + dl.join('&')
req.open("GET", url, true);
req.onreadystatechange = () ->
if req.readyState == 4
if req.status == 200 and req.responseText?
response = JSON.parse(req.responseText);
if response.error?
fail(response.error)
else
success(response)
else if !response?
fail('INVALID_STATE_ERR')
else
fail(response)
return
req.send(data);
return
kl.post = (url, data, success, fail) ->
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'POST', data, _success, fail)
return
kl.get = (url, data, success, fail) ->
# remap the arguments in case that the first argument is
# the success callback.
if arguments.length >= 2
if kl.util.is_function(data)
fail = success
success = data
data = null
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'GET', data, _success, fail)
return
_dom_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
count = urls.length
sc = 0 # loaded scripts and stylesheets counter
failed = false # indicates whether the inclusion process failed or not
for url in urls
doc = document.getElementsByTagName('head')[0]
onload = () ->
sc += 1
if sc == count and not failed
success?()
onerror = (msg) ->
failed = true
fail?(msg)
if util.ends_with(url, '.js')
js = document.createElement('script')
js.setAttribute('type', 'text/javascript')
js.setAttribute('src', url)
js.onload = onload
js.onerror = onerror
doc.appendChild(js)
else if util.ends_with(url, '.css')
if fail?
kl.exception('Kaylee is not able to invoke the fail()
callback of kl.include(..) when loading stylesheets.')
failed = true
return
css = document.createElement("link")
css.rel = 'stylesheet'
css.type = 'text/css'
css.href = url
css.onload = onload
doc.appendChild(css)
return
_worker_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
error_message = ''
all_imported = true
for url in urls
try
importScripts(url)
catch error
all_imported = false
error_message = "Error importing #{url}: #{error.message}"
break
if all_imported
success?()
else
fail?(error_message)
kl.include = (urls, success, fail) ->
# bind appropriate include function as kl.include
if __DEFINE_WORKER?
_worker_include(urls, success, fail)
else
_dom_include(urls, success, fail)
| true | ###
# klajax.coffee
# ~~~~~~~~~~~~~
#
# This file is a part of Kaylee client-side module.
# It contains a small AJAX library used in a browser's
# main JavaScript event loop.
#
# :copyright: (c) 2013 by PI:NAME:<NAME>END_PI.
# :license: MIT, see LICENSE for more details.
###
kl.ajax = (url, method, data, success=(()->), fail=(()->)) ->
req = new XMLHttpRequest();
switch method
when "POST"
data = {} if not data?
data = JSON.stringify(data)
req.open('POST', url, true);
req.setRequestHeader('Content-type', 'application/json; charset=utf-8');
when "GET"
if data?
dl = []
for key, val of data
dl.push(key + '=' + encodeURIComponent(val))
url += '?' + dl.join('&')
req.open("GET", url, true);
req.onreadystatechange = () ->
if req.readyState == 4
if req.status == 200 and req.responseText?
response = JSON.parse(req.responseText);
if response.error?
fail(response.error)
else
success(response)
else if !response?
fail('INVALID_STATE_ERR')
else
fail(response)
return
req.send(data);
return
kl.post = (url, data, success, fail) ->
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'POST', data, _success, fail)
return
kl.get = (url, data, success, fail) ->
# remap the arguments in case that the first argument is
# the success callback.
if arguments.length >= 2
if kl.util.is_function(data)
fail = success
success = data
data = null
_success = (resp_data) ->
if resp_data.error? then fail(resp_data.error) else success(resp_data)
kl.ajax(url, 'GET', data, _success, fail)
return
_dom_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
count = urls.length
sc = 0 # loaded scripts and stylesheets counter
failed = false # indicates whether the inclusion process failed or not
for url in urls
doc = document.getElementsByTagName('head')[0]
onload = () ->
sc += 1
if sc == count and not failed
success?()
onerror = (msg) ->
failed = true
fail?(msg)
if util.ends_with(url, '.js')
js = document.createElement('script')
js.setAttribute('type', 'text/javascript')
js.setAttribute('src', url)
js.onload = onload
js.onerror = onerror
doc.appendChild(js)
else if util.ends_with(url, '.css')
if fail?
kl.exception('Kaylee is not able to invoke the fail()
callback of kl.include(..) when loading stylesheets.')
failed = true
return
css = document.createElement("link")
css.rel = 'stylesheet'
css.type = 'text/css'
css.href = url
css.onload = onload
doc.appendChild(css)
return
_worker_include = (urls, success, fail) ->
if not (urls instanceof Array)
urls = [urls] # in this case string is expected
error_message = ''
all_imported = true
for url in urls
try
importScripts(url)
catch error
all_imported = false
error_message = "Error importing #{url}: #{error.message}"
break
if all_imported
success?()
else
fail?(error_message)
kl.include = (urls, success, fail) ->
# bind appropriate include function as kl.include
if __DEFINE_WORKER?
_worker_include(urls, success, fail)
else
_dom_include(urls, success, fail)
|
[
{
"context": "host', port: 0xd00d, uuid: 'some-device', token: 'some-token'\n @sut = new Verifier {meshbluConfig}\n\n c",
"end": 695,
"score": 0.7984499335289001,
"start": 685,
"tag": "PASSWORD",
"value": "some-token"
}
] | test/verifier-spec.coffee | octoblu/meshblu-verifier-mqtt | 0 | shmock = require 'shmock'
Verifier = require '../src/verifier'
MockMeshbluMQTT = require './mock-meshblu-mqtt'
xdescribe 'Verifier', ->
beforeEach (done) ->
@whoamiHandler = sinon.stub()
onPublished = (packet, publish) =>
{topic, payload} = packet
if topic == 'whoami'
@whoamiHandler payload, (response) =>
@meshblu.publish 'some-device', 'whoami', response
@meshblu = new MockMeshbluMQTT port: 0xd00d, onPublished: onPublished
@meshblu.start done
afterEach (done) ->
@meshblu.stop => done()
describe '-> verify', ->
beforeEach ->
meshbluConfig = hostname: 'localhost', port: 0xd00d, uuid: 'some-device', token: 'some-token'
@sut = new Verifier {meshbluConfig}
context 'when everything works', ->
beforeEach ->
@whoamiHandler.yields uuid: 'some-device', type: 'meshblu:verifier'
beforeEach (done) ->
@sut.verify (error) =>
done error
it 'should not error', ->
expect(@whoamiHandler).to.be.called
| 141863 | shmock = require 'shmock'
Verifier = require '../src/verifier'
MockMeshbluMQTT = require './mock-meshblu-mqtt'
xdescribe 'Verifier', ->
beforeEach (done) ->
@whoamiHandler = sinon.stub()
onPublished = (packet, publish) =>
{topic, payload} = packet
if topic == 'whoami'
@whoamiHandler payload, (response) =>
@meshblu.publish 'some-device', 'whoami', response
@meshblu = new MockMeshbluMQTT port: 0xd00d, onPublished: onPublished
@meshblu.start done
afterEach (done) ->
@meshblu.stop => done()
describe '-> verify', ->
beforeEach ->
meshbluConfig = hostname: 'localhost', port: 0xd00d, uuid: 'some-device', token: '<PASSWORD>'
@sut = new Verifier {meshbluConfig}
context 'when everything works', ->
beforeEach ->
@whoamiHandler.yields uuid: 'some-device', type: 'meshblu:verifier'
beforeEach (done) ->
@sut.verify (error) =>
done error
it 'should not error', ->
expect(@whoamiHandler).to.be.called
| true | shmock = require 'shmock'
Verifier = require '../src/verifier'
MockMeshbluMQTT = require './mock-meshblu-mqtt'
xdescribe 'Verifier', ->
beforeEach (done) ->
@whoamiHandler = sinon.stub()
onPublished = (packet, publish) =>
{topic, payload} = packet
if topic == 'whoami'
@whoamiHandler payload, (response) =>
@meshblu.publish 'some-device', 'whoami', response
@meshblu = new MockMeshbluMQTT port: 0xd00d, onPublished: onPublished
@meshblu.start done
afterEach (done) ->
@meshblu.stop => done()
describe '-> verify', ->
beforeEach ->
meshbluConfig = hostname: 'localhost', port: 0xd00d, uuid: 'some-device', token: 'PI:PASSWORD:<PASSWORD>END_PI'
@sut = new Verifier {meshbluConfig}
context 'when everything works', ->
beforeEach ->
@whoamiHandler.yields uuid: 'some-device', type: 'meshblu:verifier'
beforeEach (done) ->
@sut.verify (error) =>
done error
it 'should not error', ->
expect(@whoamiHandler).to.be.called
|
[
{
"context": "#\n# Copyright (c) 2015 JD Powell <waveclaw@waveclaw.net>\n#\n# All modifications and",
"end": 32,
"score": 0.9965730905532837,
"start": 23,
"tag": "NAME",
"value": "JD Powell"
},
{
"context": "#\n# Copyright (c) 2015 JD Powell <waveclaw@waveclaw.net>\n#\n# All modifica... | snippets/rpm-spec.cson | waveclaw/language-rpm-spec | 3 | #
# Copyright (c) 2015 JD Powell <waveclaw@waveclaw.net>
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.
#
# Please submit bugfixes or comments via
# https://github.com/waveclaw/language-rpm-spec/issues
#
'.source.rpm-spec':
'subpackage':
'prefix': '%pack'
'body': """
%package $1
Group: foo
Summary: bar
%description $1
baz
%files $1
"""
'build':
'prefix': '%bld'
'body': """
%build
%configure
%if %{defined make_jobs}
%{make_jobs} %{?_smp_mflags}
%else
%{__make} %{?_smp_mflags}
%endif
"""
'install':
'prefix': '%inst'
'body': """
%install
%{__make} install DESTDIR=%{buildroot} %{?_smp_mflags}
"""
'changelog entry':
'prefix': 'chi'
'body': """
* ${1:weekday} ${2:monthofyear} ${3:dayofmonth} ${4:year} ${5:packager} - ${6:version}-${7:release}
- $8
"""
# unlike gedit snippets, static snippets like these
# are fixed strings - no variables or expansions
| 32096 | #
# Copyright (c) 2015 <NAME> <<EMAIL>>
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.
#
# Please submit bugfixes or comments via
# https://github.com/waveclaw/language-rpm-spec/issues
#
'.source.rpm-spec':
'subpackage':
'prefix': '%pack'
'body': """
%package $1
Group: foo
Summary: bar
%description $1
baz
%files $1
"""
'build':
'prefix': '%bld'
'body': """
%build
%configure
%if %{defined make_jobs}
%{make_jobs} %{?_smp_mflags}
%else
%{__make} %{?_smp_mflags}
%endif
"""
'install':
'prefix': '%inst'
'body': """
%install
%{__make} install DESTDIR=%{buildroot} %{?_smp_mflags}
"""
'changelog entry':
'prefix': 'chi'
'body': """
* ${1:weekday} ${2:monthofyear} ${3:dayofmonth} ${4:year} ${5:packager} - ${6:version}-${7:release}
- $8
"""
# unlike gedit snippets, static snippets like these
# are fixed strings - no variables or expansions
| true | #
# Copyright (c) 2015 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
#
# All modifications and additions to the file contributed by third parties
# remain the property of their copyright owners, unless otherwise agreed
# upon. The license for this file, and modifications and additions to the
# file, is the same license as for the pristine package itself (unless the
# license for the pristine package is not an Open Source License, in which
# case the license is the MIT License). An "Open Source License" is a
# license that conforms to the Open Source Definition (Version 1.9)
# published by the Open Source Initiative.
#
# Please submit bugfixes or comments via
# https://github.com/waveclaw/language-rpm-spec/issues
#
'.source.rpm-spec':
'subpackage':
'prefix': '%pack'
'body': """
%package $1
Group: foo
Summary: bar
%description $1
baz
%files $1
"""
'build':
'prefix': '%bld'
'body': """
%build
%configure
%if %{defined make_jobs}
%{make_jobs} %{?_smp_mflags}
%else
%{__make} %{?_smp_mflags}
%endif
"""
'install':
'prefix': '%inst'
'body': """
%install
%{__make} install DESTDIR=%{buildroot} %{?_smp_mflags}
"""
'changelog entry':
'prefix': 'chi'
'body': """
* ${1:weekday} ${2:monthofyear} ${3:dayofmonth} ${4:year} ${5:packager} - ${6:version}-${7:release}
- $8
"""
# unlike gedit snippets, static snippets like these
# are fixed strings - no variables or expansions
|
[
{
"context": "ents\n\n\t### \n\t Query would be something like ?name=craig&last=condon\n\t###\n\n\tquery: (value) -> @_param 'que",
"end": 1906,
"score": 0.6675245761871338,
"start": 1901,
"tag": "NAME",
"value": "craig"
}
] | src/request.coffee | crcn-archive/beanpoll.js | 1 | Reader = require "./io/reader"
Writer = require "./io/writer"
outcome = require "outcome"
exports.Reader = class RequestReader extends Reader
###
constructor
###
constructor: (@writer, @from, @path, @query, @sanitized = {}, @headers = {}, @filter = {}, @callback = null) ->
super writer
exports.Writer = class RequestWriter extends Writer
###
###
constructor: (@_ops) ->
@next = _ops.next
@pre = _ops.pre
@path = _ops.path
@type = _ops.type
@from = _ops.from
@query = _ops.query
@filter = _ops.filter or {}
@headers = _ops.headers
@callback = _ops.callback
@sanitized = _ops.sanitized
super()
###
###
reader: () ->
return new RequestReader @,
@from,
@path,
@query,
@sanitized,
@headers,
@filter,
@callback
exports.Builder = class
###
###
constructor: (@router) -> @clean()
###
options which control how the request
is handled. This can fill out the entire request vs using the methods given
###
options: (value) ->
return @_ops if !arguments.length
@_ops = value || {}
@
###
###
clean: () ->
@_ops = {}
@from(@router)
###
filterable tags
DEPRECATED
###
tag: (keyOrTags, value) ->
@_objParam 'filter', arguments, (value) ->
if typeof value == 'boolean'
return { $exists: value }
return value
filter: (keyOrTag, value) ->
@tag keyOrTag, value
###
DEPRECATED
###
headers: (value) -> @header value
###
The header data explaining the request, such as tags, content type, etc.
###
header: (keyOrHeaders, value) -> @_objParam 'headers', arguments
###
###
type: (value) -> @_param 'type', arguments
###
###
from: (value) -> @_param 'from', arguments
###
###
to: (value) -> @_param 'to', arguments
###
###
path: (value) -> @_param 'path', arguments
###
Query would be something like ?name=craig&last=condon
###
query: (value) -> @_param 'query', arguments
###
data that has been cleaned up after validation
###
sanitized: (value) -> @_param 'sanitized', arguments
###
response handler, or ack
deprecated
###
response: (callback) -> @_param 'response', arguments
###
on error callback
###
error: (callback) -> @_param 'error', arguments
###
on success callback
###
success: (callback) -> @_param 'success', arguments
###
append middleware to the end
###
next: (middleware) -> @_param 'next', arguments
###
prepend middleware
###
pre: (middleware) -> @_param 'pre', arguments
###
###
dispatch: (type) ->
@_ops.callback = outcome error: @error(), success: @success(), callback: @response()
@type type if type
writer = new RequestWriter @_ops
@router.dispatch writer
writer
###
DEPRECATED
###
hasListeners: () -> @exists()
###
###
exists: () -> !!@listeners().length
###
###
listeners: () -> @router.director(@type()).getListeners({path: @_ops.path, filter: @_ops.filter }, false)
###
###
_param: (name, args) ->
return @_ops[name] if !args.length
@_ops[name] = args[0]
@
###
###
_objParam: (name, args, getValue) ->
return @_ops[name] if !args.length
@_ops[name] = {} if not @_ops[name]
keyOrObj = args[0]
value = args[1]
# obj(key, value)
if typeof keyOrObj == 'string'
# just one arg passed? return the value
if args.length == 1 then return @_ops.headers[keyOrObj]
@_ops[name][keyOrObj] = if getValue then getValue value else value
else
@_objParam name, [key, keyOrObj[key]], getValue for key of keyOrObj
@
| 120542 | Reader = require "./io/reader"
Writer = require "./io/writer"
outcome = require "outcome"
exports.Reader = class RequestReader extends Reader
###
constructor
###
constructor: (@writer, @from, @path, @query, @sanitized = {}, @headers = {}, @filter = {}, @callback = null) ->
super writer
exports.Writer = class RequestWriter extends Writer
###
###
constructor: (@_ops) ->
@next = _ops.next
@pre = _ops.pre
@path = _ops.path
@type = _ops.type
@from = _ops.from
@query = _ops.query
@filter = _ops.filter or {}
@headers = _ops.headers
@callback = _ops.callback
@sanitized = _ops.sanitized
super()
###
###
reader: () ->
return new RequestReader @,
@from,
@path,
@query,
@sanitized,
@headers,
@filter,
@callback
exports.Builder = class
###
###
constructor: (@router) -> @clean()
###
options which control how the request
is handled. This can fill out the entire request vs using the methods given
###
options: (value) ->
return @_ops if !arguments.length
@_ops = value || {}
@
###
###
clean: () ->
@_ops = {}
@from(@router)
###
filterable tags
DEPRECATED
###
tag: (keyOrTags, value) ->
@_objParam 'filter', arguments, (value) ->
if typeof value == 'boolean'
return { $exists: value }
return value
filter: (keyOrTag, value) ->
@tag keyOrTag, value
###
DEPRECATED
###
headers: (value) -> @header value
###
The header data explaining the request, such as tags, content type, etc.
###
header: (keyOrHeaders, value) -> @_objParam 'headers', arguments
###
###
type: (value) -> @_param 'type', arguments
###
###
from: (value) -> @_param 'from', arguments
###
###
to: (value) -> @_param 'to', arguments
###
###
path: (value) -> @_param 'path', arguments
###
Query would be something like ?name=<NAME>&last=condon
###
query: (value) -> @_param 'query', arguments
###
data that has been cleaned up after validation
###
sanitized: (value) -> @_param 'sanitized', arguments
###
response handler, or ack
deprecated
###
response: (callback) -> @_param 'response', arguments
###
on error callback
###
error: (callback) -> @_param 'error', arguments
###
on success callback
###
success: (callback) -> @_param 'success', arguments
###
append middleware to the end
###
next: (middleware) -> @_param 'next', arguments
###
prepend middleware
###
pre: (middleware) -> @_param 'pre', arguments
###
###
dispatch: (type) ->
@_ops.callback = outcome error: @error(), success: @success(), callback: @response()
@type type if type
writer = new RequestWriter @_ops
@router.dispatch writer
writer
###
DEPRECATED
###
hasListeners: () -> @exists()
###
###
exists: () -> !!@listeners().length
###
###
listeners: () -> @router.director(@type()).getListeners({path: @_ops.path, filter: @_ops.filter }, false)
###
###
_param: (name, args) ->
return @_ops[name] if !args.length
@_ops[name] = args[0]
@
###
###
_objParam: (name, args, getValue) ->
return @_ops[name] if !args.length
@_ops[name] = {} if not @_ops[name]
keyOrObj = args[0]
value = args[1]
# obj(key, value)
if typeof keyOrObj == 'string'
# just one arg passed? return the value
if args.length == 1 then return @_ops.headers[keyOrObj]
@_ops[name][keyOrObj] = if getValue then getValue value else value
else
@_objParam name, [key, keyOrObj[key]], getValue for key of keyOrObj
@
| true | Reader = require "./io/reader"
Writer = require "./io/writer"
outcome = require "outcome"
exports.Reader = class RequestReader extends Reader
###
constructor
###
constructor: (@writer, @from, @path, @query, @sanitized = {}, @headers = {}, @filter = {}, @callback = null) ->
super writer
exports.Writer = class RequestWriter extends Writer
###
###
constructor: (@_ops) ->
@next = _ops.next
@pre = _ops.pre
@path = _ops.path
@type = _ops.type
@from = _ops.from
@query = _ops.query
@filter = _ops.filter or {}
@headers = _ops.headers
@callback = _ops.callback
@sanitized = _ops.sanitized
super()
###
###
reader: () ->
return new RequestReader @,
@from,
@path,
@query,
@sanitized,
@headers,
@filter,
@callback
exports.Builder = class
###
###
constructor: (@router) -> @clean()
###
options which control how the request
is handled. This can fill out the entire request vs using the methods given
###
options: (value) ->
return @_ops if !arguments.length
@_ops = value || {}
@
###
###
clean: () ->
@_ops = {}
@from(@router)
###
filterable tags
DEPRECATED
###
tag: (keyOrTags, value) ->
@_objParam 'filter', arguments, (value) ->
if typeof value == 'boolean'
return { $exists: value }
return value
filter: (keyOrTag, value) ->
@tag keyOrTag, value
###
DEPRECATED
###
headers: (value) -> @header value
###
The header data explaining the request, such as tags, content type, etc.
###
header: (keyOrHeaders, value) -> @_objParam 'headers', arguments
###
###
type: (value) -> @_param 'type', arguments
###
###
from: (value) -> @_param 'from', arguments
###
###
to: (value) -> @_param 'to', arguments
###
###
path: (value) -> @_param 'path', arguments
###
Query would be something like ?name=PI:NAME:<NAME>END_PI&last=condon
###
query: (value) -> @_param 'query', arguments
###
data that has been cleaned up after validation
###
sanitized: (value) -> @_param 'sanitized', arguments
###
response handler, or ack
deprecated
###
response: (callback) -> @_param 'response', arguments
###
on error callback
###
error: (callback) -> @_param 'error', arguments
###
on success callback
###
success: (callback) -> @_param 'success', arguments
###
append middleware to the end
###
next: (middleware) -> @_param 'next', arguments
###
prepend middleware
###
pre: (middleware) -> @_param 'pre', arguments
###
###
dispatch: (type) ->
@_ops.callback = outcome error: @error(), success: @success(), callback: @response()
@type type if type
writer = new RequestWriter @_ops
@router.dispatch writer
writer
###
DEPRECATED
###
hasListeners: () -> @exists()
###
###
exists: () -> !!@listeners().length
###
###
listeners: () -> @router.director(@type()).getListeners({path: @_ops.path, filter: @_ops.filter }, false)
###
###
_param: (name, args) ->
return @_ops[name] if !args.length
@_ops[name] = args[0]
@
###
###
_objParam: (name, args, getValue) ->
return @_ops[name] if !args.length
@_ops[name] = {} if not @_ops[name]
keyOrObj = args[0]
value = args[1]
# obj(key, value)
if typeof keyOrObj == 'string'
# just one arg passed? return the value
if args.length == 1 then return @_ops.headers[keyOrObj]
@_ops[name][keyOrObj] = if getValue then getValue value else value
else
@_objParam name, [key, keyOrObj[key]], getValue for key of keyOrObj
@
|
[
{
"context": "gain. If you're still having issues, contact us at support@nylas.com.\"\n @_resize()\n\n _onNetworkError: (err) =>\n ",
"end": 13000,
"score": 0.9999259114265442,
"start": 12983,
"tag": "EMAIL",
"value": "support@nylas.com"
}
] | app/internal_packages/onboarding/lib/account-settings-page.cjsx | immershy/nodemail | 0 | React = require 'react'
ReactDOM = require 'react-dom'
_ = require 'underscore'
{ipcRenderer, dialog, remote} = require 'electron'
{RetinaImg} = require 'nylas-component-kit'
{RegExpUtils, EdgehillAPI, NylasAPI, APIError, Actions, AccountStore} = require 'nylas-exports'
OnboardingActions = require './onboarding-actions'
NylasApiEnvironmentStore = require './nylas-api-environment-store'
Providers = require './account-types'
class AccountSettingsPage extends React.Component
@displayName: "AccountSettingsPage"
constructor: (@props) ->
@state =
provider: @props.pageData.provider
settings: {}
fields: {}
pageNumber: 0
errorFieldNames: []
errorMessage: null
show_advanced: false
@props.pageData.provider.settings.forEach (field) =>
if field.default?
@state.settings[field.name] = field.default
# Special case for gmail. Rather than showing a form, we poll in the
# background for completion of the gmail auth on the server.
if @state.provider.name is 'gmail'
pollAttemptId = 0
done = false
# polling with capped exponential backoff
delay = 1000
tries = 0
poll = (id,initial_delay) =>
_retry = =>
tries++
@_pollForGmailAccount((account_data) =>
if account_data?
done = true
{data} = account_data
account = JSON.parse(data)
@_onAccountReceived(account)
else if tries < 20 and id is pollAttemptId
setTimeout(_retry, delay)
delay *= 1.2 # exponential backoff
)
setTimeout(_retry,initial_delay)
ipcRenderer.on('browser-window-focus', ->
if not done # hack to deactivate this listener when done
pollAttemptId++
poll(pollAttemptId,0)
)
poll(pollAttemptId,5000)
render: ->
<div className="page account-setup">
<div className="logo-container">
<RetinaImg
name={@state.provider.header_icon}
mode={RetinaImg.Mode.ContentPreserve}
className="logo"/>
</div>
{@_renderTitle()}
<div className="back" onClick={@_fireMoveToPrevPage}>
<RetinaImg
name="onboarding-back.png"
mode={RetinaImg.Mode.ContentPreserve}/>
</div>
{@_renderErrorMessage()}
<form className="settings">
{@_renderFields()}
{@_renderSettings()}
{@_renderButton()}
</form>
</div>
componentDidMount: =>
@_applyFocus()
componentDidUpdate: =>
@_applyFocus()
_applyFocus: =>
firstInput = ReactDOM.findDOMNode(@).querySelector('input')
anyInputFocused = document.activeElement and document.activeElement.nodeName is 'INPUT'
if firstInput and not anyInputFocused
firstInput.focus()
_onSettingsChanged: (event) =>
# NOTE: This code is largely duplicated in _onValueChanged. TODO Fix!
{field, format} = event.target.dataset
intFormatter = (a) ->
i = parseInt(a)
if isNaN(i) then "" else i
formatter = if format is 'integer' then intFormatter else (a) -> a
settings = @state.settings
if event.target.type is 'checkbox'
settings[field] = event.target.checked
else
settings[field] = formatter(event.target.value)
settingField = _.findWhere(@state.provider.settings, {name: field})
# If the field defines an isValid method, try to validate
# the input.
if settingField
valueIsValid = not settingField.isValid? or settingField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = settingField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
@setState({settings})
_noFormErrors: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
fieldsOnThisPage = allFields.filter(@_fieldOnCurrentPage)
fieldNames = _.pluck(fieldsOnThisPage, 'name')
return _.intersection(fieldNames, @state.errorFieldNames).length == 0
_fieldRequired: (f) =>
return f?.required == true
_allRequiredFieldsFilled: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
requiredFields = allFields.filter(@_fieldOnCurrentPage).filter(@_fieldRequired)
fields = _.extend({}, @state.fields, @state.settings)
for field in requiredFields
fieldName = field['name']
if not (fieldName of fields) or fields[fieldName] == ''
return false
return true
_onValueChanged: (event) =>
# NOTE: This code is largely duplicated in _onSettingsChanged. TODO Fix!
field = event.target.dataset.field
fields = @state.fields
fields[field] = event.target.value
providerField = _.find(@state.provider.fields, ((e) -> return e['name'] == field))
# If the field defines an isValid method, try to validate
# the input.
if providerField
valueIsValid = not providerField.isValid? or providerField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = providerField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
if providerField.type == "email" and event.target.value
if event.target.value.endsWith('@gmail.com')
# set a state that contains a "this is a gmail account" message
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
@setState
errorMessage: "This looks like a Gmail account. You should go back and sign in to Gmail instead."
errorFieldNames: errorFields
@_resize()
else
@setState({errorMessage: null})
@_resize()
@setState({fields})
_onFieldKeyPress: (event) =>
if event.key in ['Enter', 'Return']
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
@_onNextButton()
else
@_onSubmit()
_renderTitle: =>
if @state.provider.name is 'gmail'
<h2>
Sign in to Google in<br/>your browser.
</h2>
else if @state.provider.pages?.length > 0
<h2>
{@state.provider.pages[@state.pageNumber]}
</h2>
else
<h2>
Sign in to {@state.provider.displayName}
</h2>
_renderErrorMessage: =>
return unless @state.errorMessage
text = @state.errorMessage
result = RegExpUtils.urlRegex(matchEntireString: false).exec(text)
if result
link = result[0]
beforeText = text.substr(0, result.index)
afterText = text.substr(result.index + link.length)
return (
<div className="errormsg">
{beforeText}<a href={link}>{link}</a>{afterText}
</div>
)
else
return (
<div className="errormsg">
{text}
</div>
)
_fieldOnCurrentPage: (field) =>
!@state.provider.pages || field.page is @state.pageNumber
_renderFields: =>
@state.provider.fields?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={(field.className || "")} key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 1}
value={@state.fields[field.name]}
onChange={@_onValueChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass}
placeholder={field.placeholder} />
</label>
_renderSettings: =>
@state.provider.settings?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
if field.type is 'checkbox'
<label className={"checkbox #{field.className ? ""}"} key={field.name}>
<input type={field.type}
tabIndex={idx + 5}
checked={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
disabled={@state.tryingToAuthenticate}
data-format={field.format ? ""}
className={field.className ? ""} />
{field.label}
</label>
else
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={field.className ? ""}
style={if field.advanced and not @state.show_advanced then {display:'none'} else {}}
key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 5}
value={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass+(field.className ? "")}
placeholder={field.placeholder} />
</label>
_renderButton: =>
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
# We're not on the last page.
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient" onClick={@_onNextButton}>Continue</button>
else
# Disable the "Continue" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-disabled">Continue</button>
else if @state.provider.name isnt 'gmail'
if @state.tryingToAuthenticate
<button className="btn btn-large btn-disabled btn-add-account-spinning">
<RetinaImg name="sending-spinner.gif" width={15} height={15} mode={RetinaImg.Mode.ContentPreserve} /> Adding account…
</button>
else
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient btn-add-account" onClick={@_onSubmit}>Add account</button>
else
# Disable the "Add Account" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-add-account btn-disabled">Add account</button>
_onNextButton: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
@setState(pageNumber: @state.pageNumber + 1)
@_resize()
_onSubmit: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
return if @state.tryingToAuthenticate
data = settings: {}
for own k,v of @state.fields when v isnt ''
data[k] = v
for own k,v of @state.settings when v isnt ''
data.settings[k] = v
data.provider = @state.provider.name
# if there's an account with this email, get the ID for it to notify the backend of re-auth
account = AccountStore.accountForEmail(data.email)
reauthParam = if account then "&reauth=#{account.id}" else ""
# handle special case for exchange/outlook/hotmail username field
if data.provider in ['exchange','outlook','hotmail'] and not data.settings.username?.trim().length
data.settings.username = data.email
@setState(tryingToAuthenticate: true)
# Send the form data directly to Nylas to get code
# If this succeeds, send the received code to N1 server to register the account
# Otherwise process the error message from the server and highlight UI as needed
NylasAPI.makeRequest
path: "/auth?client_id=#{NylasAPI.AppID}&n1_id=#{NylasEnv.config.get('updateIdentity')}#{reauthParam}"
method: 'POST'
body: data
returnsModel: false
timeout: 60000
auth:
user: ''
pass: ''
sendImmediately: true
.then (json) =>
invite_code = NylasEnv.config.get('invitationCode')
json.invite_code = invite_code
json.email = data.email
EdgehillAPI.request
path: "/connect/nylas"
method: "POST"
timeout: 60000
body: json
success: @_onAccountReceived
error: @_onNetworkError
.catch(@_onNetworkError)
_onAccountReceived: (json) =>
Actions.recordUserEvent('Auth Successful', {
provider: @state.provider.name
})
try
OnboardingActions.accountJSONReceived(json)
catch e
NylasEnv.reportError(e)
@setState
tryingToAuthenticate: false
errorMessage: "Sorry, something went wrong on the Nylas server. Please try again. If you're still having issues, contact us at support@nylas.com."
@_resize()
_onNetworkError: (err) =>
errorMessage = err.message
Actions.recordUserEvent('Auth Failed', {
errorMessage: errorMessage
provider: @state.provider.name
})
if errorMessage is "Invite code required"
choice = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'info',
buttons: ['Okay'],
title: 'Confirm',
message: 'Due to a large number of sign-ups this week, you’ll need an invitation code to add another account! Visit http://invite.nylas.com/ to grab one, or hold tight!'
})
OnboardingActions.moveToPage("token-auth")
if errorMessage is "Invalid invite code"
OnboardingActions.moveToPage("token-auth")
pageNumber = @state.pageNumber
errorFieldNames = err.body?.missing_fields || err.body?.missing_settings
if err.errorTitle is "setting_update_error"
@setState
tryingToAuthenticate: false
errorMessage: 'The IMAP/SMTP servers for this account do not match our records. Please verify that any server names you entered are correct. If your IMAP/SMTP server has changed, first remove this account from N1, then try logging in again.'
@_resize()
OnboardingActions.moveToPage("account-settings")
return
if errorFieldNames
{pageNumber, errorMessage} = @_stateForMissingFieldNames(errorFieldNames)
if err.statusCode is -123 # timeout
errorMessage = "Request timed out. Please try again."
@setState
pageNumber: pageNumber
errorMessage: errorMessage
errorFieldNames: errorFieldNames || []
tryingToAuthenticate: false
@_resize()
_stateForMissingFieldNames: (fieldNames) ->
fieldLabels = []
fields = [].concat(@state.provider.settings, @state.provider.fields)
pageNumbers = [@state.pageNumber]
for fieldName in fieldNames
for s in fields when s.name is fieldName
fieldLabels.push(s.label.toLowerCase())
if s.page isnt undefined
pageNumbers.push(s.page)
pageNumber = Math.min.apply(null, pageNumbers)
errorMessage = @_messageForFieldLabels(fieldLabels)
{pageNumber, errorMessage}
_messageForFieldLabels: (labels) ->
if labels.length > 2
return "Please fix the highlighted fields."
else if labels.length is 2
return "Please provide your #{labels[0]} and #{labels[1]}."
else
return "Please provide your #{labels[0]}."
_pollForGmailAccount: (callback) =>
EdgehillAPI.request
path: "/oauth/google/token?key="+@state.provider.clientKey
method: "GET"
success: (json) =>
callback(json)
error: (err) =>
callback()
_resize: =>
setTimeout( =>
@props.onResize?()
, 10)
_fireMoveToPrevPage: =>
if @state.pageNumber > 0
@setState(pageNumber: @state.pageNumber - 1)
@_resize()
else
OnboardingActions.moveToPreviousPage()
module.exports = AccountSettingsPage
| 129405 | React = require 'react'
ReactDOM = require 'react-dom'
_ = require 'underscore'
{ipcRenderer, dialog, remote} = require 'electron'
{RetinaImg} = require 'nylas-component-kit'
{RegExpUtils, EdgehillAPI, NylasAPI, APIError, Actions, AccountStore} = require 'nylas-exports'
OnboardingActions = require './onboarding-actions'
NylasApiEnvironmentStore = require './nylas-api-environment-store'
Providers = require './account-types'
class AccountSettingsPage extends React.Component
@displayName: "AccountSettingsPage"
constructor: (@props) ->
@state =
provider: @props.pageData.provider
settings: {}
fields: {}
pageNumber: 0
errorFieldNames: []
errorMessage: null
show_advanced: false
@props.pageData.provider.settings.forEach (field) =>
if field.default?
@state.settings[field.name] = field.default
# Special case for gmail. Rather than showing a form, we poll in the
# background for completion of the gmail auth on the server.
if @state.provider.name is 'gmail'
pollAttemptId = 0
done = false
# polling with capped exponential backoff
delay = 1000
tries = 0
poll = (id,initial_delay) =>
_retry = =>
tries++
@_pollForGmailAccount((account_data) =>
if account_data?
done = true
{data} = account_data
account = JSON.parse(data)
@_onAccountReceived(account)
else if tries < 20 and id is pollAttemptId
setTimeout(_retry, delay)
delay *= 1.2 # exponential backoff
)
setTimeout(_retry,initial_delay)
ipcRenderer.on('browser-window-focus', ->
if not done # hack to deactivate this listener when done
pollAttemptId++
poll(pollAttemptId,0)
)
poll(pollAttemptId,5000)
render: ->
<div className="page account-setup">
<div className="logo-container">
<RetinaImg
name={@state.provider.header_icon}
mode={RetinaImg.Mode.ContentPreserve}
className="logo"/>
</div>
{@_renderTitle()}
<div className="back" onClick={@_fireMoveToPrevPage}>
<RetinaImg
name="onboarding-back.png"
mode={RetinaImg.Mode.ContentPreserve}/>
</div>
{@_renderErrorMessage()}
<form className="settings">
{@_renderFields()}
{@_renderSettings()}
{@_renderButton()}
</form>
</div>
componentDidMount: =>
@_applyFocus()
componentDidUpdate: =>
@_applyFocus()
_applyFocus: =>
firstInput = ReactDOM.findDOMNode(@).querySelector('input')
anyInputFocused = document.activeElement and document.activeElement.nodeName is 'INPUT'
if firstInput and not anyInputFocused
firstInput.focus()
_onSettingsChanged: (event) =>
# NOTE: This code is largely duplicated in _onValueChanged. TODO Fix!
{field, format} = event.target.dataset
intFormatter = (a) ->
i = parseInt(a)
if isNaN(i) then "" else i
formatter = if format is 'integer' then intFormatter else (a) -> a
settings = @state.settings
if event.target.type is 'checkbox'
settings[field] = event.target.checked
else
settings[field] = formatter(event.target.value)
settingField = _.findWhere(@state.provider.settings, {name: field})
# If the field defines an isValid method, try to validate
# the input.
if settingField
valueIsValid = not settingField.isValid? or settingField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = settingField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
@setState({settings})
_noFormErrors: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
fieldsOnThisPage = allFields.filter(@_fieldOnCurrentPage)
fieldNames = _.pluck(fieldsOnThisPage, 'name')
return _.intersection(fieldNames, @state.errorFieldNames).length == 0
_fieldRequired: (f) =>
return f?.required == true
_allRequiredFieldsFilled: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
requiredFields = allFields.filter(@_fieldOnCurrentPage).filter(@_fieldRequired)
fields = _.extend({}, @state.fields, @state.settings)
for field in requiredFields
fieldName = field['name']
if not (fieldName of fields) or fields[fieldName] == ''
return false
return true
_onValueChanged: (event) =>
# NOTE: This code is largely duplicated in _onSettingsChanged. TODO Fix!
field = event.target.dataset.field
fields = @state.fields
fields[field] = event.target.value
providerField = _.find(@state.provider.fields, ((e) -> return e['name'] == field))
# If the field defines an isValid method, try to validate
# the input.
if providerField
valueIsValid = not providerField.isValid? or providerField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = providerField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
if providerField.type == "email" and event.target.value
if event.target.value.endsWith('@gmail.com')
# set a state that contains a "this is a gmail account" message
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
@setState
errorMessage: "This looks like a Gmail account. You should go back and sign in to Gmail instead."
errorFieldNames: errorFields
@_resize()
else
@setState({errorMessage: null})
@_resize()
@setState({fields})
_onFieldKeyPress: (event) =>
if event.key in ['Enter', 'Return']
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
@_onNextButton()
else
@_onSubmit()
_renderTitle: =>
if @state.provider.name is 'gmail'
<h2>
Sign in to Google in<br/>your browser.
</h2>
else if @state.provider.pages?.length > 0
<h2>
{@state.provider.pages[@state.pageNumber]}
</h2>
else
<h2>
Sign in to {@state.provider.displayName}
</h2>
_renderErrorMessage: =>
return unless @state.errorMessage
text = @state.errorMessage
result = RegExpUtils.urlRegex(matchEntireString: false).exec(text)
if result
link = result[0]
beforeText = text.substr(0, result.index)
afterText = text.substr(result.index + link.length)
return (
<div className="errormsg">
{beforeText}<a href={link}>{link}</a>{afterText}
</div>
)
else
return (
<div className="errormsg">
{text}
</div>
)
_fieldOnCurrentPage: (field) =>
!@state.provider.pages || field.page is @state.pageNumber
_renderFields: =>
@state.provider.fields?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={(field.className || "")} key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 1}
value={@state.fields[field.name]}
onChange={@_onValueChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass}
placeholder={field.placeholder} />
</label>
_renderSettings: =>
@state.provider.settings?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
if field.type is 'checkbox'
<label className={"checkbox #{field.className ? ""}"} key={field.name}>
<input type={field.type}
tabIndex={idx + 5}
checked={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
disabled={@state.tryingToAuthenticate}
data-format={field.format ? ""}
className={field.className ? ""} />
{field.label}
</label>
else
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={field.className ? ""}
style={if field.advanced and not @state.show_advanced then {display:'none'} else {}}
key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 5}
value={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass+(field.className ? "")}
placeholder={field.placeholder} />
</label>
_renderButton: =>
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
# We're not on the last page.
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient" onClick={@_onNextButton}>Continue</button>
else
# Disable the "Continue" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-disabled">Continue</button>
else if @state.provider.name isnt 'gmail'
if @state.tryingToAuthenticate
<button className="btn btn-large btn-disabled btn-add-account-spinning">
<RetinaImg name="sending-spinner.gif" width={15} height={15} mode={RetinaImg.Mode.ContentPreserve} /> Adding account…
</button>
else
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient btn-add-account" onClick={@_onSubmit}>Add account</button>
else
# Disable the "Add Account" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-add-account btn-disabled">Add account</button>
_onNextButton: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
@setState(pageNumber: @state.pageNumber + 1)
@_resize()
_onSubmit: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
return if @state.tryingToAuthenticate
data = settings: {}
for own k,v of @state.fields when v isnt ''
data[k] = v
for own k,v of @state.settings when v isnt ''
data.settings[k] = v
data.provider = @state.provider.name
# if there's an account with this email, get the ID for it to notify the backend of re-auth
account = AccountStore.accountForEmail(data.email)
reauthParam = if account then "&reauth=#{account.id}" else ""
# handle special case for exchange/outlook/hotmail username field
if data.provider in ['exchange','outlook','hotmail'] and not data.settings.username?.trim().length
data.settings.username = data.email
@setState(tryingToAuthenticate: true)
# Send the form data directly to Nylas to get code
# If this succeeds, send the received code to N1 server to register the account
# Otherwise process the error message from the server and highlight UI as needed
NylasAPI.makeRequest
path: "/auth?client_id=#{NylasAPI.AppID}&n1_id=#{NylasEnv.config.get('updateIdentity')}#{reauthParam}"
method: 'POST'
body: data
returnsModel: false
timeout: 60000
auth:
user: ''
pass: ''
sendImmediately: true
.then (json) =>
invite_code = NylasEnv.config.get('invitationCode')
json.invite_code = invite_code
json.email = data.email
EdgehillAPI.request
path: "/connect/nylas"
method: "POST"
timeout: 60000
body: json
success: @_onAccountReceived
error: @_onNetworkError
.catch(@_onNetworkError)
_onAccountReceived: (json) =>
Actions.recordUserEvent('Auth Successful', {
provider: @state.provider.name
})
try
OnboardingActions.accountJSONReceived(json)
catch e
NylasEnv.reportError(e)
@setState
tryingToAuthenticate: false
errorMessage: "Sorry, something went wrong on the Nylas server. Please try again. If you're still having issues, contact us at <EMAIL>."
@_resize()
_onNetworkError: (err) =>
errorMessage = err.message
Actions.recordUserEvent('Auth Failed', {
errorMessage: errorMessage
provider: @state.provider.name
})
if errorMessage is "Invite code required"
choice = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'info',
buttons: ['Okay'],
title: 'Confirm',
message: 'Due to a large number of sign-ups this week, you’ll need an invitation code to add another account! Visit http://invite.nylas.com/ to grab one, or hold tight!'
})
OnboardingActions.moveToPage("token-auth")
if errorMessage is "Invalid invite code"
OnboardingActions.moveToPage("token-auth")
pageNumber = @state.pageNumber
errorFieldNames = err.body?.missing_fields || err.body?.missing_settings
if err.errorTitle is "setting_update_error"
@setState
tryingToAuthenticate: false
errorMessage: 'The IMAP/SMTP servers for this account do not match our records. Please verify that any server names you entered are correct. If your IMAP/SMTP server has changed, first remove this account from N1, then try logging in again.'
@_resize()
OnboardingActions.moveToPage("account-settings")
return
if errorFieldNames
{pageNumber, errorMessage} = @_stateForMissingFieldNames(errorFieldNames)
if err.statusCode is -123 # timeout
errorMessage = "Request timed out. Please try again."
@setState
pageNumber: pageNumber
errorMessage: errorMessage
errorFieldNames: errorFieldNames || []
tryingToAuthenticate: false
@_resize()
_stateForMissingFieldNames: (fieldNames) ->
fieldLabels = []
fields = [].concat(@state.provider.settings, @state.provider.fields)
pageNumbers = [@state.pageNumber]
for fieldName in fieldNames
for s in fields when s.name is fieldName
fieldLabels.push(s.label.toLowerCase())
if s.page isnt undefined
pageNumbers.push(s.page)
pageNumber = Math.min.apply(null, pageNumbers)
errorMessage = @_messageForFieldLabels(fieldLabels)
{pageNumber, errorMessage}
_messageForFieldLabels: (labels) ->
if labels.length > 2
return "Please fix the highlighted fields."
else if labels.length is 2
return "Please provide your #{labels[0]} and #{labels[1]}."
else
return "Please provide your #{labels[0]}."
_pollForGmailAccount: (callback) =>
EdgehillAPI.request
path: "/oauth/google/token?key="+@state.provider.clientKey
method: "GET"
success: (json) =>
callback(json)
error: (err) =>
callback()
_resize: =>
setTimeout( =>
@props.onResize?()
, 10)
_fireMoveToPrevPage: =>
if @state.pageNumber > 0
@setState(pageNumber: @state.pageNumber - 1)
@_resize()
else
OnboardingActions.moveToPreviousPage()
module.exports = AccountSettingsPage
| true | React = require 'react'
ReactDOM = require 'react-dom'
_ = require 'underscore'
{ipcRenderer, dialog, remote} = require 'electron'
{RetinaImg} = require 'nylas-component-kit'
{RegExpUtils, EdgehillAPI, NylasAPI, APIError, Actions, AccountStore} = require 'nylas-exports'
OnboardingActions = require './onboarding-actions'
NylasApiEnvironmentStore = require './nylas-api-environment-store'
Providers = require './account-types'
class AccountSettingsPage extends React.Component
@displayName: "AccountSettingsPage"
constructor: (@props) ->
@state =
provider: @props.pageData.provider
settings: {}
fields: {}
pageNumber: 0
errorFieldNames: []
errorMessage: null
show_advanced: false
@props.pageData.provider.settings.forEach (field) =>
if field.default?
@state.settings[field.name] = field.default
# Special case for gmail. Rather than showing a form, we poll in the
# background for completion of the gmail auth on the server.
if @state.provider.name is 'gmail'
pollAttemptId = 0
done = false
# polling with capped exponential backoff
delay = 1000
tries = 0
poll = (id,initial_delay) =>
_retry = =>
tries++
@_pollForGmailAccount((account_data) =>
if account_data?
done = true
{data} = account_data
account = JSON.parse(data)
@_onAccountReceived(account)
else if tries < 20 and id is pollAttemptId
setTimeout(_retry, delay)
delay *= 1.2 # exponential backoff
)
setTimeout(_retry,initial_delay)
ipcRenderer.on('browser-window-focus', ->
if not done # hack to deactivate this listener when done
pollAttemptId++
poll(pollAttemptId,0)
)
poll(pollAttemptId,5000)
render: ->
<div className="page account-setup">
<div className="logo-container">
<RetinaImg
name={@state.provider.header_icon}
mode={RetinaImg.Mode.ContentPreserve}
className="logo"/>
</div>
{@_renderTitle()}
<div className="back" onClick={@_fireMoveToPrevPage}>
<RetinaImg
name="onboarding-back.png"
mode={RetinaImg.Mode.ContentPreserve}/>
</div>
{@_renderErrorMessage()}
<form className="settings">
{@_renderFields()}
{@_renderSettings()}
{@_renderButton()}
</form>
</div>
componentDidMount: =>
@_applyFocus()
componentDidUpdate: =>
@_applyFocus()
_applyFocus: =>
firstInput = ReactDOM.findDOMNode(@).querySelector('input')
anyInputFocused = document.activeElement and document.activeElement.nodeName is 'INPUT'
if firstInput and not anyInputFocused
firstInput.focus()
_onSettingsChanged: (event) =>
# NOTE: This code is largely duplicated in _onValueChanged. TODO Fix!
{field, format} = event.target.dataset
intFormatter = (a) ->
i = parseInt(a)
if isNaN(i) then "" else i
formatter = if format is 'integer' then intFormatter else (a) -> a
settings = @state.settings
if event.target.type is 'checkbox'
settings[field] = event.target.checked
else
settings[field] = formatter(event.target.value)
settingField = _.findWhere(@state.provider.settings, {name: field})
# If the field defines an isValid method, try to validate
# the input.
if settingField
valueIsValid = not settingField.isValid? or settingField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = settingField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
@setState({settings})
_noFormErrors: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
fieldsOnThisPage = allFields.filter(@_fieldOnCurrentPage)
fieldNames = _.pluck(fieldsOnThisPage, 'name')
return _.intersection(fieldNames, @state.errorFieldNames).length == 0
_fieldRequired: (f) =>
return f?.required == true
_allRequiredFieldsFilled: =>
allFields = @state.provider.fields.concat(@state.provider.settings || [])
requiredFields = allFields.filter(@_fieldOnCurrentPage).filter(@_fieldRequired)
fields = _.extend({}, @state.fields, @state.settings)
for field in requiredFields
fieldName = field['name']
if not (fieldName of fields) or fields[fieldName] == ''
return false
return true
_onValueChanged: (event) =>
# NOTE: This code is largely duplicated in _onSettingsChanged. TODO Fix!
field = event.target.dataset.field
fields = @state.fields
fields[field] = event.target.value
providerField = _.find(@state.provider.fields, ((e) -> return e['name'] == field))
# If the field defines an isValid method, try to validate
# the input.
if providerField
valueIsValid = not providerField.isValid? or providerField.isValid(event.target.value)
valueIsPresent = event.target.value and event.target.value.length > 0
valueIsRequired = providerField.required is true
if (not valueIsPresent and valueIsRequired) or (valueIsPresent and not valueIsValid)
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
else
errorFields = _.uniq(_.without(@state.errorFieldNames, field))
@setState({errorFieldNames: errorFields})
if providerField.type == "email" and event.target.value
if event.target.value.endsWith('@gmail.com')
# set a state that contains a "this is a gmail account" message
errorFields = _.uniq(@state.errorFieldNames.concat([field]))
@setState
errorMessage: "This looks like a Gmail account. You should go back and sign in to Gmail instead."
errorFieldNames: errorFields
@_resize()
else
@setState({errorMessage: null})
@_resize()
@setState({fields})
_onFieldKeyPress: (event) =>
if event.key in ['Enter', 'Return']
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
@_onNextButton()
else
@_onSubmit()
_renderTitle: =>
if @state.provider.name is 'gmail'
<h2>
Sign in to Google in<br/>your browser.
</h2>
else if @state.provider.pages?.length > 0
<h2>
{@state.provider.pages[@state.pageNumber]}
</h2>
else
<h2>
Sign in to {@state.provider.displayName}
</h2>
_renderErrorMessage: =>
return unless @state.errorMessage
text = @state.errorMessage
result = RegExpUtils.urlRegex(matchEntireString: false).exec(text)
if result
link = result[0]
beforeText = text.substr(0, result.index)
afterText = text.substr(result.index + link.length)
return (
<div className="errormsg">
{beforeText}<a href={link}>{link}</a>{afterText}
</div>
)
else
return (
<div className="errormsg">
{text}
</div>
)
_fieldOnCurrentPage: (field) =>
!@state.provider.pages || field.page is @state.pageNumber
_renderFields: =>
@state.provider.fields?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={(field.className || "")} key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 1}
value={@state.fields[field.name]}
onChange={@_onValueChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass}
placeholder={field.placeholder} />
</label>
_renderSettings: =>
@state.provider.settings?.filter(@_fieldOnCurrentPage)
.map (field, idx) =>
if field.type is 'checkbox'
<label className={"checkbox #{field.className ? ""}"} key={field.name}>
<input type={field.type}
tabIndex={idx + 5}
checked={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
disabled={@state.tryingToAuthenticate}
data-format={field.format ? ""}
className={field.className ? ""} />
{field.label}
</label>
else
errclass = if field.name in @state.errorFieldNames then "error " else ""
<label className={field.className ? ""}
style={if field.advanced and not @state.show_advanced then {display:'none'} else {}}
key={field.name}>
{field.label}
<input type={field.type}
tabIndex={idx + 5}
value={@state.settings[field.name]}
onChange={@_onSettingsChanged}
onKeyPress={@_onFieldKeyPress}
data-field={field.name}
data-format={field.format ? ""}
disabled={@state.tryingToAuthenticate}
className={errclass+(field.className ? "")}
placeholder={field.placeholder} />
</label>
_renderButton: =>
pages = @state.provider.pages || []
if pages.length > @state.pageNumber + 1
# We're not on the last page.
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient" onClick={@_onNextButton}>Continue</button>
else
# Disable the "Continue" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-disabled">Continue</button>
else if @state.provider.name isnt 'gmail'
if @state.tryingToAuthenticate
<button className="btn btn-large btn-disabled btn-add-account-spinning">
<RetinaImg name="sending-spinner.gif" width={15} height={15} mode={RetinaImg.Mode.ContentPreserve} /> Adding account…
</button>
else
if @_noFormErrors() and @_allRequiredFieldsFilled()
<button className="btn btn-large btn-gradient btn-add-account" onClick={@_onSubmit}>Add account</button>
else
# Disable the "Add Account" button if the fields haven't been filled correctly.
<button className="btn btn-large btn-gradient btn-add-account btn-disabled">Add account</button>
_onNextButton: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
@setState(pageNumber: @state.pageNumber + 1)
@_resize()
_onSubmit: (event) =>
return unless @_noFormErrors() and @_allRequiredFieldsFilled()
return if @state.tryingToAuthenticate
data = settings: {}
for own k,v of @state.fields when v isnt ''
data[k] = v
for own k,v of @state.settings when v isnt ''
data.settings[k] = v
data.provider = @state.provider.name
# if there's an account with this email, get the ID for it to notify the backend of re-auth
account = AccountStore.accountForEmail(data.email)
reauthParam = if account then "&reauth=#{account.id}" else ""
# handle special case for exchange/outlook/hotmail username field
if data.provider in ['exchange','outlook','hotmail'] and not data.settings.username?.trim().length
data.settings.username = data.email
@setState(tryingToAuthenticate: true)
# Send the form data directly to Nylas to get code
# If this succeeds, send the received code to N1 server to register the account
# Otherwise process the error message from the server and highlight UI as needed
NylasAPI.makeRequest
path: "/auth?client_id=#{NylasAPI.AppID}&n1_id=#{NylasEnv.config.get('updateIdentity')}#{reauthParam}"
method: 'POST'
body: data
returnsModel: false
timeout: 60000
auth:
user: ''
pass: ''
sendImmediately: true
.then (json) =>
invite_code = NylasEnv.config.get('invitationCode')
json.invite_code = invite_code
json.email = data.email
EdgehillAPI.request
path: "/connect/nylas"
method: "POST"
timeout: 60000
body: json
success: @_onAccountReceived
error: @_onNetworkError
.catch(@_onNetworkError)
_onAccountReceived: (json) =>
Actions.recordUserEvent('Auth Successful', {
provider: @state.provider.name
})
try
OnboardingActions.accountJSONReceived(json)
catch e
NylasEnv.reportError(e)
@setState
tryingToAuthenticate: false
errorMessage: "Sorry, something went wrong on the Nylas server. Please try again. If you're still having issues, contact us at PI:EMAIL:<EMAIL>END_PI."
@_resize()
_onNetworkError: (err) =>
errorMessage = err.message
Actions.recordUserEvent('Auth Failed', {
errorMessage: errorMessage
provider: @state.provider.name
})
if errorMessage is "Invite code required"
choice = dialog.showMessageBox(remote.getCurrentWindow(), {
type: 'info',
buttons: ['Okay'],
title: 'Confirm',
message: 'Due to a large number of sign-ups this week, you’ll need an invitation code to add another account! Visit http://invite.nylas.com/ to grab one, or hold tight!'
})
OnboardingActions.moveToPage("token-auth")
if errorMessage is "Invalid invite code"
OnboardingActions.moveToPage("token-auth")
pageNumber = @state.pageNumber
errorFieldNames = err.body?.missing_fields || err.body?.missing_settings
if err.errorTitle is "setting_update_error"
@setState
tryingToAuthenticate: false
errorMessage: 'The IMAP/SMTP servers for this account do not match our records. Please verify that any server names you entered are correct. If your IMAP/SMTP server has changed, first remove this account from N1, then try logging in again.'
@_resize()
OnboardingActions.moveToPage("account-settings")
return
if errorFieldNames
{pageNumber, errorMessage} = @_stateForMissingFieldNames(errorFieldNames)
if err.statusCode is -123 # timeout
errorMessage = "Request timed out. Please try again."
@setState
pageNumber: pageNumber
errorMessage: errorMessage
errorFieldNames: errorFieldNames || []
tryingToAuthenticate: false
@_resize()
_stateForMissingFieldNames: (fieldNames) ->
fieldLabels = []
fields = [].concat(@state.provider.settings, @state.provider.fields)
pageNumbers = [@state.pageNumber]
for fieldName in fieldNames
for s in fields when s.name is fieldName
fieldLabels.push(s.label.toLowerCase())
if s.page isnt undefined
pageNumbers.push(s.page)
pageNumber = Math.min.apply(null, pageNumbers)
errorMessage = @_messageForFieldLabels(fieldLabels)
{pageNumber, errorMessage}
_messageForFieldLabels: (labels) ->
if labels.length > 2
return "Please fix the highlighted fields."
else if labels.length is 2
return "Please provide your #{labels[0]} and #{labels[1]}."
else
return "Please provide your #{labels[0]}."
_pollForGmailAccount: (callback) =>
EdgehillAPI.request
path: "/oauth/google/token?key="+@state.provider.clientKey
method: "GET"
success: (json) =>
callback(json)
error: (err) =>
callback()
_resize: =>
setTimeout( =>
@props.onResize?()
, 10)
_fireMoveToPrevPage: =>
if @state.pageNumber > 0
@setState(pageNumber: @state.pageNumber - 1)
@_resize()
else
OnboardingActions.moveToPreviousPage()
module.exports = AccountSettingsPage
|
[
{
"context": "\n type: 'bulldozer'\n name: 'willy'\n response = [machine]\n res.sta",
"end": 1344,
"score": 0.9968496561050415,
"start": 1339,
"tag": "NAME",
"value": "willy"
},
{
"context": "\n type: 'bulldozer'\n name: '... | test/integration/cli/cli-test.coffee | jasonrayles-nbcuni/dredd-public | 0 | {assert} = require('chai')
{exec} = require('child_process')
express = require 'express'
clone = require 'clone'
bodyParser = require 'body-parser'
fs = require 'fs'
syncExec = require 'sync-exec'
net = require 'net'
{DREDD_BIN, isProcessRunning} = require './helpers'
PORT = 8887
CMD_PREFIX = ''
stderr = ''
stdout = ''
exitStatus = null
requests = []
execCommand = (cmd, options = {}, callback) ->
stderr = ''
stdout = ''
exitStatus = null
if typeof options is 'function'
callback = options
options = undefined
cli = exec CMD_PREFIX + cmd, options, (error, out, err) ->
stdout = out
stderr = err
if error
exitStatus = error.code
cli.on 'close', (code) ->
exitStatus = code if exitStatus == null and code != undefined
callback(undefined, stdout, stderr, exitStatus)
describe 'CLI', () ->
describe "Arguments with existing blueprint and responding server", () ->
describe "when executing the command and the server is responding as specified in the blueprint", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is responding as specified in the blueprint, endpoint with path", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}/v2/"
app = express()
app.get '/v2/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is sending different response", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1', () ->
assert.equal exitStatus, 1
describe "when called with arguments", () ->
describe 'when using language hook handler and spawning the server', () ->
describe "and handler file doesn't exist", () ->
apiHit = false
before (done) ->
languageCmd = "./foo/bar.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should not return message containing exited or killed', () ->
assert.notInclude stderr, 'exited'
assert.notInclude stderr, 'killed'
it 'should not return message announcing the fact', () ->
assert.include stderr, 'not found'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe 'and handler crashes before execution', () ->
apiHit = false
before (done) ->
languageCmd = "./test/fixtures/scripts/exit_3.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'exited'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed before execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/kill-self.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed during execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/hooks-kill-after-all.coffee"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
killHandlerCmd = 'ps aux | grep "bash" | grep "endless-nosigterm.sh" | grep -v grep | awk \'{print $2}\' | xargs kill -9'
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
exec killHandlerCmd, (error, stdout, stderr) ->
done error if error
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should execute the transaction', () ->
assert.isTrue apiHit
describe "and handler didn't quit but all Dredd tests were OK", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server '#{serverCmd}' --language '#{languageCmd}' --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 0', () ->
assert.equal exitStatus, 0
it 'should not return any killed or exited message', () ->
assert.notInclude stderr, 'killed'
assert.notInclude stderr, 'exited'
it 'should kill the handler', () ->
assert.isFalse isProcessRunning "dredd-fake-handler"
it 'should kill the server', () ->
assert.isFalse isProcessRunning "dredd-fake-server"
it 'should execute some transaction', () ->
assert.isTrue apiHit
describe "when adding additional headers with -h", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -h Accept:application/json"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an additional header in the request', () ->
assert.deepPropertyVal receivedRequest, 'headers.accept', 'application/json'
describe "when adding basic auth credentials with -u", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -u username:password"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an authorization header in the request', () ->
assert.ok receivedRequest.headers.authorization
it 'should contain a base64 encoded string of the username and password', () ->
assert.ok receivedRequest.headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64')
describe "when sorting requests with -s", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/apiary.apib http://localhost:#{PORT} -s"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should perform the POST, GET, PUT, DELETE in order', () ->
assert.ok stdout.indexOf('POST') < stdout.indexOf('GET') < stdout.indexOf('PUT') < stdout.indexOf('DELETE')
describe 'when displaying errors inline with -e', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -e"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display errors inline', () ->
# when displayed inline, a single fail request only creates two "fail:" messages,
# as opposed to the usual three
count = stdout.split("fail").length - 2 #says fail in the epilogue
assert.equal count, 2
describe 'when showing details for all requests with -d', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -d"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display details on passing tests', () ->
# the request: block is not shown for passing tests normally
assert.ok stdout.indexOf('request') > -1
describe "when filtering request methods with -m", () ->
describe 'when blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m POST"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request request', () ->
assert.deepEqual receivedRequest, {}
describe 'when not blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m GET"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should allow the request to go through', () ->
assert.ok receivedRequest.headers
describe "when filtering transaction to particular name with -x or --only", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --only=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse machineHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /machines'
it 'should hit the only transaction', () ->
assert.isTrue messageHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when filtering transaction to particular name with -z or --skip", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --skip=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse messageHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /message'
it 'should hit the only transaction', () ->
assert.isTrue machineHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe 'when suppressing color with --no-color', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when suppressing color with --color false', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --color false"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when setting the log output level with -l', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -l=error"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not display anything', () ->
# at the "error" level, complete should not be shown
assert.ok stdout.indexOf('complete') is -1
describe 'when showing timestamps with -t', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -t"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display timestamps', () ->
# look for the prefix for cli output with timestamps
assert.notEqual stdout.indexOf('Z -'), -1
describe 'when loading hooks with --hookfiles', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_hooks.*"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should modify the transaction with hooks', () ->
assert.equal receivedRequest.headers['header'], '123232323'
describe 'when describing events in hookfiles', () ->
output = {}
containsLine = (str, expected) ->
lines = str.split('\n')
for line in lines
if line.indexOf(expected) > -1
return true
return false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_events.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute the before and after events', () ->
assert.ok containsLine(output.stdout, 'hooks.beforeAll'), (stdout)
assert.ok containsLine(output.stdout, 'hooks.afterAll'), (stdout)
describe 'when describing both hooks and events in hookfiles', () ->
output = {}
getResults = (str) ->
ret = []
lines = str.split('\n')
for line in lines
if line.indexOf('*** ') > -1
ret.push(line.substr(line.indexOf('*** ') + 4))
return ret.join(',')
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_all.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute hooks and events in order', () ->
events = getResults(output.stdout)
assert.ok events is 'beforeAll,before,after,afterAll'
describe "tests a blueprint containing an endpoint with schema", () ->
describe "and server is responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 1234,
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0 (success)', () ->
assert.equal exitStatus, 0
describe "and server is NOT responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 'this should fail since it is a string',
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1 (failure)', () ->
assert.equal exitStatus, 1
describe "when blueprint path is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost --names"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching the glob', () ->
assert.include stdout, '> /greeting > GET'
assert.include stdout, '> /message > GET'
assert.include stdout, '> /name > GET'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe 'and called with hooks', () ->
receivedRequests = []
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/multifile/multifile_hooks.coffee"
app = express()
app.get '/name', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Adam\n"
app.get '/greeting', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Howdy!\n"
app.get '/message', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should eval the hook for each transaction', () ->
assert.include stdout, 'after name'
assert.include stdout, 'after greeting'
assert.include stdout, 'after message'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0, (stdout+stderr)
it 'server should receive 3 requests', () ->
assert.lengthOf receivedRequests, 3
describe "when called with additional --path argument which is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multiple-examples.apib http://localhost --path=./test/fixtures/multifile/*.apib --names --no-color"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching all paths and globs', () ->
assert.include stdout, 'Greeting API > /greeting > GET'
assert.include stdout, 'Message API > /message > GET'
assert.include stdout, 'Name API > /name > GET'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe "Using sandboxed hooks", () ->
resourceRequested = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --sandbox --hookfiles=./test/fixtures/sandboxed-hook.js"
app = express()
app.get '/machines', (req, res) ->
resourceRequested = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'willy'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should hit the resource', () ->
assert.ok resourceRequested
it 'exit status should be 0', () ->
assert.equal exitStatus, 1
it 'stdout shoud contain fail message', () ->
assert.include stdout, 'failed in sandboxed hook'
it 'stdout shoud contain sandbox messagae', () ->
assert.include stdout, 'Loading hookfiles in sandboxed context'
| 59469 | {assert} = require('chai')
{exec} = require('child_process')
express = require 'express'
clone = require 'clone'
bodyParser = require 'body-parser'
fs = require 'fs'
syncExec = require 'sync-exec'
net = require 'net'
{DREDD_BIN, isProcessRunning} = require './helpers'
PORT = 8887
CMD_PREFIX = ''
stderr = ''
stdout = ''
exitStatus = null
requests = []
execCommand = (cmd, options = {}, callback) ->
stderr = ''
stdout = ''
exitStatus = null
if typeof options is 'function'
callback = options
options = undefined
cli = exec CMD_PREFIX + cmd, options, (error, out, err) ->
stdout = out
stderr = err
if error
exitStatus = error.code
cli.on 'close', (code) ->
exitStatus = code if exitStatus == null and code != undefined
callback(undefined, stdout, stderr, exitStatus)
describe 'CLI', () ->
describe "Arguments with existing blueprint and responding server", () ->
describe "when executing the command and the server is responding as specified in the blueprint", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is responding as specified in the blueprint, endpoint with path", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}/v2/"
app = express()
app.get '/v2/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is sending different response", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1', () ->
assert.equal exitStatus, 1
describe "when called with arguments", () ->
describe 'when using language hook handler and spawning the server', () ->
describe "and handler file doesn't exist", () ->
apiHit = false
before (done) ->
languageCmd = "./foo/bar.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should not return message containing exited or killed', () ->
assert.notInclude stderr, 'exited'
assert.notInclude stderr, 'killed'
it 'should not return message announcing the fact', () ->
assert.include stderr, 'not found'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe 'and handler crashes before execution', () ->
apiHit = false
before (done) ->
languageCmd = "./test/fixtures/scripts/exit_3.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'exited'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed before execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/kill-self.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed during execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/hooks-kill-after-all.coffee"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
killHandlerCmd = 'ps aux | grep "bash" | grep "endless-nosigterm.sh" | grep -v grep | awk \'{print $2}\' | xargs kill -9'
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
exec killHandlerCmd, (error, stdout, stderr) ->
done error if error
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should execute the transaction', () ->
assert.isTrue apiHit
describe "and handler didn't quit but all Dredd tests were OK", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server '#{serverCmd}' --language '#{languageCmd}' --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 0', () ->
assert.equal exitStatus, 0
it 'should not return any killed or exited message', () ->
assert.notInclude stderr, 'killed'
assert.notInclude stderr, 'exited'
it 'should kill the handler', () ->
assert.isFalse isProcessRunning "dredd-fake-handler"
it 'should kill the server', () ->
assert.isFalse isProcessRunning "dredd-fake-server"
it 'should execute some transaction', () ->
assert.isTrue apiHit
describe "when adding additional headers with -h", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -h Accept:application/json"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an additional header in the request', () ->
assert.deepPropertyVal receivedRequest, 'headers.accept', 'application/json'
describe "when adding basic auth credentials with -u", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -u username:password"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an authorization header in the request', () ->
assert.ok receivedRequest.headers.authorization
it 'should contain a base64 encoded string of the username and password', () ->
assert.ok receivedRequest.headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64')
describe "when sorting requests with -s", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/apiary.apib http://localhost:#{PORT} -s"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should perform the POST, GET, PUT, DELETE in order', () ->
assert.ok stdout.indexOf('POST') < stdout.indexOf('GET') < stdout.indexOf('PUT') < stdout.indexOf('DELETE')
describe 'when displaying errors inline with -e', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -e"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display errors inline', () ->
# when displayed inline, a single fail request only creates two "fail:" messages,
# as opposed to the usual three
count = stdout.split("fail").length - 2 #says fail in the epilogue
assert.equal count, 2
describe 'when showing details for all requests with -d', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -d"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display details on passing tests', () ->
# the request: block is not shown for passing tests normally
assert.ok stdout.indexOf('request') > -1
describe "when filtering request methods with -m", () ->
describe 'when blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m POST"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request request', () ->
assert.deepEqual receivedRequest, {}
describe 'when not blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m GET"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should allow the request to go through', () ->
assert.ok receivedRequest.headers
describe "when filtering transaction to particular name with -x or --only", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --only=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse machineHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /machines'
it 'should hit the only transaction', () ->
assert.isTrue messageHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when filtering transaction to particular name with -z or --skip", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --skip=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse messageHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /message'
it 'should hit the only transaction', () ->
assert.isTrue machineHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe 'when suppressing color with --no-color', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when suppressing color with --color false', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --color false"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when setting the log output level with -l', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -l=error"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not display anything', () ->
# at the "error" level, complete should not be shown
assert.ok stdout.indexOf('complete') is -1
describe 'when showing timestamps with -t', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -t"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display timestamps', () ->
# look for the prefix for cli output with timestamps
assert.notEqual stdout.indexOf('Z -'), -1
describe 'when loading hooks with --hookfiles', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_hooks.*"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should modify the transaction with hooks', () ->
assert.equal receivedRequest.headers['header'], '123232323'
describe 'when describing events in hookfiles', () ->
output = {}
containsLine = (str, expected) ->
lines = str.split('\n')
for line in lines
if line.indexOf(expected) > -1
return true
return false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_events.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute the before and after events', () ->
assert.ok containsLine(output.stdout, 'hooks.beforeAll'), (stdout)
assert.ok containsLine(output.stdout, 'hooks.afterAll'), (stdout)
describe 'when describing both hooks and events in hookfiles', () ->
output = {}
getResults = (str) ->
ret = []
lines = str.split('\n')
for line in lines
if line.indexOf('*** ') > -1
ret.push(line.substr(line.indexOf('*** ') + 4))
return ret.join(',')
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_all.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute hooks and events in order', () ->
events = getResults(output.stdout)
assert.ok events is 'beforeAll,before,after,afterAll'
describe "tests a blueprint containing an endpoint with schema", () ->
describe "and server is responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 1234,
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0 (success)', () ->
assert.equal exitStatus, 0
describe "and server is NOT responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 'this should fail since it is a string',
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1 (failure)', () ->
assert.equal exitStatus, 1
describe "when blueprint path is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost --names"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching the glob', () ->
assert.include stdout, '> /greeting > GET'
assert.include stdout, '> /message > GET'
assert.include stdout, '> /name > GET'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe 'and called with hooks', () ->
receivedRequests = []
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/multifile/multifile_hooks.coffee"
app = express()
app.get '/name', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "<NAME>\n"
app.get '/greeting', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Howdy!\n"
app.get '/message', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should eval the hook for each transaction', () ->
assert.include stdout, 'after name'
assert.include stdout, 'after greeting'
assert.include stdout, 'after message'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0, (stdout+stderr)
it 'server should receive 3 requests', () ->
assert.lengthOf receivedRequests, 3
describe "when called with additional --path argument which is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multiple-examples.apib http://localhost --path=./test/fixtures/multifile/*.apib --names --no-color"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching all paths and globs', () ->
assert.include stdout, 'Greeting API > /greeting > GET'
assert.include stdout, 'Message API > /message > GET'
assert.include stdout, 'Name API > /name > GET'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe "Using sandboxed hooks", () ->
resourceRequested = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --sandbox --hookfiles=./test/fixtures/sandboxed-hook.js"
app = express()
app.get '/machines', (req, res) ->
resourceRequested = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: '<NAME>'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should hit the resource', () ->
assert.ok resourceRequested
it 'exit status should be 0', () ->
assert.equal exitStatus, 1
it 'stdout shoud contain fail message', () ->
assert.include stdout, 'failed in sandboxed hook'
it 'stdout shoud contain sandbox messagae', () ->
assert.include stdout, 'Loading hookfiles in sandboxed context'
| true | {assert} = require('chai')
{exec} = require('child_process')
express = require 'express'
clone = require 'clone'
bodyParser = require 'body-parser'
fs = require 'fs'
syncExec = require 'sync-exec'
net = require 'net'
{DREDD_BIN, isProcessRunning} = require './helpers'
PORT = 8887
CMD_PREFIX = ''
stderr = ''
stdout = ''
exitStatus = null
requests = []
execCommand = (cmd, options = {}, callback) ->
stderr = ''
stdout = ''
exitStatus = null
if typeof options is 'function'
callback = options
options = undefined
cli = exec CMD_PREFIX + cmd, options, (error, out, err) ->
stdout = out
stderr = err
if error
exitStatus = error.code
cli.on 'close', (code) ->
exitStatus = code if exitStatus == null and code != undefined
callback(undefined, stdout, stderr, exitStatus)
describe 'CLI', () ->
describe "Arguments with existing blueprint and responding server", () ->
describe "when executing the command and the server is responding as specified in the blueprint", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is responding as specified in the blueprint, endpoint with path", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}/v2/"
app = express()
app.get '/v2/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when executing the command and the server is sending different response", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT}"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1', () ->
assert.equal exitStatus, 1
describe "when called with arguments", () ->
describe 'when using language hook handler and spawning the server', () ->
describe "and handler file doesn't exist", () ->
apiHit = false
before (done) ->
languageCmd = "./foo/bar.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should not return message containing exited or killed', () ->
assert.notInclude stderr, 'exited'
assert.notInclude stderr, 'killed'
it 'should not return message announcing the fact', () ->
assert.include stderr, 'not found'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe 'and handler crashes before execution', () ->
apiHit = false
before (done) ->
languageCmd = "./test/fixtures/scripts/exit_3.sh"
hookfiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --language #{languageCmd} --hookfiles #{hookfiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'exited'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed before execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/kill-self.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should not execute any transaction', () ->
assert.isFalse apiHit
describe "and handler is killed during execution", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/hooks-kill-after-all.coffee"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server #{serverCmd} --language #{languageCmd} --hookfiles #{hookFiles} --server-wait 0"
killHandlerCmd = 'ps aux | grep "bash" | grep "endless-nosigterm.sh" | grep -v grep | awk \'{print $2}\' | xargs kill -9'
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
exec killHandlerCmd, (error, stdout, stderr) ->
done error if error
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 1', () ->
assert.equal exitStatus, 1
it 'should return message announcing the fact', () ->
assert.include stderr, 'killed'
it 'should term or kill the server', () ->
assert.isFalse isProcessRunning("endless-nosigterm")
it 'should execute the transaction', () ->
assert.isTrue apiHit
describe "and handler didn't quit but all Dredd tests were OK", () ->
apiHit = false
before (done) ->
serverCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
languageCmd = "./test/fixtures/scripts/endless-nosigterm.sh"
hookFiles = "./test/fixtures/scripts/emptyfile"
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --server '#{serverCmd}' --language '#{languageCmd}' --hookfiles #{hookFiles} --server-wait 0"
app = express()
app.get '/machines', (req, res) ->
apiHit = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
# TCP server echoing transactions back
hookServer = net.createServer (socket) ->
socket.on 'data', (data) ->
socket.write data
hookServer.listen 61321, () ->
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', () ->
hookServer.close()
done()
after () ->
syncExec "ps aux | grep test/fixtures/scripts/ | grep -v grep | awk '{print $2}' | xargs kill -9"
it 'should return with status 0', () ->
assert.equal exitStatus, 0
it 'should not return any killed or exited message', () ->
assert.notInclude stderr, 'killed'
assert.notInclude stderr, 'exited'
it 'should kill the handler', () ->
assert.isFalse isProcessRunning "dredd-fake-handler"
it 'should kill the server', () ->
assert.isFalse isProcessRunning "dredd-fake-server"
it 'should execute some transaction', () ->
assert.isTrue apiHit
describe "when adding additional headers with -h", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -h Accept:application/json"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an additional header in the request', () ->
assert.deepPropertyVal receivedRequest, 'headers.accept', 'application/json'
describe "when adding basic auth credentials with -u", () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -u username:password"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should have an authorization header in the request', () ->
assert.ok receivedRequest.headers.authorization
it 'should contain a base64 encoded string of the username and password', () ->
assert.ok receivedRequest.headers.authorization is 'Basic ' + new Buffer('username:password').toString('base64')
describe "when sorting requests with -s", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/apiary.apib http://localhost:#{PORT} -s"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should perform the POST, GET, PUT, DELETE in order', () ->
assert.ok stdout.indexOf('POST') < stdout.indexOf('GET') < stdout.indexOf('PUT') < stdout.indexOf('DELETE')
describe 'when displaying errors inline with -e', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -e"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
kind: 'bulldozer'
imatriculation: 'willy'
response = [machine]
res.status(201).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display errors inline', () ->
# when displayed inline, a single fail request only creates two "fail:" messages,
# as opposed to the usual three
count = stdout.split("fail").length - 2 #says fail in the epilogue
assert.equal count, 2
describe 'when showing details for all requests with -d', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -d"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display details on passing tests', () ->
# the request: block is not shown for passing tests normally
assert.ok stdout.indexOf('request') > -1
describe "when filtering request methods with -m", () ->
describe 'when blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m POST"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request request', () ->
assert.deepEqual receivedRequest, {}
describe 'when not blocking a request', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -m GET"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should allow the request to go through', () ->
assert.ok receivedRequest.headers
describe "when filtering transaction to particular name with -x or --only", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --only=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse machineHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /machines'
it 'should hit the only transaction', () ->
assert.isTrue messageHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe "when filtering transaction to particular name with -z or --skip", () ->
machineHit = false
messageHit = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --path=./test/fixtures/multifile/*.apib --skip=\"Message API > /message > GET\" --no-color"
app = express()
app.get '/machines', (req, res) ->
machineHit = true
res.setHeader 'Content-Type', 'application/json; charset=utf-8'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
app.get '/message', (req, res) ->
messageHit = true
res.setHeader 'Content-Type', 'text/plain; charset=utf-8'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not send the request', () ->
assert.isFalse messageHit
it 'should notify skipping to the stdout', () ->
assert.include stdout, 'skip: GET /message'
it 'should hit the only transaction', () ->
assert.isTrue machineHit
it 'exit status should be 0', () ->
assert.equal exitStatus, 0
describe 'when suppressing color with --no-color', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when suppressing color with --color false', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --color false"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should print without colors', () ->
# if colors are not on, there is no closing color code between
# the "pass" and the ":"
assert.include stdout, 'pass:'
describe 'when setting the log output level with -l', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -l=error"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should not display anything', () ->
# at the "error" level, complete should not be shown
assert.ok stdout.indexOf('complete') is -1
describe 'when showing timestamps with -t', () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} -t"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should display timestamps', () ->
# look for the prefix for cli output with timestamps
assert.notEqual stdout.indexOf('Z -'), -1
describe 'when loading hooks with --hookfiles', () ->
receivedRequest = {}
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_hooks.*"
app = express()
app.get '/machines', (req, res) ->
receivedRequest = req
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should modify the transaction with hooks', () ->
assert.equal receivedRequest.headers['header'], '123232323'
describe 'when describing events in hookfiles', () ->
output = {}
containsLine = (str, expected) ->
lines = str.split('\n')
for line in lines
if line.indexOf(expected) > -1
return true
return false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_events.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute the before and after events', () ->
assert.ok containsLine(output.stdout, 'hooks.beforeAll'), (stdout)
assert.ok containsLine(output.stdout, 'hooks.afterAll'), (stdout)
describe 'when describing both hooks and events in hookfiles', () ->
output = {}
getResults = (str) ->
ret = []
lines = str.split('\n')
for line in lines
if line.indexOf('*** ') > -1
ret.push(line.substr(line.indexOf('*** ') + 4))
return ret.join(',')
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/*_all.*"
app = express()
app.get '/machines', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, (err, stdout, stderr) ->
output.stdout = stdout
output.stderr = stderr
server.close()
server.on 'close', done
it 'should execute hooks and events in order', () ->
events = getResults(output.stdout)
assert.ok events is 'beforeAll,before,after,afterAll'
describe "tests a blueprint containing an endpoint with schema", () ->
describe "and server is responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 1234,
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 0 (success)', () ->
assert.equal exitStatus, 0
describe "and server is NOT responding in accordance with the schema", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/schema.apib http://localhost:#{PORT}"
app = express()
app.get '/', (req, res) ->
res.setHeader 'Content-Type', 'application/json'
response =
data:
expires: 'this should fail since it is a string',
token: 'this should pass since it is a string'
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'exit status should be 1 (failure)', () ->
assert.equal exitStatus, 1
describe "when blueprint path is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost --names"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching the glob', () ->
assert.include stdout, '> /greeting > GET'
assert.include stdout, '> /message > GET'
assert.include stdout, '> /name > GET'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe 'and called with hooks', () ->
receivedRequests = []
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multifile/*.apib http://localhost:#{PORT} --hookfiles=./test/fixtures/multifile/multifile_hooks.coffee"
app = express()
app.get '/name', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "PI:NAME:<NAME>END_PI\n"
app.get '/greeting', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Howdy!\n"
app.get '/message', (req, res) ->
receivedRequests.push req
res.setHeader 'content-type', 'text/plain'
res.status(200).send "Hello World!\n"
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should eval the hook for each transaction', () ->
assert.include stdout, 'after name'
assert.include stdout, 'after greeting'
assert.include stdout, 'after message'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0, (stdout+stderr)
it 'server should receive 3 requests', () ->
assert.lengthOf receivedRequests, 3
describe "when called with additional --path argument which is a glob", () ->
describe "and called with --names options", () ->
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/multiple-examples.apib http://localhost --path=./test/fixtures/multifile/*.apib --names --no-color"
execCommand cmd, () ->
done()
it 'it should include all paths from all blueprints matching all paths and globs', () ->
assert.include stdout, 'Greeting API > /greeting > GET'
assert.include stdout, 'Message API > /message > GET'
assert.include stdout, 'Name API > /name > GET'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 1'
assert.include stdout, 'Machines API > Machines > Machines collection > Get Machines > Example 2'
it 'should exit with status 0', () ->
assert.equal exitStatus, 0
describe "Using sandboxed hooks", () ->
resourceRequested = false
before (done) ->
cmd = "#{DREDD_BIN} ./test/fixtures/single-get.apib http://localhost:#{PORT} --no-color --sandbox --hookfiles=./test/fixtures/sandboxed-hook.js"
app = express()
app.get '/machines', (req, res) ->
resourceRequested = true
res.setHeader 'Content-Type', 'application/json'
machine =
type: 'bulldozer'
name: 'PI:NAME:<NAME>END_PI'
response = [machine]
res.status(200).send response
server = app.listen PORT, () ->
execCommand cmd, () ->
server.close()
server.on 'close', done
it 'should hit the resource', () ->
assert.ok resourceRequested
it 'exit status should be 0', () ->
assert.equal exitStatus, 1
it 'stdout shoud contain fail message', () ->
assert.include stdout, 'failed in sandboxed hook'
it 'stdout shoud contain sandbox messagae', () ->
assert.include stdout, 'Loading hookfiles in sandboxed context'
|
[
{
"context": ".5)\n\n token = if @options.toc then 'nav' else 'ncx'\n attr = if @options.toc then 'properties' els",
"end": 3201,
"score": 0.7218964695930481,
"start": 3198,
"tag": "KEY",
"value": "ncx"
}
] | src/coffee/main.coffee | msimmer/gfa-reader | 0 | class Reader
proxy = null
pagect = null
memStore =
html:{}
body:{}
constructor: (@options = {})->
# Kick off our progress bar
#
$('.wrapper').css('visibility', 'hidden')
NProgress.configure
showSpinner: false
minimum: 0.1
speed: 250
NProgress.start()
NProgress.set(0.3)
# create an element to attach event listeners to. only needs to stay in
# memory, so not attaching it to the DOM
#
proxy = document.createElement('div')
proxy.id = "_#{Date.now()}";
@utils = new @Utils()
@query = new @Query()
@parse = new @Parse()
@layout = new @Layout()
@template = new @Template()
@events = new @Events()
@wheel = new @Wheel()
@swipe = new @Swipe()
@package =
attributes: null
guide : null
manifest : null
metadata : null
spine : null
text : null
@location =
assets : @options.assets or ''
url : "#{window.location.origin}".replace(/\/$/, '')
@nav =
elem : null
regexp : null
path : null
attribute : null
@navMap = null
@ncx = null
@html = []
@metadata = []
@navElem = document.getElementById('reader-nav')
@mainElem = document.getElementById('reader-frame')
# $(@mainElem).css(opacity:0)
getNavDocument: (that)->
return (key, val, item)->
if key == that.nav.attribute and that.nav.regexp.test(val)
that.nav.elem = item
that.nav.path = item.getAttribute('href')
that.xml()
renderPage: (that)->
return (url, parentId, navId) ->
that.query.html("#{that.location.assets}/#{url}")
.done (data)->
doc = that.template.parse(data, that.location.assets)
that.layout.render(doc, parentId, '#doc-nav')
if not pagect -=1 then that.trigger('pagesloaded', {})
xml: ()->
curry = @renderPage(@)
@query.xml("#{@location.assets}/#{@nav.path}")
.done (data) =>
@ncx = @parse.nav(data)
@navMap = @parse.mapNcx(@ncx.navMap.navPoint)
@layout.build(@navMap, curry, @mainElem.id)
build: (data)->
curry = @getNavDocument(@)
pagect = @parse.xml(data, curry).package.spine.itemref.length
on: (method, callback) ->
evt = document.createEvent('CustomEvent')
evt.initCustomEvent(method, true, false, {})
proxy.addEventListener(method, callback)
trigger: (method, data) ->
proxy.dispatchEvent(new CustomEvent(method, data))
setup:()->
# Store existing html/body attributes and apply reader attributes
#
memStore.html.overflow = $('html').css('overflow')
memStore.body.overflow = $('body').css('overflow')
$('html').addClass('reader')
$('html,body').css({overflow:'hidden'})
destroy:()=>
# Reset previous attributes on html/body, and remove proxy element
#
$('html').css({overflow:memStore.html.overflow}).removeClass('reader')
$('body').css({overflow:memStore.body.overflow})
@events.destroy()
@swipe.destroy()
proxy = undefined
initialize: =>
NProgress.set(0.5)
token = if @options.toc then 'nav' else 'ncx'
attr = if @options.toc then 'properties' else 'id'
@nav.regexp = new RegExp("^#{token}$", 'i')
@nav.attribute = attr
@setup()
@query.xml(@options.packageUrl).done (data) => @build(data)
layoutcomplete = false
observer = new MutationObserver((mutations) =>
mutations.forEach (mutationRecord) =>
if !layoutcomplete
layoutcomplete = true
@trigger('layoutcomplete', {})
)
observer.observe document.body,
childList: true
attributes: true
attributeFilter: ['style']
# Public event listeners
#
@on 'pagesloaded', =>
NProgress.set(0.7)
console.log 'Reader pagesloaded'
window.scopedPolyFill(document)
@on 'layoutcomplete', =>
NProgress.set(0.9)
console.log 'Reader layoutcomplete'
@events.initialize()
setTimeout (() => @trigger('ready', {}) ), 0
@on 'nextPage', => @events.nextPage()
@on 'prevPage', => @events.prevPage()
@on 'ready', =>
NProgress.done()
console.log 'Reader ready'
$('.wrapper').css('visibility', 'visible')
$(@mainElem).addClass('ready')
# $(@mainElem).css(opacity:1)
# init wheel event handling
#
@wheel.initialize()
# init touch event handling
#
if Modernizr.touch then @swipe.initialize()
# some DOM manipulation for link behaviour
#
$('a').each (i, el)=>
$this = $(el)
if $this.attr('href').match(/^#/)
return
else if $this.attr('href').match(/^(?:\/|window.location.host)/)
$this.on 'click', => @destroy()
else
$this.attr('target', '_blank')
@on 'destroy', =>
@destroy()
# Important to destroy our proxy element, as it will continue to have
# handlers attached unless it's removed
#
window.onunload = window.onpopstate = () => @destroy()
window.Reader = Reader
| 188645 | class Reader
proxy = null
pagect = null
memStore =
html:{}
body:{}
constructor: (@options = {})->
# Kick off our progress bar
#
$('.wrapper').css('visibility', 'hidden')
NProgress.configure
showSpinner: false
minimum: 0.1
speed: 250
NProgress.start()
NProgress.set(0.3)
# create an element to attach event listeners to. only needs to stay in
# memory, so not attaching it to the DOM
#
proxy = document.createElement('div')
proxy.id = "_#{Date.now()}";
@utils = new @Utils()
@query = new @Query()
@parse = new @Parse()
@layout = new @Layout()
@template = new @Template()
@events = new @Events()
@wheel = new @Wheel()
@swipe = new @Swipe()
@package =
attributes: null
guide : null
manifest : null
metadata : null
spine : null
text : null
@location =
assets : @options.assets or ''
url : "#{window.location.origin}".replace(/\/$/, '')
@nav =
elem : null
regexp : null
path : null
attribute : null
@navMap = null
@ncx = null
@html = []
@metadata = []
@navElem = document.getElementById('reader-nav')
@mainElem = document.getElementById('reader-frame')
# $(@mainElem).css(opacity:0)
getNavDocument: (that)->
return (key, val, item)->
if key == that.nav.attribute and that.nav.regexp.test(val)
that.nav.elem = item
that.nav.path = item.getAttribute('href')
that.xml()
renderPage: (that)->
return (url, parentId, navId) ->
that.query.html("#{that.location.assets}/#{url}")
.done (data)->
doc = that.template.parse(data, that.location.assets)
that.layout.render(doc, parentId, '#doc-nav')
if not pagect -=1 then that.trigger('pagesloaded', {})
xml: ()->
curry = @renderPage(@)
@query.xml("#{@location.assets}/#{@nav.path}")
.done (data) =>
@ncx = @parse.nav(data)
@navMap = @parse.mapNcx(@ncx.navMap.navPoint)
@layout.build(@navMap, curry, @mainElem.id)
build: (data)->
curry = @getNavDocument(@)
pagect = @parse.xml(data, curry).package.spine.itemref.length
on: (method, callback) ->
evt = document.createEvent('CustomEvent')
evt.initCustomEvent(method, true, false, {})
proxy.addEventListener(method, callback)
trigger: (method, data) ->
proxy.dispatchEvent(new CustomEvent(method, data))
setup:()->
# Store existing html/body attributes and apply reader attributes
#
memStore.html.overflow = $('html').css('overflow')
memStore.body.overflow = $('body').css('overflow')
$('html').addClass('reader')
$('html,body').css({overflow:'hidden'})
destroy:()=>
# Reset previous attributes on html/body, and remove proxy element
#
$('html').css({overflow:memStore.html.overflow}).removeClass('reader')
$('body').css({overflow:memStore.body.overflow})
@events.destroy()
@swipe.destroy()
proxy = undefined
initialize: =>
NProgress.set(0.5)
token = if @options.toc then 'nav' else '<KEY>'
attr = if @options.toc then 'properties' else 'id'
@nav.regexp = new RegExp("^#{token}$", 'i')
@nav.attribute = attr
@setup()
@query.xml(@options.packageUrl).done (data) => @build(data)
layoutcomplete = false
observer = new MutationObserver((mutations) =>
mutations.forEach (mutationRecord) =>
if !layoutcomplete
layoutcomplete = true
@trigger('layoutcomplete', {})
)
observer.observe document.body,
childList: true
attributes: true
attributeFilter: ['style']
# Public event listeners
#
@on 'pagesloaded', =>
NProgress.set(0.7)
console.log 'Reader pagesloaded'
window.scopedPolyFill(document)
@on 'layoutcomplete', =>
NProgress.set(0.9)
console.log 'Reader layoutcomplete'
@events.initialize()
setTimeout (() => @trigger('ready', {}) ), 0
@on 'nextPage', => @events.nextPage()
@on 'prevPage', => @events.prevPage()
@on 'ready', =>
NProgress.done()
console.log 'Reader ready'
$('.wrapper').css('visibility', 'visible')
$(@mainElem).addClass('ready')
# $(@mainElem).css(opacity:1)
# init wheel event handling
#
@wheel.initialize()
# init touch event handling
#
if Modernizr.touch then @swipe.initialize()
# some DOM manipulation for link behaviour
#
$('a').each (i, el)=>
$this = $(el)
if $this.attr('href').match(/^#/)
return
else if $this.attr('href').match(/^(?:\/|window.location.host)/)
$this.on 'click', => @destroy()
else
$this.attr('target', '_blank')
@on 'destroy', =>
@destroy()
# Important to destroy our proxy element, as it will continue to have
# handlers attached unless it's removed
#
window.onunload = window.onpopstate = () => @destroy()
window.Reader = Reader
| true | class Reader
proxy = null
pagect = null
memStore =
html:{}
body:{}
constructor: (@options = {})->
# Kick off our progress bar
#
$('.wrapper').css('visibility', 'hidden')
NProgress.configure
showSpinner: false
minimum: 0.1
speed: 250
NProgress.start()
NProgress.set(0.3)
# create an element to attach event listeners to. only needs to stay in
# memory, so not attaching it to the DOM
#
proxy = document.createElement('div')
proxy.id = "_#{Date.now()}";
@utils = new @Utils()
@query = new @Query()
@parse = new @Parse()
@layout = new @Layout()
@template = new @Template()
@events = new @Events()
@wheel = new @Wheel()
@swipe = new @Swipe()
@package =
attributes: null
guide : null
manifest : null
metadata : null
spine : null
text : null
@location =
assets : @options.assets or ''
url : "#{window.location.origin}".replace(/\/$/, '')
@nav =
elem : null
regexp : null
path : null
attribute : null
@navMap = null
@ncx = null
@html = []
@metadata = []
@navElem = document.getElementById('reader-nav')
@mainElem = document.getElementById('reader-frame')
# $(@mainElem).css(opacity:0)
getNavDocument: (that)->
return (key, val, item)->
if key == that.nav.attribute and that.nav.regexp.test(val)
that.nav.elem = item
that.nav.path = item.getAttribute('href')
that.xml()
renderPage: (that)->
return (url, parentId, navId) ->
that.query.html("#{that.location.assets}/#{url}")
.done (data)->
doc = that.template.parse(data, that.location.assets)
that.layout.render(doc, parentId, '#doc-nav')
if not pagect -=1 then that.trigger('pagesloaded', {})
xml: ()->
curry = @renderPage(@)
@query.xml("#{@location.assets}/#{@nav.path}")
.done (data) =>
@ncx = @parse.nav(data)
@navMap = @parse.mapNcx(@ncx.navMap.navPoint)
@layout.build(@navMap, curry, @mainElem.id)
build: (data)->
curry = @getNavDocument(@)
pagect = @parse.xml(data, curry).package.spine.itemref.length
on: (method, callback) ->
evt = document.createEvent('CustomEvent')
evt.initCustomEvent(method, true, false, {})
proxy.addEventListener(method, callback)
trigger: (method, data) ->
proxy.dispatchEvent(new CustomEvent(method, data))
setup:()->
# Store existing html/body attributes and apply reader attributes
#
memStore.html.overflow = $('html').css('overflow')
memStore.body.overflow = $('body').css('overflow')
$('html').addClass('reader')
$('html,body').css({overflow:'hidden'})
destroy:()=>
# Reset previous attributes on html/body, and remove proxy element
#
$('html').css({overflow:memStore.html.overflow}).removeClass('reader')
$('body').css({overflow:memStore.body.overflow})
@events.destroy()
@swipe.destroy()
proxy = undefined
initialize: =>
NProgress.set(0.5)
token = if @options.toc then 'nav' else 'PI:KEY:<KEY>END_PI'
attr = if @options.toc then 'properties' else 'id'
@nav.regexp = new RegExp("^#{token}$", 'i')
@nav.attribute = attr
@setup()
@query.xml(@options.packageUrl).done (data) => @build(data)
layoutcomplete = false
observer = new MutationObserver((mutations) =>
mutations.forEach (mutationRecord) =>
if !layoutcomplete
layoutcomplete = true
@trigger('layoutcomplete', {})
)
observer.observe document.body,
childList: true
attributes: true
attributeFilter: ['style']
# Public event listeners
#
@on 'pagesloaded', =>
NProgress.set(0.7)
console.log 'Reader pagesloaded'
window.scopedPolyFill(document)
@on 'layoutcomplete', =>
NProgress.set(0.9)
console.log 'Reader layoutcomplete'
@events.initialize()
setTimeout (() => @trigger('ready', {}) ), 0
@on 'nextPage', => @events.nextPage()
@on 'prevPage', => @events.prevPage()
@on 'ready', =>
NProgress.done()
console.log 'Reader ready'
$('.wrapper').css('visibility', 'visible')
$(@mainElem).addClass('ready')
# $(@mainElem).css(opacity:1)
# init wheel event handling
#
@wheel.initialize()
# init touch event handling
#
if Modernizr.touch then @swipe.initialize()
# some DOM manipulation for link behaviour
#
$('a').each (i, el)=>
$this = $(el)
if $this.attr('href').match(/^#/)
return
else if $this.attr('href').match(/^(?:\/|window.location.host)/)
$this.on 'click', => @destroy()
else
$this.attr('target', '_blank')
@on 'destroy', =>
@destroy()
# Important to destroy our proxy element, as it will continue to have
# handlers attached unless it's removed
#
window.onunload = window.onpopstate = () => @destroy()
window.Reader = Reader
|
[
{
"context": "], []]\r\n[genIvl, genIvlId, me] = [5, null, \"John\"]\r\n[lists, otId, maxAsn] = [{head: {}, top",
"end": 688,
"score": 0.9998461008071899,
"start": 684,
"tag": "NAME",
"value": "John"
},
{
"context": "SA\"}\r\n ]\r\n detail =\r\n WS: [ \"Create:\\nMe... | src/demo.coffee | koolb/devops-ce-demo | 0 | # vim:expandtab:ts=2:
# @(#) $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $
$ = jQuery
# Handle requests from background.html
console.log "Loading $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $"
console.log "Initializing %0", this
handleRequest = (request, sender, sendResponse) ->
console.log "got request #{request.callFunction}"
toggleSB() if request?.callFunction is "toggleSB"
chrome.extension.onRequest.addListener handleRequest
# Create the sidebar - ToDo: Use a config object as args to callSB
sidebarPrev = true # prev state true means current is false
[openTickets, aeTickets] = [[], []]
[genIvl, genIvlId, me] = [5, null, "John"]
[lists, otId, maxAsn] = [{head: {}, top: {}}, 0, 5]
sbId = "mySidebar"
# undo createSB()
destroySB = ->
console.log "disabling sidebar and genIvl: #{genIvl}"
genIvlId? and clearInterval genIvlId
el = document.getElementById sbId
return el.parentNode.removeChild el
# create sidebar()
createSB = ->
navBar = """
<div class="navbar navbar-custom">
<div class="navbar-inner">
<a class="brand" href="#">JJR@DevOps</a>
<ul class="nav">
<li class="active"><a href="#">Open</a></li>
<li><a href="#">Servers</a></li>
<li><a href="#">Users</a></li>
<li><a href="#">Perms</a>
</ul>
</div>
</div>"""
# Start of Lists
lists.head.id = "listHead"
lists.head.html = """
<div id="#{lists.head.id}">
<h4>Open Requests <span class="badge">#{openTickets.length}</span></h1>
<ul class="nav-list"></ul>
</div>
"""
lists.top.id = "listTop"
lists.top.html = """
<div id="#{lists.top.id}">
<h4>Assigned Requests <span class="badge">#{aeTickets.length}</span></h4>
<ul class="nav-list"></ul>
</div>
"""
#var sbNav ='<button class="btn", id="servers">Servers</button>' +
# '<button class="btn", id="users">Users</button>'
sbMain = '<div> <ul id="sbMain"> </ul> <div>'
sidebar = document.createElement 'div'
sidebar.id = sbId
sidebar.style.display = 'hide'
sidebar.innerHTML ="""
#{navBar}
#{lists.head.html}
#{lists.top.html}
#{sbMain}
"""
document.body.appendChild sidebar
console.log "sidebar div added."
for name in ["head", "top"]
for tag in [ "ul", "span"]
lists[name][tag] = $ tag, "div##{lists[name].id}"
initLists()
# toggle and kick things off...
toggleSB = ->
genIvlId = setInterval genTicket, genIvl * 1000 unless genIvlId?
console.log "setting up a genTicket every #{genIvl} secs"
if sidebarPrev = not sidebarPrev then $("##{sbId}").hide() else $("##{sbId}").show()
console.log "enabling sidebar: checking notifications for this page"
checkReqNotify() # ToD:o fix request perms for current page
console.log "sidebar div added. Adding empty lists head: #{lists.head.id}, and top: #{lists.top.id}"
createSB() if not $("##{sbId}").length
initLists = () ->
once = false
if once
console.log "Initializing lists..."
openTickets.forEach (e)-> insElement e, lists.head
updCounters lists.head, openTickets.length
aeTickets.forEach (e)-> insElement e, lists.top
updCounters lists.top, aeTickets.length
addElement = (el, list, ary) ->
console.log "addEl: #{el} Before: ary: #{ary.length} to #{list.id}: #{list.ul.length}"
ary.push el
insElement el, list
console.log "addEl: After: ary: #{ary.length} ul: #{list.id}: #{list.ul.length}"
updCounters list, ary.length
title = (el) -> "#{el.st} - #{el.app} - #{el.cmp}"
createNotificationIfNotVisible = (el) ->
nOpts = body: el.detail, icon: "icon.png", tag: el.id
if el.status is "Open" and document.webkitVisibilityState isnt "visible"
el.closer = notify.createNotification "#{title el}", nOpts
insElement = (el, list) ->
[ae, labclass] = if el.ae then [" - #{el.ae} ", "label-info"] else ["", "label-warning active"]
createNotificationIfNotVisible el
html = """<li class="#{el.id}">#{title el}: <span class="label #{labclass}"> #{el.status}#{ae}</span></li>"""
$(html).hide().prependTo(list.ul).fadeIn 1900
removeElement = (sel, list, ary) ->
console.log "rmEl: before: #{sel} len: #{ary.length}, ul: #{list.id}: #{list.ul.length}"
found = _(ary).remove (e)-> e.id is sel
if found and ret = found.value()[0]
ret.closer.close() if ret.closer
$("li.#{sel}", list.ul).remove()
msg = "rmEl: after: #{ret.id} len: #{ary.length}, ul: #{list.id} (#{list.ul.length})"
console.log msg
# throw new Error(msg) unless list.ul.length < preRm
updCounters list, ary.length
else
msg = "didnt find #{sel} in #{list.id}"
console.log msg
throw new Error msg
ret
removeLast = (list, ary) ->
console.log "remLast of #{ary.length} (#{ list.ul.length})"
if ary.length > 0 and list.ul.length > 0
last = ary.pop()
if last.closer then last.closer.close()
list.ul.last().remove()
console.log "remLast of #{ary.length } (#{list.ul.length})"
else
console.log "No last element to remove"
updCounters = (list, val) -> list.span.text val
genTicket = ->
apps = [ "eP AuthHub", "eP4 Synergy", "eP VIPAA", "CSS Blaze", "eP ASA", "CTMT - CDS", "CTMT - KTC", "CTMT - DAF", "CGW - authGateway", "CGW - eCommerceGW", "BCT Gateway", "eP POE", "Brainiac Studio" ]
ctypes = [
{name: "Pilot DML", type: "DML"}
{name: "Ear", type: "WS"}
{name: "Dynamic DML", type: "DML"}
{name: "Web Assets", type: "SA"}
{name: "Jars", type: "SA"}
{name: "Properties", type: "SA"}
{name: "Artifacts", type: "SA"}
{name: "Config", type: "SA"}
{name: "Xml", type: "SA"}
]
detail =
WS: [ "Create:\nMember: John Ribera (NBKI812)\nRole: Developer\n", "Create:\nEnviroment: DEV01\nServer: ldranql05\nApp Name:APP"]
SA: [ "Create:\nMember: Kool Breeze (NBKK00L)\nRole: Manager\n", "Create:\nEnviroment: CERT01\nServer: ldranql05.chp.bankofamerica.com\nBase Artifact Install Dir:\n/hosting/apps/udeploy\n"]
DML: [ "Create:\nMember: ARandom Name\nRole: Lead Developer\n", "Environment: SIT02\nDML Env Name: E3SIT02"]
supTypes = [ "BS", "DS", "BO", "DO" ]
ai = getRandIdx apps.length
ct = getRandIdx ctypes.length
st = getRandIdx supTypes.length
ot =
ts: +Date.now()
id: "id-#{++otId}"
app: apps[ai]
cmp: ctypes[ct].name,
detail: detail[ctypes[ct].type]
status: "Open"
st: supTypes[st]
ae: null
toString: -> "#{@id}: #{@st} - #{@app} - #{@cmp}"
console.log "Generated random ticket #{ot}...adding to openTickets..."
addElement ot, lists.head, openTickets
console.log "added ticket #{ot} to #{lists.head.id}"
addAESecs = getRandIdx(5)+5
setTimeout assnTicket, addAESecs * 1000
# clean up assigned tickets
cleanAssigned = ->
while aeTickets.length > maxAsn
removeElement aeTickets[0].id, lists.top, aeTickets
# assign an avaialable ticket
retryMs = 1000
assnTicket = ->
aes = [ me, "Prudhvi", "Gregory", "Dan", "Hemal", "Shailza", "Billy", "John", "Jennifer", "David", "Koyt", "Waldo", "Kripa", "Amit" ]
olderOpen= _(openTickets).filter (e) -> (+Date.now() - e.ts) > retryMs
if olderOpen.length < 1
console.log "No tickets more than #{retryMs}ms old"
return setTimeout assnTicket, retryMs
aei = getRandIdx aes.length
oti = getRandIdx openTickets.length
ot = openTickets[oti]
console.log "Assigning open ticket @#{oti} #{ot} to #{aes[aei]}"
if rm = removeElement ot.id, lists.head, openTickets
rm.ae = aes[aei]
rm.status = "Accepted"
console.log "#{rm.ae} - #{rm.status} Ticket #{rm}"
addElement rm, lists.top, aeTickets
setTimeout cleanAssigned, 5000
getRandIdx = (len) ->
exp = Math.log len
exp = if exp < 1 then 1 else Math.floor exp
mult = Math.pow 10, exp
rand = Math.floor(Math.random()*mult) % len
notify = @notify # was window.notify
perms = null
checkReqNotify = ->
console.log "After require notify: #{notify}"
return unless notify
perms = notify.permissionLevel()
console.log "perms are initially #{perms}"
if perms isnt notify.PERMISSION_GRANTED
perms = notify.requestPermission -> console.log "Permission Granted"
console.log "Perms after are #{perms}"
| 89716 | # vim:expandtab:ts=2:
# @(#) $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $
$ = jQuery
# Handle requests from background.html
console.log "Loading $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $"
console.log "Initializing %0", this
handleRequest = (request, sender, sendResponse) ->
console.log "got request #{request.callFunction}"
toggleSB() if request?.callFunction is "toggleSB"
chrome.extension.onRequest.addListener handleRequest
# Create the sidebar - ToDo: Use a config object as args to callSB
sidebarPrev = true # prev state true means current is false
[openTickets, aeTickets] = [[], []]
[genIvl, genIvlId, me] = [5, null, "<NAME>"]
[lists, otId, maxAsn] = [{head: {}, top: {}}, 0, 5]
sbId = "mySidebar"
# undo createSB()
destroySB = ->
console.log "disabling sidebar and genIvl: #{genIvl}"
genIvlId? and clearInterval genIvlId
el = document.getElementById sbId
return el.parentNode.removeChild el
# create sidebar()
createSB = ->
navBar = """
<div class="navbar navbar-custom">
<div class="navbar-inner">
<a class="brand" href="#">JJR@DevOps</a>
<ul class="nav">
<li class="active"><a href="#">Open</a></li>
<li><a href="#">Servers</a></li>
<li><a href="#">Users</a></li>
<li><a href="#">Perms</a>
</ul>
</div>
</div>"""
# Start of Lists
lists.head.id = "listHead"
lists.head.html = """
<div id="#{lists.head.id}">
<h4>Open Requests <span class="badge">#{openTickets.length}</span></h1>
<ul class="nav-list"></ul>
</div>
"""
lists.top.id = "listTop"
lists.top.html = """
<div id="#{lists.top.id}">
<h4>Assigned Requests <span class="badge">#{aeTickets.length}</span></h4>
<ul class="nav-list"></ul>
</div>
"""
#var sbNav ='<button class="btn", id="servers">Servers</button>' +
# '<button class="btn", id="users">Users</button>'
sbMain = '<div> <ul id="sbMain"> </ul> <div>'
sidebar = document.createElement 'div'
sidebar.id = sbId
sidebar.style.display = 'hide'
sidebar.innerHTML ="""
#{navBar}
#{lists.head.html}
#{lists.top.html}
#{sbMain}
"""
document.body.appendChild sidebar
console.log "sidebar div added."
for name in ["head", "top"]
for tag in [ "ul", "span"]
lists[name][tag] = $ tag, "div##{lists[name].id}"
initLists()
# toggle and kick things off...
toggleSB = ->
genIvlId = setInterval genTicket, genIvl * 1000 unless genIvlId?
console.log "setting up a genTicket every #{genIvl} secs"
if sidebarPrev = not sidebarPrev then $("##{sbId}").hide() else $("##{sbId}").show()
console.log "enabling sidebar: checking notifications for this page"
checkReqNotify() # ToD:o fix request perms for current page
console.log "sidebar div added. Adding empty lists head: #{lists.head.id}, and top: #{lists.top.id}"
createSB() if not $("##{sbId}").length
initLists = () ->
once = false
if once
console.log "Initializing lists..."
openTickets.forEach (e)-> insElement e, lists.head
updCounters lists.head, openTickets.length
aeTickets.forEach (e)-> insElement e, lists.top
updCounters lists.top, aeTickets.length
addElement = (el, list, ary) ->
console.log "addEl: #{el} Before: ary: #{ary.length} to #{list.id}: #{list.ul.length}"
ary.push el
insElement el, list
console.log "addEl: After: ary: #{ary.length} ul: #{list.id}: #{list.ul.length}"
updCounters list, ary.length
title = (el) -> "#{el.st} - #{el.app} - #{el.cmp}"
createNotificationIfNotVisible = (el) ->
nOpts = body: el.detail, icon: "icon.png", tag: el.id
if el.status is "Open" and document.webkitVisibilityState isnt "visible"
el.closer = notify.createNotification "#{title el}", nOpts
insElement = (el, list) ->
[ae, labclass] = if el.ae then [" - #{el.ae} ", "label-info"] else ["", "label-warning active"]
createNotificationIfNotVisible el
html = """<li class="#{el.id}">#{title el}: <span class="label #{labclass}"> #{el.status}#{ae}</span></li>"""
$(html).hide().prependTo(list.ul).fadeIn 1900
removeElement = (sel, list, ary) ->
console.log "rmEl: before: #{sel} len: #{ary.length}, ul: #{list.id}: #{list.ul.length}"
found = _(ary).remove (e)-> e.id is sel
if found and ret = found.value()[0]
ret.closer.close() if ret.closer
$("li.#{sel}", list.ul).remove()
msg = "rmEl: after: #{ret.id} len: #{ary.length}, ul: #{list.id} (#{list.ul.length})"
console.log msg
# throw new Error(msg) unless list.ul.length < preRm
updCounters list, ary.length
else
msg = "didnt find #{sel} in #{list.id}"
console.log msg
throw new Error msg
ret
removeLast = (list, ary) ->
console.log "remLast of #{ary.length} (#{ list.ul.length})"
if ary.length > 0 and list.ul.length > 0
last = ary.pop()
if last.closer then last.closer.close()
list.ul.last().remove()
console.log "remLast of #{ary.length } (#{list.ul.length})"
else
console.log "No last element to remove"
updCounters = (list, val) -> list.span.text val
genTicket = ->
apps = [ "eP AuthHub", "eP4 Synergy", "eP VIPAA", "CSS Blaze", "eP ASA", "CTMT - CDS", "CTMT - KTC", "CTMT - DAF", "CGW - authGateway", "CGW - eCommerceGW", "BCT Gateway", "eP POE", "Brainiac Studio" ]
ctypes = [
{name: "Pilot DML", type: "DML"}
{name: "Ear", type: "WS"}
{name: "Dynamic DML", type: "DML"}
{name: "Web Assets", type: "SA"}
{name: "Jars", type: "SA"}
{name: "Properties", type: "SA"}
{name: "Artifacts", type: "SA"}
{name: "Config", type: "SA"}
{name: "Xml", type: "SA"}
]
detail =
WS: [ "Create:\nMember: <NAME> (NBKI812)\nRole: Developer\n", "Create:\nEnviroment: DEV01\nServer: ldranql05\nApp Name:APP"]
SA: [ "Create:\nMember: <NAME> (NBKK00L)\nRole: Manager\n", "Create:\nEnviroment: CERT01\nServer: ldranql05.chp.bankofamerica.com\nBase Artifact Install Dir:\n/hosting/apps/udeploy\n"]
DML: [ "Create:\nMember: ARandom Name\nRole: Lead Developer\n", "Environment: SIT02\nDML Env Name: E3SIT02"]
supTypes = [ "BS", "DS", "BO", "DO" ]
ai = getRandIdx apps.length
ct = getRandIdx ctypes.length
st = getRandIdx supTypes.length
ot =
ts: +Date.now()
id: "id-#{++otId}"
app: apps[ai]
cmp: ctypes[ct].name,
detail: detail[ctypes[ct].type]
status: "Open"
st: supTypes[st]
ae: null
toString: -> "#{@id}: #{@st} - #{@app} - #{@cmp}"
console.log "Generated random ticket #{ot}...adding to openTickets..."
addElement ot, lists.head, openTickets
console.log "added ticket #{ot} to #{lists.head.id}"
addAESecs = getRandIdx(5)+5
setTimeout assnTicket, addAESecs * 1000
# clean up assigned tickets
cleanAssigned = ->
while aeTickets.length > maxAsn
removeElement aeTickets[0].id, lists.top, aeTickets
# assign an avaialable ticket
retryMs = 1000
assnTicket = ->
aes = [ me, "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>", "<NAME>" ]
olderOpen= _(openTickets).filter (e) -> (+Date.now() - e.ts) > retryMs
if olderOpen.length < 1
console.log "No tickets more than #{retryMs}ms old"
return setTimeout assnTicket, retryMs
aei = getRandIdx aes.length
oti = getRandIdx openTickets.length
ot = openTickets[oti]
console.log "Assigning open ticket @#{oti} #{ot} to #{aes[aei]}"
if rm = removeElement ot.id, lists.head, openTickets
rm.ae = aes[aei]
rm.status = "Accepted"
console.log "#{rm.ae} - #{rm.status} Ticket #{rm}"
addElement rm, lists.top, aeTickets
setTimeout cleanAssigned, 5000
getRandIdx = (len) ->
exp = Math.log len
exp = if exp < 1 then 1 else Math.floor exp
mult = Math.pow 10, exp
rand = Math.floor(Math.random()*mult) % len
notify = @notify # was window.notify
perms = null
checkReqNotify = ->
console.log "After require notify: #{notify}"
return unless notify
perms = notify.permissionLevel()
console.log "perms are initially #{perms}"
if perms isnt notify.PERMISSION_GRANTED
perms = notify.requestPermission -> console.log "Permission Granted"
console.log "Perms after are #{perms}"
| true | # vim:expandtab:ts=2:
# @(#) $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $
$ = jQuery
# Handle requests from background.html
console.log "Loading $Id: demo.coffee 543 2014-11-05 00:41:31Z knoppix $"
console.log "Initializing %0", this
handleRequest = (request, sender, sendResponse) ->
console.log "got request #{request.callFunction}"
toggleSB() if request?.callFunction is "toggleSB"
chrome.extension.onRequest.addListener handleRequest
# Create the sidebar - ToDo: Use a config object as args to callSB
sidebarPrev = true # prev state true means current is false
[openTickets, aeTickets] = [[], []]
[genIvl, genIvlId, me] = [5, null, "PI:NAME:<NAME>END_PI"]
[lists, otId, maxAsn] = [{head: {}, top: {}}, 0, 5]
sbId = "mySidebar"
# undo createSB()
destroySB = ->
console.log "disabling sidebar and genIvl: #{genIvl}"
genIvlId? and clearInterval genIvlId
el = document.getElementById sbId
return el.parentNode.removeChild el
# create sidebar()
createSB = ->
navBar = """
<div class="navbar navbar-custom">
<div class="navbar-inner">
<a class="brand" href="#">JJR@DevOps</a>
<ul class="nav">
<li class="active"><a href="#">Open</a></li>
<li><a href="#">Servers</a></li>
<li><a href="#">Users</a></li>
<li><a href="#">Perms</a>
</ul>
</div>
</div>"""
# Start of Lists
lists.head.id = "listHead"
lists.head.html = """
<div id="#{lists.head.id}">
<h4>Open Requests <span class="badge">#{openTickets.length}</span></h1>
<ul class="nav-list"></ul>
</div>
"""
lists.top.id = "listTop"
lists.top.html = """
<div id="#{lists.top.id}">
<h4>Assigned Requests <span class="badge">#{aeTickets.length}</span></h4>
<ul class="nav-list"></ul>
</div>
"""
#var sbNav ='<button class="btn", id="servers">Servers</button>' +
# '<button class="btn", id="users">Users</button>'
sbMain = '<div> <ul id="sbMain"> </ul> <div>'
sidebar = document.createElement 'div'
sidebar.id = sbId
sidebar.style.display = 'hide'
sidebar.innerHTML ="""
#{navBar}
#{lists.head.html}
#{lists.top.html}
#{sbMain}
"""
document.body.appendChild sidebar
console.log "sidebar div added."
for name in ["head", "top"]
for tag in [ "ul", "span"]
lists[name][tag] = $ tag, "div##{lists[name].id}"
initLists()
# toggle and kick things off...
toggleSB = ->
genIvlId = setInterval genTicket, genIvl * 1000 unless genIvlId?
console.log "setting up a genTicket every #{genIvl} secs"
if sidebarPrev = not sidebarPrev then $("##{sbId}").hide() else $("##{sbId}").show()
console.log "enabling sidebar: checking notifications for this page"
checkReqNotify() # ToD:o fix request perms for current page
console.log "sidebar div added. Adding empty lists head: #{lists.head.id}, and top: #{lists.top.id}"
createSB() if not $("##{sbId}").length
initLists = () ->
once = false
if once
console.log "Initializing lists..."
openTickets.forEach (e)-> insElement e, lists.head
updCounters lists.head, openTickets.length
aeTickets.forEach (e)-> insElement e, lists.top
updCounters lists.top, aeTickets.length
addElement = (el, list, ary) ->
console.log "addEl: #{el} Before: ary: #{ary.length} to #{list.id}: #{list.ul.length}"
ary.push el
insElement el, list
console.log "addEl: After: ary: #{ary.length} ul: #{list.id}: #{list.ul.length}"
updCounters list, ary.length
title = (el) -> "#{el.st} - #{el.app} - #{el.cmp}"
createNotificationIfNotVisible = (el) ->
nOpts = body: el.detail, icon: "icon.png", tag: el.id
if el.status is "Open" and document.webkitVisibilityState isnt "visible"
el.closer = notify.createNotification "#{title el}", nOpts
insElement = (el, list) ->
[ae, labclass] = if el.ae then [" - #{el.ae} ", "label-info"] else ["", "label-warning active"]
createNotificationIfNotVisible el
html = """<li class="#{el.id}">#{title el}: <span class="label #{labclass}"> #{el.status}#{ae}</span></li>"""
$(html).hide().prependTo(list.ul).fadeIn 1900
removeElement = (sel, list, ary) ->
console.log "rmEl: before: #{sel} len: #{ary.length}, ul: #{list.id}: #{list.ul.length}"
found = _(ary).remove (e)-> e.id is sel
if found and ret = found.value()[0]
ret.closer.close() if ret.closer
$("li.#{sel}", list.ul).remove()
msg = "rmEl: after: #{ret.id} len: #{ary.length}, ul: #{list.id} (#{list.ul.length})"
console.log msg
# throw new Error(msg) unless list.ul.length < preRm
updCounters list, ary.length
else
msg = "didnt find #{sel} in #{list.id}"
console.log msg
throw new Error msg
ret
removeLast = (list, ary) ->
console.log "remLast of #{ary.length} (#{ list.ul.length})"
if ary.length > 0 and list.ul.length > 0
last = ary.pop()
if last.closer then last.closer.close()
list.ul.last().remove()
console.log "remLast of #{ary.length } (#{list.ul.length})"
else
console.log "No last element to remove"
updCounters = (list, val) -> list.span.text val
genTicket = ->
apps = [ "eP AuthHub", "eP4 Synergy", "eP VIPAA", "CSS Blaze", "eP ASA", "CTMT - CDS", "CTMT - KTC", "CTMT - DAF", "CGW - authGateway", "CGW - eCommerceGW", "BCT Gateway", "eP POE", "Brainiac Studio" ]
ctypes = [
{name: "Pilot DML", type: "DML"}
{name: "Ear", type: "WS"}
{name: "Dynamic DML", type: "DML"}
{name: "Web Assets", type: "SA"}
{name: "Jars", type: "SA"}
{name: "Properties", type: "SA"}
{name: "Artifacts", type: "SA"}
{name: "Config", type: "SA"}
{name: "Xml", type: "SA"}
]
detail =
WS: [ "Create:\nMember: PI:NAME:<NAME>END_PI (NBKI812)\nRole: Developer\n", "Create:\nEnviroment: DEV01\nServer: ldranql05\nApp Name:APP"]
SA: [ "Create:\nMember: PI:NAME:<NAME>END_PI (NBKK00L)\nRole: Manager\n", "Create:\nEnviroment: CERT01\nServer: ldranql05.chp.bankofamerica.com\nBase Artifact Install Dir:\n/hosting/apps/udeploy\n"]
DML: [ "Create:\nMember: ARandom Name\nRole: Lead Developer\n", "Environment: SIT02\nDML Env Name: E3SIT02"]
supTypes = [ "BS", "DS", "BO", "DO" ]
ai = getRandIdx apps.length
ct = getRandIdx ctypes.length
st = getRandIdx supTypes.length
ot =
ts: +Date.now()
id: "id-#{++otId}"
app: apps[ai]
cmp: ctypes[ct].name,
detail: detail[ctypes[ct].type]
status: "Open"
st: supTypes[st]
ae: null
toString: -> "#{@id}: #{@st} - #{@app} - #{@cmp}"
console.log "Generated random ticket #{ot}...adding to openTickets..."
addElement ot, lists.head, openTickets
console.log "added ticket #{ot} to #{lists.head.id}"
addAESecs = getRandIdx(5)+5
setTimeout assnTicket, addAESecs * 1000
# clean up assigned tickets
cleanAssigned = ->
while aeTickets.length > maxAsn
removeElement aeTickets[0].id, lists.top, aeTickets
# assign an avaialable ticket
retryMs = 1000
assnTicket = ->
aes = [ me, "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI", "PI:NAME:<NAME>END_PI" ]
olderOpen= _(openTickets).filter (e) -> (+Date.now() - e.ts) > retryMs
if olderOpen.length < 1
console.log "No tickets more than #{retryMs}ms old"
return setTimeout assnTicket, retryMs
aei = getRandIdx aes.length
oti = getRandIdx openTickets.length
ot = openTickets[oti]
console.log "Assigning open ticket @#{oti} #{ot} to #{aes[aei]}"
if rm = removeElement ot.id, lists.head, openTickets
rm.ae = aes[aei]
rm.status = "Accepted"
console.log "#{rm.ae} - #{rm.status} Ticket #{rm}"
addElement rm, lists.top, aeTickets
setTimeout cleanAssigned, 5000
getRandIdx = (len) ->
exp = Math.log len
exp = if exp < 1 then 1 else Math.floor exp
mult = Math.pow 10, exp
rand = Math.floor(Math.random()*mult) % len
notify = @notify # was window.notify
perms = null
checkReqNotify = ->
console.log "After require notify: #{notify}"
return unless notify
perms = notify.permissionLevel()
console.log "perms are initially #{perms}"
if perms isnt notify.PERMISSION_GRANTED
perms = notify.requestPermission -> console.log "Permission Granted"
console.log "Perms after are #{perms}"
|
[
{
"context": "author: \"Wittgenstein\"\nquote: \"A picture is a fact. -- $author\"",
"end": 21,
"score": 0.999853253364563,
"start": 9,
"tag": "NAME",
"value": "Wittgenstein"
}
] | lib/coffee/lib/coffee-script/documentation/coffee/interpolation.coffee | InfinitelLoop/website-3 | 2 | author: "Wittgenstein"
quote: "A picture is a fact. -- $author" | 82044 | author: "<NAME>"
quote: "A picture is a fact. -- $author" | true | author: "PI:NAME:<NAME>END_PI"
quote: "A picture is a fact. -- $author" |
[
{
"context": " host: \"http://demo.gitlab.com\"\n token: \"Wvjy2Krpb7y8xi93owUz\"\n password: \"123456\"\n login: \"test@test.com\"",
"end": 173,
"score": 0.9523305296897888,
"start": 153,
"tag": "PASSWORD",
"value": "Wvjy2Krpb7y8xi93owUz"
},
{
"context": "\"\n token: ... | hubots/hubot-gitsy/src/gitlab/tests/test.coffee | RocketChat/Rocket.Chat.Ops | 143 | assert = require 'assert'
# Setup
Gitlab = require('..')
credentials = # From http://demo.gitlab.com/
host: "http://demo.gitlab.com"
token: "Wvjy2Krpb7y8xi93owUz"
password: "123456"
login: "test@test.com"
gitlab = new Gitlab
token: credentials.token
url: credentials.host
# Working variables
projectId = 3
userId = 1
{validate_project} = require './validators'
mock = require './mock'
unless process.env.TEST_NO_MOCK?
mock.setup gitlab
describe 'User', ->
describe '#all()', ->
it 'should retrieve array of users without error', (done) ->
gitlab.users.all (result) ->
done()
describe '#current()', ->
it 'should retrieve current user without error', (done) ->
gitlab.users.current (result) ->
done()
describe '#show()', ->
it 'should retrieve a single user', (done) ->
gitlab.users.show userId, (result) ->
done()
describe '#session()', ->
it 'should retrieve a users session without error', (done) ->
gitlab.users.session credentials.login, credentials.password, (result) ->
done()
describe 'Project', ->
describe '#all()', ->
beforeEach ->
mock.get = (opts, cb) ->
cb(null, {}, mock.projects)
it 'should retrieve array of projects without error', (done) ->
gitlab.projects.all (projects) ->
assert projects.length > 0
validate_project project for project in projects
done()
describe '#show()', ->
beforeEach ->
mock.get = (opts, cb) ->
project = mock.projects[0]
project.id = parseInt mock.path.split('/')[-1...][0]
cb(null, {}, project)
it 'should retrieve single project', (done) ->
gitlab.projects.show projectId, (project) ->
assert.equal project.id, projectId
validate_project project
done()
describe 'Members', ->
describe '#listMembers()', ->
describe '#list', ->
it 'should retrieve list of members of a project', (done) ->
gitlab.projects.members.list projectId, (result) ->
done()
describe '#repository', ->
describe '#listBranches', ->
it 'should retrive branches of a given project', (done) ->
gitlab.projects.repository.listBranches projectId, (result) ->
done()
describe '#listCommits()', ->
it 'should retrieve commits of a given project', (done) ->
gitlab.projects.repository.listCommits projectId, (result) ->
done()
describe '#listTags()', ->
it 'should retrieve tags of a given project', (done) ->
gitlab.projects.repository.listTags projectId, (result) ->
done()
describe '#listTree()', ->
it 'should retrieve tree of a given project', (done) ->
gitlab.projects.repository.listTree projectId, (result) ->
done()
describe '#showFile()', ->
it 'should retrieve specified file with arity=3', (done) ->
opts = file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile projectId, opts, (result) ->
done()
it 'should retrieve specified file with arity=2', (done) ->
opts = projectId: projectId, file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile opts, (result) ->
done()
describe 'Issue', ->
describe '#all()', ->
it 'should retrieve array of issues created by user', (done) ->
gitlab.issues.all (result) ->
done()
| 166485 | assert = require 'assert'
# Setup
Gitlab = require('..')
credentials = # From http://demo.gitlab.com/
host: "http://demo.gitlab.com"
token: "<PASSWORD>"
password: "<PASSWORD>"
login: "<EMAIL>"
gitlab = new Gitlab
token: credentials.token
url: credentials.host
# Working variables
projectId = 3
userId = 1
{validate_project} = require './validators'
mock = require './mock'
unless process.env.TEST_NO_MOCK?
mock.setup gitlab
describe 'User', ->
describe '#all()', ->
it 'should retrieve array of users without error', (done) ->
gitlab.users.all (result) ->
done()
describe '#current()', ->
it 'should retrieve current user without error', (done) ->
gitlab.users.current (result) ->
done()
describe '#show()', ->
it 'should retrieve a single user', (done) ->
gitlab.users.show userId, (result) ->
done()
describe '#session()', ->
it 'should retrieve a users session without error', (done) ->
gitlab.users.session credentials.login, credentials.password, (result) ->
done()
describe 'Project', ->
describe '#all()', ->
beforeEach ->
mock.get = (opts, cb) ->
cb(null, {}, mock.projects)
it 'should retrieve array of projects without error', (done) ->
gitlab.projects.all (projects) ->
assert projects.length > 0
validate_project project for project in projects
done()
describe '#show()', ->
beforeEach ->
mock.get = (opts, cb) ->
project = mock.projects[0]
project.id = parseInt mock.path.split('/')[-1...][0]
cb(null, {}, project)
it 'should retrieve single project', (done) ->
gitlab.projects.show projectId, (project) ->
assert.equal project.id, projectId
validate_project project
done()
describe 'Members', ->
describe '#listMembers()', ->
describe '#list', ->
it 'should retrieve list of members of a project', (done) ->
gitlab.projects.members.list projectId, (result) ->
done()
describe '#repository', ->
describe '#listBranches', ->
it 'should retrive branches of a given project', (done) ->
gitlab.projects.repository.listBranches projectId, (result) ->
done()
describe '#listCommits()', ->
it 'should retrieve commits of a given project', (done) ->
gitlab.projects.repository.listCommits projectId, (result) ->
done()
describe '#listTags()', ->
it 'should retrieve tags of a given project', (done) ->
gitlab.projects.repository.listTags projectId, (result) ->
done()
describe '#listTree()', ->
it 'should retrieve tree of a given project', (done) ->
gitlab.projects.repository.listTree projectId, (result) ->
done()
describe '#showFile()', ->
it 'should retrieve specified file with arity=3', (done) ->
opts = file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile projectId, opts, (result) ->
done()
it 'should retrieve specified file with arity=2', (done) ->
opts = projectId: projectId, file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile opts, (result) ->
done()
describe 'Issue', ->
describe '#all()', ->
it 'should retrieve array of issues created by user', (done) ->
gitlab.issues.all (result) ->
done()
| true | assert = require 'assert'
# Setup
Gitlab = require('..')
credentials = # From http://demo.gitlab.com/
host: "http://demo.gitlab.com"
token: "PI:PASSWORD:<PASSWORD>END_PI"
password: "PI:PASSWORD:<PASSWORD>END_PI"
login: "PI:EMAIL:<EMAIL>END_PI"
gitlab = new Gitlab
token: credentials.token
url: credentials.host
# Working variables
projectId = 3
userId = 1
{validate_project} = require './validators'
mock = require './mock'
unless process.env.TEST_NO_MOCK?
mock.setup gitlab
describe 'User', ->
describe '#all()', ->
it 'should retrieve array of users without error', (done) ->
gitlab.users.all (result) ->
done()
describe '#current()', ->
it 'should retrieve current user without error', (done) ->
gitlab.users.current (result) ->
done()
describe '#show()', ->
it 'should retrieve a single user', (done) ->
gitlab.users.show userId, (result) ->
done()
describe '#session()', ->
it 'should retrieve a users session without error', (done) ->
gitlab.users.session credentials.login, credentials.password, (result) ->
done()
describe 'Project', ->
describe '#all()', ->
beforeEach ->
mock.get = (opts, cb) ->
cb(null, {}, mock.projects)
it 'should retrieve array of projects without error', (done) ->
gitlab.projects.all (projects) ->
assert projects.length > 0
validate_project project for project in projects
done()
describe '#show()', ->
beforeEach ->
mock.get = (opts, cb) ->
project = mock.projects[0]
project.id = parseInt mock.path.split('/')[-1...][0]
cb(null, {}, project)
it 'should retrieve single project', (done) ->
gitlab.projects.show projectId, (project) ->
assert.equal project.id, projectId
validate_project project
done()
describe 'Members', ->
describe '#listMembers()', ->
describe '#list', ->
it 'should retrieve list of members of a project', (done) ->
gitlab.projects.members.list projectId, (result) ->
done()
describe '#repository', ->
describe '#listBranches', ->
it 'should retrive branches of a given project', (done) ->
gitlab.projects.repository.listBranches projectId, (result) ->
done()
describe '#listCommits()', ->
it 'should retrieve commits of a given project', (done) ->
gitlab.projects.repository.listCommits projectId, (result) ->
done()
describe '#listTags()', ->
it 'should retrieve tags of a given project', (done) ->
gitlab.projects.repository.listTags projectId, (result) ->
done()
describe '#listTree()', ->
it 'should retrieve tree of a given project', (done) ->
gitlab.projects.repository.listTree projectId, (result) ->
done()
describe '#showFile()', ->
it 'should retrieve specified file with arity=3', (done) ->
opts = file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile projectId, opts, (result) ->
done()
it 'should retrieve specified file with arity=2', (done) ->
opts = projectId: projectId, file_path: 'README.md', ref: 'master'
gitlab.projects.repository.showFile opts, (result) ->
done()
describe 'Issue', ->
describe '#all()', ->
it 'should retrieve array of issues created by user', (done) ->
gitlab.issues.all (result) ->
done()
|
[
{
"context": "\n new app.models.Entry\n doc: @\n name: @name\n path: 'index'\n\n findEntryByPathAndHash",
"end": 918,
"score": 0.966381847858429,
"start": 918,
"tag": "NAME",
"value": ""
},
{
"context": " new app.models.Entry\n doc: @\n name: @name\n ... | resources/assets/coffee/models/doc.coffee | stevenay/Laradoc | 2 | class app.models.Doc extends app.Model
# Attributes: name, slug, type, version, index_path, db_path, db_size, mtime, links
constructor: ->
super
@reset @
@text = @name.toLowerCase()
reset: (data) ->
@resetEntries data.entries
@resetTypes data.types
return
resetEntries: (entries) ->
@entries = new app.collections.Entries(entries)
@entries.each (entry) => entry.doc = @;
return
resetTypes: (types) ->
@types = new app.collections.Types(types)
@types.each (type) => type.doc = @;
return
fullPath: (path = '') ->
path = "/#{path}" unless path[0] is '/'
"/#{@slug}#{path}"
fileUrl: (path) ->
"#{app.config.docs_host}#{@fullPath(path)}?#{@mtime}"
dbUrl: ->
"#{app.config.docs_host}/#{@db_path}?#{@mtime}"
indexUrl: ->
"#{app.indexHost()}/#{@index_path}?#{@mtime}"
toEntry: ->
new app.models.Entry
doc: @
name: @name
path: 'index'
findEntryByPathAndHash: (path, hash) ->
if hash and entry = @entries.findBy 'path', "#{path}##{hash}"
entry
else if path is 'index'
@toEntry()
else
@entries.findBy 'path', path
load: (onSuccess, onError, options = {}) ->
return if options.readCache and @_loadFromCache(onSuccess)
callback = (data) =>
@reset data
onSuccess()
@_setCache data if options.writeCache
return
# console.log @indexUrl() # /docs/c/index.json?1420139786
ajax
url: @indexUrl()
success: callback
error: onError
clearCache: ->
app.store.del @slug
return
_loadFromCache: (onSuccess) ->
return unless data = @_getCache()
# '=>' symbol will return the function
# I think it's because of _this variable
callback = =>
@reset data
onSuccess()
return
setTimeout callback, 0
true
_getCache: ->
return unless data = app.store.get @slug
if data[0] is @mtime
return data[1]
else
@clearCache()
return
_setCache: (data) ->
app.store.set @slug, [@mtime, data]
return
install: (onSuccess, onError) ->
return if @installing
@installing = true
error = =>
@installing = null
onError()
return
success = (data) =>
@installing = null
app.db.store @, data, onSuccess, error
return
ajax
url: @dbUrl()
success: success
error: error
timeout: 3600
return
uninstall: (onSuccess, onError) ->
return if @installing
@installing = true
success = =>
@installing = null
onSuccess()
return
error = =>
@installing = null
onError()
return
app.db.unstore @, success, error
return
getInstallStatus: (callback) ->
app.db.version @, (value) ->
callback installed: !!value, mtime: value
return
isOutdated: (status) ->
status.installed and @mtime isnt status.mtime
| 117923 | class app.models.Doc extends app.Model
# Attributes: name, slug, type, version, index_path, db_path, db_size, mtime, links
constructor: ->
super
@reset @
@text = @name.toLowerCase()
reset: (data) ->
@resetEntries data.entries
@resetTypes data.types
return
resetEntries: (entries) ->
@entries = new app.collections.Entries(entries)
@entries.each (entry) => entry.doc = @;
return
resetTypes: (types) ->
@types = new app.collections.Types(types)
@types.each (type) => type.doc = @;
return
fullPath: (path = '') ->
path = "/#{path}" unless path[0] is '/'
"/#{@slug}#{path}"
fileUrl: (path) ->
"#{app.config.docs_host}#{@fullPath(path)}?#{@mtime}"
dbUrl: ->
"#{app.config.docs_host}/#{@db_path}?#{@mtime}"
indexUrl: ->
"#{app.indexHost()}/#{@index_path}?#{@mtime}"
toEntry: ->
new app.models.Entry
doc: @
name:<NAME> @<NAME>
path: 'index'
findEntryByPathAndHash: (path, hash) ->
if hash and entry = @entries.findBy 'path', "#{path}##{hash}"
entry
else if path is 'index'
@toEntry()
else
@entries.findBy 'path', path
load: (onSuccess, onError, options = {}) ->
return if options.readCache and @_loadFromCache(onSuccess)
callback = (data) =>
@reset data
onSuccess()
@_setCache data if options.writeCache
return
# console.log @indexUrl() # /docs/c/index.json?1420139786
ajax
url: @indexUrl()
success: callback
error: onError
clearCache: ->
app.store.del @slug
return
_loadFromCache: (onSuccess) ->
return unless data = @_getCache()
# '=>' symbol will return the function
# I think it's because of _this variable
callback = =>
@reset data
onSuccess()
return
setTimeout callback, 0
true
_getCache: ->
return unless data = app.store.get @slug
if data[0] is @mtime
return data[1]
else
@clearCache()
return
_setCache: (data) ->
app.store.set @slug, [@mtime, data]
return
install: (onSuccess, onError) ->
return if @installing
@installing = true
error = =>
@installing = null
onError()
return
success = (data) =>
@installing = null
app.db.store @, data, onSuccess, error
return
ajax
url: @dbUrl()
success: success
error: error
timeout: 3600
return
uninstall: (onSuccess, onError) ->
return if @installing
@installing = true
success = =>
@installing = null
onSuccess()
return
error = =>
@installing = null
onError()
return
app.db.unstore @, success, error
return
getInstallStatus: (callback) ->
app.db.version @, (value) ->
callback installed: !!value, mtime: value
return
isOutdated: (status) ->
status.installed and @mtime isnt status.mtime
| true | class app.models.Doc extends app.Model
# Attributes: name, slug, type, version, index_path, db_path, db_size, mtime, links
constructor: ->
super
@reset @
@text = @name.toLowerCase()
reset: (data) ->
@resetEntries data.entries
@resetTypes data.types
return
resetEntries: (entries) ->
@entries = new app.collections.Entries(entries)
@entries.each (entry) => entry.doc = @;
return
resetTypes: (types) ->
@types = new app.collections.Types(types)
@types.each (type) => type.doc = @;
return
fullPath: (path = '') ->
path = "/#{path}" unless path[0] is '/'
"/#{@slug}#{path}"
fileUrl: (path) ->
"#{app.config.docs_host}#{@fullPath(path)}?#{@mtime}"
dbUrl: ->
"#{app.config.docs_host}/#{@db_path}?#{@mtime}"
indexUrl: ->
"#{app.indexHost()}/#{@index_path}?#{@mtime}"
toEntry: ->
new app.models.Entry
doc: @
name:PI:NAME:<NAME>END_PI @PI:NAME:<NAME>END_PI
path: 'index'
findEntryByPathAndHash: (path, hash) ->
if hash and entry = @entries.findBy 'path', "#{path}##{hash}"
entry
else if path is 'index'
@toEntry()
else
@entries.findBy 'path', path
load: (onSuccess, onError, options = {}) ->
return if options.readCache and @_loadFromCache(onSuccess)
callback = (data) =>
@reset data
onSuccess()
@_setCache data if options.writeCache
return
# console.log @indexUrl() # /docs/c/index.json?1420139786
ajax
url: @indexUrl()
success: callback
error: onError
clearCache: ->
app.store.del @slug
return
_loadFromCache: (onSuccess) ->
return unless data = @_getCache()
# '=>' symbol will return the function
# I think it's because of _this variable
callback = =>
@reset data
onSuccess()
return
setTimeout callback, 0
true
_getCache: ->
return unless data = app.store.get @slug
if data[0] is @mtime
return data[1]
else
@clearCache()
return
_setCache: (data) ->
app.store.set @slug, [@mtime, data]
return
install: (onSuccess, onError) ->
return if @installing
@installing = true
error = =>
@installing = null
onError()
return
success = (data) =>
@installing = null
app.db.store @, data, onSuccess, error
return
ajax
url: @dbUrl()
success: success
error: error
timeout: 3600
return
uninstall: (onSuccess, onError) ->
return if @installing
@installing = true
success = =>
@installing = null
onSuccess()
return
error = =>
@installing = null
onError()
return
app.db.unstore @, success, error
return
getInstallStatus: (callback) ->
app.db.version @, (value) ->
callback installed: !!value, mtime: value
return
isOutdated: (status) ->
status.installed and @mtime isnt status.mtime
|
[
{
"context": "###!\nCopyright (c) 2002-2017 \"Neo Technology,\"\nNetwork Engine for Objects in Lund AB [http://n",
"end": 44,
"score": 0.6880049109458923,
"start": 30,
"tag": "NAME",
"value": "Neo Technology"
}
] | src/components/D3Visualization/lib/visualization/components/queryPlan.coffee | yezonggang/zcfx-admin-master | 24 | ###!
Copyright (c) 2002-2017 "Neo Technology,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.queryPlan = (element)->
maxChildOperators = 2 # Fact we know about the cypher compiler
maxComparableRows = 1000000 # link widths are comparable between plans if all operators are below this row count
maxComparableDbHits = 1000000 # db hits are comparable between plans if all operators are below this db hit count
operatorWidth = 180
operatorCornerRadius = 4
operatorHeaderHeight = 18
operatorHeaderFontSize = 11
operatorDetailHeight = 14
maxCostHeight = 50
detailFontSize = 10
operatorMargin = 50
operatorPadding = 3
rankMargin = 50
margin = 10
standardFont = "'Helvetica Neue',Helvetica,Arial,sans-serif"
fixedWidthFont = "Monaco,'Courier New',Terminal,monospace"
linkColor = '#DFE1E3'
costColor = '#F25A29'
dividerColor = '#DFE1E3'
operatorColors = ["#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]
operatorCategories =
result: ['result']
seek: ['scan', 'seek', 'argument']
rows: ['limit', 'top', 'skip', 'sort', 'union', 'projection']
other: []
filter: ['select', 'filter', 'apply', 'distinct']
expand: ['expand', 'product', 'join', 'optional', 'path']
eager: ['eager']
augment = (color) ->
{
color: color,
'border-color': d3.rgb(color).darker(),
'text-color-internal': if d3.hsl(color).l < 0.7 then '#FFFFFF' else '#000000'
}
colors =
d3.scale.ordinal()
.domain(d3.keys(operatorCategories))
.range(operatorColors);
color = (d) ->
for name, keywords of operatorCategories
for keyword in keywords
if new RegExp(keyword, 'i').test(d)
return augment(colors(name))
augment(colors('other'))
rows = (operator) ->
operator.Rows ? operator.EstimatedRows ? 0
plural = (noun, count) ->
if count is 1 then noun else noun + 's'
formatNumber = d3.format(",.0f")
operatorDetails = (operator) ->
return [] unless operator.expanded
details = []
wordWrap = (string, className) ->
measure = (text) ->
neo.utils.measureText(text, fixedWidthFont, 10)
words = string.split(/([^a-zA-Z\d])/)
firstWord = 0
lastWord = 1
while firstWord < words.length
while lastWord < words.length and measure(words.slice(firstWord, lastWord + 1).join('')) < operatorWidth - operatorPadding * 2
lastWord++
details.push { className: className, value: words.slice(firstWord, lastWord).join('') }
firstWord = lastWord
lastWord = firstWord + 1
if identifiers = operator.identifiers ? operator.KeyNames?.split(', ')
wordWrap(identifiers.filter((d) -> not (/^ /.test(d))).join(', '), 'identifiers')
details.push { className: 'padding' }
if index = operator.Index
wordWrap(index, 'index')
details.push { className: 'padding' }
if expression = operator.LegacyExpression ? operator.ExpandExpression ? operator.LabelName ? operator.Signature
wordWrap(expression, 'expression')
details.push { className: 'padding' }
if operator.Rows? and operator.EstimatedRows?
details.push { className: 'estimated-rows', key: 'estimated rows', value: formatNumber(operator.EstimatedRows)}
if operator.DbHits? and not operator.alwaysShowCost
details.push { className: 'db-hits', key: plural('db hit', operator.DbHits || 0), value: formatNumber(operator.DbHits || 0)}
if details.length and details[details.length - 1].className == 'padding'
details.pop()
y = operatorDetailHeight
for detail in details
detail.y = y
y += if detail.className == 'padding'
operatorPadding * 2
else
operatorDetailHeight
details
transform = (queryPlan) ->
operators = []
links = []
result =
operatorType: 'Result'
children: [queryPlan.root]
collectLinks = (operator, rank) ->
operators.push operator
operator.rank = rank
for child in operator.children
child.parent = operator
collectLinks child, rank + 1
links.push
source: child
target: operator
collectLinks result, 0
[operators, links]
layout = (operators, links) ->
costHeight = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> operator.DbHits or 0), maxComparableDbHits)])
.range([0, maxCostHeight])
(operator) ->
scale((operator.DbHits ? 0) + 1)
operatorHeight = (operator) ->
height = operatorHeaderHeight
if operator.expanded
height += operatorDetails(operator).slice(-1)[0].y + operatorPadding * 2
height += costHeight(operator)
height
linkWidth = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> rows(operator) + 1), maxComparableRows)])
.range([2, (operatorWidth - operatorCornerRadius * 2) / maxChildOperators])
(operator) ->
scale(rows(operator) + 1)
for operator in operators
operator.height = operatorHeight(operator)
operator.costHeight = costHeight(operator)
if operator.costHeight > operatorDetailHeight + operatorPadding
operator.alwaysShowCost = true
childrenWidth = d3.sum(operator.children, linkWidth)
tx = (operatorWidth - childrenWidth) / 2
for child in operator.children
child.tx = tx
tx += linkWidth(child)
for link in links
link.width = linkWidth(link.source)
ranks = d3.nest()
.key((operator) -> operator.rank)
.entries(operators)
currentY = 0
for rank in ranks
currentY -= (d3.max(rank.values, operatorHeight) + rankMargin)
for operator in rank.values
operator.x = 0
operator.y = currentY
width = d3.max(ranks.map((rank) -> rank.values.length * (operatorWidth + operatorMargin)))
height = -currentY
collide = ->
for rank in ranks
x0 = 0
for operator in rank.values
dx = x0 - operator.x
if dx > 0
operator.x += dx
x0 = operator.x + operatorWidth + operatorMargin
dx = x0 - operatorMargin - width
if dx > 0
lastOperator = rank.values[rank.values.length - 1]
x0 = lastOperator.x -= dx
for i in [rank.values.length - 2..0] by -1
operator = rank.values[i]
dx = operator.x + operatorWidth + operatorMargin - x0
if dx > 0
operator.x -= operatorWidth
x0 = operator.x
center = (operator) ->
operator.x + operatorWidth / 2
relaxUpwards = (alpha) ->
for rank in ranks
for operator in rank.values
if operator.children.length
x = d3.sum(operator.children, (child) -> linkWidth(child) * center(child)) / d3.sum(operator.children, linkWidth)
operator.x += (x - center(operator)) * alpha
relaxDownwards = (alpha) ->
for rank in ranks.slice().reverse()
for operator in rank.values
if operator.parent
operator.x += (center(operator.parent) - center(operator)) * alpha
collide()
iterations = 300
alpha = 1
while iterations--
relaxUpwards(alpha)
collide()
relaxDownwards(alpha)
collide()
alpha *= .98
width = d3.max(operators, (o) -> o.x) - d3.min(operators, (o) -> o.x) + operatorWidth
[width, height]
render = (operators, links, width, height, redisplay) ->
svg = d3.select(element)
svg.transition()
.attr('width', width + margin * 2)
.attr('height', height + margin * 2)
.attr('viewBox', [d3.min(operators, (o) -> o.x) - margin, -margin - height, width + margin * 2, height + margin * 2].join(' '))
join = (parent, children) ->
for child in d3.entries(children)
selection = parent.selectAll(child.key).data(child.value.data)
child.value.selections(selection.enter(), selection, selection.exit())
if child.value.children
join(selection, child.value.children)
join(svg, {
'g.layer.links':
data: [links]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer links')
children:
'.link':
data: ((d) -> d),
selections: (enter) ->
enter.append('g')
.attr('class', 'link')
children:
'path':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('fill', linkColor)
update
.transition()
.attr('d', (d) ->
width = Math.max(1, d.width)
sourceX = d.source.x + operatorWidth / 2
targetX = d.target.x + d.source.tx
sourceY = d.source.y + d.source.height
targetY = d.target.y
yi = d3.interpolateNumber(sourceY, targetY)
curvature = .5
control1 = yi(curvature)
control2 = yi(1 - curvature)
controlWidth = Math.min(width / Math.PI, (targetY - sourceY) / Math.PI)
if sourceX > targetX + width / 2
controlWidth *= -1
[
'M', (sourceX + width / 2), sourceY,
'C', (sourceX + width / 2), control1 - controlWidth,
(targetX + width), control2 - controlWidth,
(targetX + width), targetY,
'L', targetX, targetY,
'C', targetX, control2 + controlWidth,
(sourceX - width / 2), control1 + controlWidth,
(sourceX - width / 2), sourceY,
'Z'
].join(' '))
'text':
data: (d) ->
x = d.source.x + operatorWidth / 2
y = d.source.y + d.source.height + operatorDetailHeight
source = d.source
if source.Rows? or source.EstimatedRows?
[key, caption] = if source.Rows?
['Rows', 'row']
else
['EstimatedRows', 'estimated row']
[
{ x: x, y: y, text: formatNumber(source[key]) + '\u00A0', anchor: 'end' }
{ x: x, y: y, text: plural(caption, source[key]), anchor: 'start' }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
update
.transition()
.attr('x', (d) -> d.x)
.attr('y', (d) -> d.y)
.attr('text-anchor', (d) -> d.anchor)
.text((d) -> d.text)
'g.layer.operators':
data: [operators]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer operators')
children:
'.operator':
data: ((d) -> d)
selections: (enter, update) ->
enter
.append('g')
.attr('class', 'operator')
update
.transition()
.attr('transform', (d) -> "translate(#{d.x},#{d.y})")
children:
'rect.background':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'background')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'white')
.style('stroke', 'none')
'g.header':
data: (d) -> [d]
selections: (enter) ->
enter
.append('g')
.attr('class', 'header')
.attr('pointer-events', 'all')
.on('click', (d) ->
d.expanded = !d.expanded
redisplay()
)
children:
'path.banner':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'banner')
update
.attr('d', (d) ->
shaving =
if d.height <= operatorHeaderHeight
operatorCornerRadius
else if d.height < operatorHeaderHeight + operatorCornerRadius
operatorCornerRadius - Math.sqrt(Math.pow(operatorCornerRadius, 2) -
Math.pow(operatorCornerRadius - d.height + operatorHeaderHeight, 2))
else 0
[
'M', operatorWidth - operatorCornerRadius, 0
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth, operatorCornerRadius
'L', operatorWidth, operatorHeaderHeight - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - shaving, operatorHeaderHeight
'L', shaving, operatorHeaderHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, operatorHeaderHeight - operatorCornerRadius
'L', 0, operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorCornerRadius, 0
'Z'
].join(' '))
.style('fill', (d) -> color(d.operatorType).color)
'path.expand':
data: (d) -> if d.operatorType is 'Result' then [] else [d]
selections: (enter, update) ->
rotateForExpand = (d) ->
d3.transform()
"translate(#{operatorHeaderHeight / 2}, #{operatorHeaderHeight / 2}) " +
"rotate(#{if d.expanded then 90 else 0}) " +
"scale(0.5)"
enter
.append('path')
.attr('class', 'expand')
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.attr('d', 'M -5 -10 L 8.66 0 L -5 10 Z')
.attr('transform', rotateForExpand)
update
.transition()
.attrTween('transform', (d, i, a) ->
d3.interpolateString(a, rotateForExpand(d))
)
'text.title':
data: (d) -> [d]
selections: (enter) ->
enter
.append('text')
.attr('class', 'title')
.attr('font-size', operatorHeaderFontSize)
.attr('font-family', standardFont)
.attr('x', operatorHeaderHeight)
.attr('y', 13)
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.text((d) -> d.operatorType)
'g.detail':
data: operatorDetails
selections: (enter, update, exit) ->
enter
.append('g')
update
.attr('class', (d) -> 'detail ' + d.className)
.attr('transform', (d) -> "translate(0, #{operatorHeaderHeight + d.y})")
.attr('font-family', (d) ->
if d.className is 'expression' or d.className is 'identifiers'
fixedWidthFont
else
standardFont)
exit.remove()
children:
'text':
data: (d) ->
if d.key
[
{ text: d.value + '\u00A0', anchor: 'end', x: operatorWidth / 2 }
{ text: d.key, anchor: 'start', x: operatorWidth / 2 }
]
else
[
{ text: d.value, anchor: 'start', x: operatorPadding }
]
selections: (enter, update, exit) ->
enter
.append('text')
.attr('font-size', detailFontSize)
update
.attr('x', (d) -> d.x)
.attr('text-anchor', (d) -> d.anchor)
.attr('fill', 'black')
.transition()
.each('end', ->
update
.text((d) -> d.text)
)
exit.remove()
'path.divider':
data: (d) ->
if (d.className == 'padding')
[d]
else
[]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'divider')
.attr('visibility', 'hidden')
update
.attr('d', [
'M', 0, -operatorPadding * 2
'L', operatorWidth, -operatorPadding * 2
].join(' '))
.attr('stroke', dividerColor)
.transition()
.each('end', ->
update
.attr('visibility', 'visible')
)
'path.cost':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'cost')
.attr('fill', costColor)
update
.transition()
.attr('d', (d) ->
if d.costHeight < operatorCornerRadius
shaving = operatorCornerRadius -
Math.sqrt(Math.pow(operatorCornerRadius, 2) - Math.pow(operatorCornerRadius - d.costHeight, 2))
[
'M', operatorWidth - shaving, d.height - d.costHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, shaving, d.height - d.costHeight
'Z'
].join(' ')
else
[
'M', 0, d.height - d.costHeight
'L', operatorWidth, d.height - d.costHeight
'L', operatorWidth, d.height - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, d.height - operatorCornerRadius
'Z'
].join(' ')
)
'text.cost':
data: (d) ->
if d.alwaysShowCost
y = d.height - d.costHeight + operatorDetailHeight
[
{ text: formatNumber(d.DbHits) + '\u00A0', anchor: 'end', y: y }
{ text: 'db hits', anchor: 'start', y: y }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('class', 'cost')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
.attr('fill', 'white')
update
.attr('x', operatorWidth / 2)
.attr('text-anchor', (d) -> d.anchor)
.transition()
.attr('y', (d) -> d.y)
.each('end', ->
update
.text((d) -> d.text)
)
'rect.outline':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'outline')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'none')
.attr('stroke-width', 1)
.style('stroke', (d) -> color(d.operatorType)['border-color'])
})
display = (queryPlan) ->
[operators, links] = transform(queryPlan)
[width, height] = layout(operators, links)
render(operators, links, width, height, -> display(queryPlan))
@display = display
@
| 225791 | ###!
Copyright (c) 2002-2017 "<NAME>,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.queryPlan = (element)->
maxChildOperators = 2 # Fact we know about the cypher compiler
maxComparableRows = 1000000 # link widths are comparable between plans if all operators are below this row count
maxComparableDbHits = 1000000 # db hits are comparable between plans if all operators are below this db hit count
operatorWidth = 180
operatorCornerRadius = 4
operatorHeaderHeight = 18
operatorHeaderFontSize = 11
operatorDetailHeight = 14
maxCostHeight = 50
detailFontSize = 10
operatorMargin = 50
operatorPadding = 3
rankMargin = 50
margin = 10
standardFont = "'Helvetica Neue',Helvetica,Arial,sans-serif"
fixedWidthFont = "Monaco,'Courier New',Terminal,monospace"
linkColor = '#DFE1E3'
costColor = '#F25A29'
dividerColor = '#DFE1E3'
operatorColors = ["#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]
operatorCategories =
result: ['result']
seek: ['scan', 'seek', 'argument']
rows: ['limit', 'top', 'skip', 'sort', 'union', 'projection']
other: []
filter: ['select', 'filter', 'apply', 'distinct']
expand: ['expand', 'product', 'join', 'optional', 'path']
eager: ['eager']
augment = (color) ->
{
color: color,
'border-color': d3.rgb(color).darker(),
'text-color-internal': if d3.hsl(color).l < 0.7 then '#FFFFFF' else '#000000'
}
colors =
d3.scale.ordinal()
.domain(d3.keys(operatorCategories))
.range(operatorColors);
color = (d) ->
for name, keywords of operatorCategories
for keyword in keywords
if new RegExp(keyword, 'i').test(d)
return augment(colors(name))
augment(colors('other'))
rows = (operator) ->
operator.Rows ? operator.EstimatedRows ? 0
plural = (noun, count) ->
if count is 1 then noun else noun + 's'
formatNumber = d3.format(",.0f")
operatorDetails = (operator) ->
return [] unless operator.expanded
details = []
wordWrap = (string, className) ->
measure = (text) ->
neo.utils.measureText(text, fixedWidthFont, 10)
words = string.split(/([^a-zA-Z\d])/)
firstWord = 0
lastWord = 1
while firstWord < words.length
while lastWord < words.length and measure(words.slice(firstWord, lastWord + 1).join('')) < operatorWidth - operatorPadding * 2
lastWord++
details.push { className: className, value: words.slice(firstWord, lastWord).join('') }
firstWord = lastWord
lastWord = firstWord + 1
if identifiers = operator.identifiers ? operator.KeyNames?.split(', ')
wordWrap(identifiers.filter((d) -> not (/^ /.test(d))).join(', '), 'identifiers')
details.push { className: 'padding' }
if index = operator.Index
wordWrap(index, 'index')
details.push { className: 'padding' }
if expression = operator.LegacyExpression ? operator.ExpandExpression ? operator.LabelName ? operator.Signature
wordWrap(expression, 'expression')
details.push { className: 'padding' }
if operator.Rows? and operator.EstimatedRows?
details.push { className: 'estimated-rows', key: 'estimated rows', value: formatNumber(operator.EstimatedRows)}
if operator.DbHits? and not operator.alwaysShowCost
details.push { className: 'db-hits', key: plural('db hit', operator.DbHits || 0), value: formatNumber(operator.DbHits || 0)}
if details.length and details[details.length - 1].className == 'padding'
details.pop()
y = operatorDetailHeight
for detail in details
detail.y = y
y += if detail.className == 'padding'
operatorPadding * 2
else
operatorDetailHeight
details
transform = (queryPlan) ->
operators = []
links = []
result =
operatorType: 'Result'
children: [queryPlan.root]
collectLinks = (operator, rank) ->
operators.push operator
operator.rank = rank
for child in operator.children
child.parent = operator
collectLinks child, rank + 1
links.push
source: child
target: operator
collectLinks result, 0
[operators, links]
layout = (operators, links) ->
costHeight = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> operator.DbHits or 0), maxComparableDbHits)])
.range([0, maxCostHeight])
(operator) ->
scale((operator.DbHits ? 0) + 1)
operatorHeight = (operator) ->
height = operatorHeaderHeight
if operator.expanded
height += operatorDetails(operator).slice(-1)[0].y + operatorPadding * 2
height += costHeight(operator)
height
linkWidth = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> rows(operator) + 1), maxComparableRows)])
.range([2, (operatorWidth - operatorCornerRadius * 2) / maxChildOperators])
(operator) ->
scale(rows(operator) + 1)
for operator in operators
operator.height = operatorHeight(operator)
operator.costHeight = costHeight(operator)
if operator.costHeight > operatorDetailHeight + operatorPadding
operator.alwaysShowCost = true
childrenWidth = d3.sum(operator.children, linkWidth)
tx = (operatorWidth - childrenWidth) / 2
for child in operator.children
child.tx = tx
tx += linkWidth(child)
for link in links
link.width = linkWidth(link.source)
ranks = d3.nest()
.key((operator) -> operator.rank)
.entries(operators)
currentY = 0
for rank in ranks
currentY -= (d3.max(rank.values, operatorHeight) + rankMargin)
for operator in rank.values
operator.x = 0
operator.y = currentY
width = d3.max(ranks.map((rank) -> rank.values.length * (operatorWidth + operatorMargin)))
height = -currentY
collide = ->
for rank in ranks
x0 = 0
for operator in rank.values
dx = x0 - operator.x
if dx > 0
operator.x += dx
x0 = operator.x + operatorWidth + operatorMargin
dx = x0 - operatorMargin - width
if dx > 0
lastOperator = rank.values[rank.values.length - 1]
x0 = lastOperator.x -= dx
for i in [rank.values.length - 2..0] by -1
operator = rank.values[i]
dx = operator.x + operatorWidth + operatorMargin - x0
if dx > 0
operator.x -= operatorWidth
x0 = operator.x
center = (operator) ->
operator.x + operatorWidth / 2
relaxUpwards = (alpha) ->
for rank in ranks
for operator in rank.values
if operator.children.length
x = d3.sum(operator.children, (child) -> linkWidth(child) * center(child)) / d3.sum(operator.children, linkWidth)
operator.x += (x - center(operator)) * alpha
relaxDownwards = (alpha) ->
for rank in ranks.slice().reverse()
for operator in rank.values
if operator.parent
operator.x += (center(operator.parent) - center(operator)) * alpha
collide()
iterations = 300
alpha = 1
while iterations--
relaxUpwards(alpha)
collide()
relaxDownwards(alpha)
collide()
alpha *= .98
width = d3.max(operators, (o) -> o.x) - d3.min(operators, (o) -> o.x) + operatorWidth
[width, height]
render = (operators, links, width, height, redisplay) ->
svg = d3.select(element)
svg.transition()
.attr('width', width + margin * 2)
.attr('height', height + margin * 2)
.attr('viewBox', [d3.min(operators, (o) -> o.x) - margin, -margin - height, width + margin * 2, height + margin * 2].join(' '))
join = (parent, children) ->
for child in d3.entries(children)
selection = parent.selectAll(child.key).data(child.value.data)
child.value.selections(selection.enter(), selection, selection.exit())
if child.value.children
join(selection, child.value.children)
join(svg, {
'g.layer.links':
data: [links]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer links')
children:
'.link':
data: ((d) -> d),
selections: (enter) ->
enter.append('g')
.attr('class', 'link')
children:
'path':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('fill', linkColor)
update
.transition()
.attr('d', (d) ->
width = Math.max(1, d.width)
sourceX = d.source.x + operatorWidth / 2
targetX = d.target.x + d.source.tx
sourceY = d.source.y + d.source.height
targetY = d.target.y
yi = d3.interpolateNumber(sourceY, targetY)
curvature = .5
control1 = yi(curvature)
control2 = yi(1 - curvature)
controlWidth = Math.min(width / Math.PI, (targetY - sourceY) / Math.PI)
if sourceX > targetX + width / 2
controlWidth *= -1
[
'M', (sourceX + width / 2), sourceY,
'C', (sourceX + width / 2), control1 - controlWidth,
(targetX + width), control2 - controlWidth,
(targetX + width), targetY,
'L', targetX, targetY,
'C', targetX, control2 + controlWidth,
(sourceX - width / 2), control1 + controlWidth,
(sourceX - width / 2), sourceY,
'Z'
].join(' '))
'text':
data: (d) ->
x = d.source.x + operatorWidth / 2
y = d.source.y + d.source.height + operatorDetailHeight
source = d.source
if source.Rows? or source.EstimatedRows?
[key, caption] = if source.Rows?
['Rows', 'row']
else
['EstimatedRows', 'estimated row']
[
{ x: x, y: y, text: formatNumber(source[key]) + '\u00A0', anchor: 'end' }
{ x: x, y: y, text: plural(caption, source[key]), anchor: 'start' }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
update
.transition()
.attr('x', (d) -> d.x)
.attr('y', (d) -> d.y)
.attr('text-anchor', (d) -> d.anchor)
.text((d) -> d.text)
'g.layer.operators':
data: [operators]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer operators')
children:
'.operator':
data: ((d) -> d)
selections: (enter, update) ->
enter
.append('g')
.attr('class', 'operator')
update
.transition()
.attr('transform', (d) -> "translate(#{d.x},#{d.y})")
children:
'rect.background':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'background')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'white')
.style('stroke', 'none')
'g.header':
data: (d) -> [d]
selections: (enter) ->
enter
.append('g')
.attr('class', 'header')
.attr('pointer-events', 'all')
.on('click', (d) ->
d.expanded = !d.expanded
redisplay()
)
children:
'path.banner':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'banner')
update
.attr('d', (d) ->
shaving =
if d.height <= operatorHeaderHeight
operatorCornerRadius
else if d.height < operatorHeaderHeight + operatorCornerRadius
operatorCornerRadius - Math.sqrt(Math.pow(operatorCornerRadius, 2) -
Math.pow(operatorCornerRadius - d.height + operatorHeaderHeight, 2))
else 0
[
'M', operatorWidth - operatorCornerRadius, 0
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth, operatorCornerRadius
'L', operatorWidth, operatorHeaderHeight - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - shaving, operatorHeaderHeight
'L', shaving, operatorHeaderHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, operatorHeaderHeight - operatorCornerRadius
'L', 0, operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorCornerRadius, 0
'Z'
].join(' '))
.style('fill', (d) -> color(d.operatorType).color)
'path.expand':
data: (d) -> if d.operatorType is 'Result' then [] else [d]
selections: (enter, update) ->
rotateForExpand = (d) ->
d3.transform()
"translate(#{operatorHeaderHeight / 2}, #{operatorHeaderHeight / 2}) " +
"rotate(#{if d.expanded then 90 else 0}) " +
"scale(0.5)"
enter
.append('path')
.attr('class', 'expand')
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.attr('d', 'M -5 -10 L 8.66 0 L -5 10 Z')
.attr('transform', rotateForExpand)
update
.transition()
.attrTween('transform', (d, i, a) ->
d3.interpolateString(a, rotateForExpand(d))
)
'text.title':
data: (d) -> [d]
selections: (enter) ->
enter
.append('text')
.attr('class', 'title')
.attr('font-size', operatorHeaderFontSize)
.attr('font-family', standardFont)
.attr('x', operatorHeaderHeight)
.attr('y', 13)
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.text((d) -> d.operatorType)
'g.detail':
data: operatorDetails
selections: (enter, update, exit) ->
enter
.append('g')
update
.attr('class', (d) -> 'detail ' + d.className)
.attr('transform', (d) -> "translate(0, #{operatorHeaderHeight + d.y})")
.attr('font-family', (d) ->
if d.className is 'expression' or d.className is 'identifiers'
fixedWidthFont
else
standardFont)
exit.remove()
children:
'text':
data: (d) ->
if d.key
[
{ text: d.value + '\u00A0', anchor: 'end', x: operatorWidth / 2 }
{ text: d.key, anchor: 'start', x: operatorWidth / 2 }
]
else
[
{ text: d.value, anchor: 'start', x: operatorPadding }
]
selections: (enter, update, exit) ->
enter
.append('text')
.attr('font-size', detailFontSize)
update
.attr('x', (d) -> d.x)
.attr('text-anchor', (d) -> d.anchor)
.attr('fill', 'black')
.transition()
.each('end', ->
update
.text((d) -> d.text)
)
exit.remove()
'path.divider':
data: (d) ->
if (d.className == 'padding')
[d]
else
[]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'divider')
.attr('visibility', 'hidden')
update
.attr('d', [
'M', 0, -operatorPadding * 2
'L', operatorWidth, -operatorPadding * 2
].join(' '))
.attr('stroke', dividerColor)
.transition()
.each('end', ->
update
.attr('visibility', 'visible')
)
'path.cost':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'cost')
.attr('fill', costColor)
update
.transition()
.attr('d', (d) ->
if d.costHeight < operatorCornerRadius
shaving = operatorCornerRadius -
Math.sqrt(Math.pow(operatorCornerRadius, 2) - Math.pow(operatorCornerRadius - d.costHeight, 2))
[
'M', operatorWidth - shaving, d.height - d.costHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, shaving, d.height - d.costHeight
'Z'
].join(' ')
else
[
'M', 0, d.height - d.costHeight
'L', operatorWidth, d.height - d.costHeight
'L', operatorWidth, d.height - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, d.height - operatorCornerRadius
'Z'
].join(' ')
)
'text.cost':
data: (d) ->
if d.alwaysShowCost
y = d.height - d.costHeight + operatorDetailHeight
[
{ text: formatNumber(d.DbHits) + '\u00A0', anchor: 'end', y: y }
{ text: 'db hits', anchor: 'start', y: y }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('class', 'cost')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
.attr('fill', 'white')
update
.attr('x', operatorWidth / 2)
.attr('text-anchor', (d) -> d.anchor)
.transition()
.attr('y', (d) -> d.y)
.each('end', ->
update
.text((d) -> d.text)
)
'rect.outline':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'outline')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'none')
.attr('stroke-width', 1)
.style('stroke', (d) -> color(d.operatorType)['border-color'])
})
display = (queryPlan) ->
[operators, links] = transform(queryPlan)
[width, height] = layout(operators, links)
render(operators, links, width, height, -> display(queryPlan))
@display = display
@
| true | ###!
Copyright (c) 2002-2017 "PI:NAME:<NAME>END_PI,"
Network Engine for Objects in Lund AB [http://neotechnology.com]
This file is part of Neo4j.
Neo4j is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
###
'use strict'
neo.queryPlan = (element)->
maxChildOperators = 2 # Fact we know about the cypher compiler
maxComparableRows = 1000000 # link widths are comparable between plans if all operators are below this row count
maxComparableDbHits = 1000000 # db hits are comparable between plans if all operators are below this db hit count
operatorWidth = 180
operatorCornerRadius = 4
operatorHeaderHeight = 18
operatorHeaderFontSize = 11
operatorDetailHeight = 14
maxCostHeight = 50
detailFontSize = 10
operatorMargin = 50
operatorPadding = 3
rankMargin = 50
margin = 10
standardFont = "'Helvetica Neue',Helvetica,Arial,sans-serif"
fixedWidthFont = "Monaco,'Courier New',Terminal,monospace"
linkColor = '#DFE1E3'
costColor = '#F25A29'
dividerColor = '#DFE1E3'
operatorColors = ["#c6dbef","#9ecae1","#6baed6","#4292c6","#2171b5","#08519c","#08306b"]
operatorCategories =
result: ['result']
seek: ['scan', 'seek', 'argument']
rows: ['limit', 'top', 'skip', 'sort', 'union', 'projection']
other: []
filter: ['select', 'filter', 'apply', 'distinct']
expand: ['expand', 'product', 'join', 'optional', 'path']
eager: ['eager']
augment = (color) ->
{
color: color,
'border-color': d3.rgb(color).darker(),
'text-color-internal': if d3.hsl(color).l < 0.7 then '#FFFFFF' else '#000000'
}
colors =
d3.scale.ordinal()
.domain(d3.keys(operatorCategories))
.range(operatorColors);
color = (d) ->
for name, keywords of operatorCategories
for keyword in keywords
if new RegExp(keyword, 'i').test(d)
return augment(colors(name))
augment(colors('other'))
rows = (operator) ->
operator.Rows ? operator.EstimatedRows ? 0
plural = (noun, count) ->
if count is 1 then noun else noun + 's'
formatNumber = d3.format(",.0f")
operatorDetails = (operator) ->
return [] unless operator.expanded
details = []
wordWrap = (string, className) ->
measure = (text) ->
neo.utils.measureText(text, fixedWidthFont, 10)
words = string.split(/([^a-zA-Z\d])/)
firstWord = 0
lastWord = 1
while firstWord < words.length
while lastWord < words.length and measure(words.slice(firstWord, lastWord + 1).join('')) < operatorWidth - operatorPadding * 2
lastWord++
details.push { className: className, value: words.slice(firstWord, lastWord).join('') }
firstWord = lastWord
lastWord = firstWord + 1
if identifiers = operator.identifiers ? operator.KeyNames?.split(', ')
wordWrap(identifiers.filter((d) -> not (/^ /.test(d))).join(', '), 'identifiers')
details.push { className: 'padding' }
if index = operator.Index
wordWrap(index, 'index')
details.push { className: 'padding' }
if expression = operator.LegacyExpression ? operator.ExpandExpression ? operator.LabelName ? operator.Signature
wordWrap(expression, 'expression')
details.push { className: 'padding' }
if operator.Rows? and operator.EstimatedRows?
details.push { className: 'estimated-rows', key: 'estimated rows', value: formatNumber(operator.EstimatedRows)}
if operator.DbHits? and not operator.alwaysShowCost
details.push { className: 'db-hits', key: plural('db hit', operator.DbHits || 0), value: formatNumber(operator.DbHits || 0)}
if details.length and details[details.length - 1].className == 'padding'
details.pop()
y = operatorDetailHeight
for detail in details
detail.y = y
y += if detail.className == 'padding'
operatorPadding * 2
else
operatorDetailHeight
details
transform = (queryPlan) ->
operators = []
links = []
result =
operatorType: 'Result'
children: [queryPlan.root]
collectLinks = (operator, rank) ->
operators.push operator
operator.rank = rank
for child in operator.children
child.parent = operator
collectLinks child, rank + 1
links.push
source: child
target: operator
collectLinks result, 0
[operators, links]
layout = (operators, links) ->
costHeight = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> operator.DbHits or 0), maxComparableDbHits)])
.range([0, maxCostHeight])
(operator) ->
scale((operator.DbHits ? 0) + 1)
operatorHeight = (operator) ->
height = operatorHeaderHeight
if operator.expanded
height += operatorDetails(operator).slice(-1)[0].y + operatorPadding * 2
height += costHeight(operator)
height
linkWidth = do ->
scale = d3.scale.log()
.domain([1, Math.max(d3.max(operators, (operator) -> rows(operator) + 1), maxComparableRows)])
.range([2, (operatorWidth - operatorCornerRadius * 2) / maxChildOperators])
(operator) ->
scale(rows(operator) + 1)
for operator in operators
operator.height = operatorHeight(operator)
operator.costHeight = costHeight(operator)
if operator.costHeight > operatorDetailHeight + operatorPadding
operator.alwaysShowCost = true
childrenWidth = d3.sum(operator.children, linkWidth)
tx = (operatorWidth - childrenWidth) / 2
for child in operator.children
child.tx = tx
tx += linkWidth(child)
for link in links
link.width = linkWidth(link.source)
ranks = d3.nest()
.key((operator) -> operator.rank)
.entries(operators)
currentY = 0
for rank in ranks
currentY -= (d3.max(rank.values, operatorHeight) + rankMargin)
for operator in rank.values
operator.x = 0
operator.y = currentY
width = d3.max(ranks.map((rank) -> rank.values.length * (operatorWidth + operatorMargin)))
height = -currentY
collide = ->
for rank in ranks
x0 = 0
for operator in rank.values
dx = x0 - operator.x
if dx > 0
operator.x += dx
x0 = operator.x + operatorWidth + operatorMargin
dx = x0 - operatorMargin - width
if dx > 0
lastOperator = rank.values[rank.values.length - 1]
x0 = lastOperator.x -= dx
for i in [rank.values.length - 2..0] by -1
operator = rank.values[i]
dx = operator.x + operatorWidth + operatorMargin - x0
if dx > 0
operator.x -= operatorWidth
x0 = operator.x
center = (operator) ->
operator.x + operatorWidth / 2
relaxUpwards = (alpha) ->
for rank in ranks
for operator in rank.values
if operator.children.length
x = d3.sum(operator.children, (child) -> linkWidth(child) * center(child)) / d3.sum(operator.children, linkWidth)
operator.x += (x - center(operator)) * alpha
relaxDownwards = (alpha) ->
for rank in ranks.slice().reverse()
for operator in rank.values
if operator.parent
operator.x += (center(operator.parent) - center(operator)) * alpha
collide()
iterations = 300
alpha = 1
while iterations--
relaxUpwards(alpha)
collide()
relaxDownwards(alpha)
collide()
alpha *= .98
width = d3.max(operators, (o) -> o.x) - d3.min(operators, (o) -> o.x) + operatorWidth
[width, height]
render = (operators, links, width, height, redisplay) ->
svg = d3.select(element)
svg.transition()
.attr('width', width + margin * 2)
.attr('height', height + margin * 2)
.attr('viewBox', [d3.min(operators, (o) -> o.x) - margin, -margin - height, width + margin * 2, height + margin * 2].join(' '))
join = (parent, children) ->
for child in d3.entries(children)
selection = parent.selectAll(child.key).data(child.value.data)
child.value.selections(selection.enter(), selection, selection.exit())
if child.value.children
join(selection, child.value.children)
join(svg, {
'g.layer.links':
data: [links]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer links')
children:
'.link':
data: ((d) -> d),
selections: (enter) ->
enter.append('g')
.attr('class', 'link')
children:
'path':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('fill', linkColor)
update
.transition()
.attr('d', (d) ->
width = Math.max(1, d.width)
sourceX = d.source.x + operatorWidth / 2
targetX = d.target.x + d.source.tx
sourceY = d.source.y + d.source.height
targetY = d.target.y
yi = d3.interpolateNumber(sourceY, targetY)
curvature = .5
control1 = yi(curvature)
control2 = yi(1 - curvature)
controlWidth = Math.min(width / Math.PI, (targetY - sourceY) / Math.PI)
if sourceX > targetX + width / 2
controlWidth *= -1
[
'M', (sourceX + width / 2), sourceY,
'C', (sourceX + width / 2), control1 - controlWidth,
(targetX + width), control2 - controlWidth,
(targetX + width), targetY,
'L', targetX, targetY,
'C', targetX, control2 + controlWidth,
(sourceX - width / 2), control1 + controlWidth,
(sourceX - width / 2), sourceY,
'Z'
].join(' '))
'text':
data: (d) ->
x = d.source.x + operatorWidth / 2
y = d.source.y + d.source.height + operatorDetailHeight
source = d.source
if source.Rows? or source.EstimatedRows?
[key, caption] = if source.Rows?
['Rows', 'row']
else
['EstimatedRows', 'estimated row']
[
{ x: x, y: y, text: formatNumber(source[key]) + '\u00A0', anchor: 'end' }
{ x: x, y: y, text: plural(caption, source[key]), anchor: 'start' }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
update
.transition()
.attr('x', (d) -> d.x)
.attr('y', (d) -> d.y)
.attr('text-anchor', (d) -> d.anchor)
.text((d) -> d.text)
'g.layer.operators':
data: [operators]
selections: (enter) ->
enter.append('g')
.attr('class', 'layer operators')
children:
'.operator':
data: ((d) -> d)
selections: (enter, update) ->
enter
.append('g')
.attr('class', 'operator')
update
.transition()
.attr('transform', (d) -> "translate(#{d.x},#{d.y})")
children:
'rect.background':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'background')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'white')
.style('stroke', 'none')
'g.header':
data: (d) -> [d]
selections: (enter) ->
enter
.append('g')
.attr('class', 'header')
.attr('pointer-events', 'all')
.on('click', (d) ->
d.expanded = !d.expanded
redisplay()
)
children:
'path.banner':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'banner')
update
.attr('d', (d) ->
shaving =
if d.height <= operatorHeaderHeight
operatorCornerRadius
else if d.height < operatorHeaderHeight + operatorCornerRadius
operatorCornerRadius - Math.sqrt(Math.pow(operatorCornerRadius, 2) -
Math.pow(operatorCornerRadius - d.height + operatorHeaderHeight, 2))
else 0
[
'M', operatorWidth - operatorCornerRadius, 0
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth, operatorCornerRadius
'L', operatorWidth, operatorHeaderHeight - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - shaving, operatorHeaderHeight
'L', shaving, operatorHeaderHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, operatorHeaderHeight - operatorCornerRadius
'L', 0, operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorCornerRadius, 0
'Z'
].join(' '))
.style('fill', (d) -> color(d.operatorType).color)
'path.expand':
data: (d) -> if d.operatorType is 'Result' then [] else [d]
selections: (enter, update) ->
rotateForExpand = (d) ->
d3.transform()
"translate(#{operatorHeaderHeight / 2}, #{operatorHeaderHeight / 2}) " +
"rotate(#{if d.expanded then 90 else 0}) " +
"scale(0.5)"
enter
.append('path')
.attr('class', 'expand')
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.attr('d', 'M -5 -10 L 8.66 0 L -5 10 Z')
.attr('transform', rotateForExpand)
update
.transition()
.attrTween('transform', (d, i, a) ->
d3.interpolateString(a, rotateForExpand(d))
)
'text.title':
data: (d) -> [d]
selections: (enter) ->
enter
.append('text')
.attr('class', 'title')
.attr('font-size', operatorHeaderFontSize)
.attr('font-family', standardFont)
.attr('x', operatorHeaderHeight)
.attr('y', 13)
.attr('fill', (d) -> color(d.operatorType)['text-color-internal'])
.text((d) -> d.operatorType)
'g.detail':
data: operatorDetails
selections: (enter, update, exit) ->
enter
.append('g')
update
.attr('class', (d) -> 'detail ' + d.className)
.attr('transform', (d) -> "translate(0, #{operatorHeaderHeight + d.y})")
.attr('font-family', (d) ->
if d.className is 'expression' or d.className is 'identifiers'
fixedWidthFont
else
standardFont)
exit.remove()
children:
'text':
data: (d) ->
if d.key
[
{ text: d.value + '\u00A0', anchor: 'end', x: operatorWidth / 2 }
{ text: d.key, anchor: 'start', x: operatorWidth / 2 }
]
else
[
{ text: d.value, anchor: 'start', x: operatorPadding }
]
selections: (enter, update, exit) ->
enter
.append('text')
.attr('font-size', detailFontSize)
update
.attr('x', (d) -> d.x)
.attr('text-anchor', (d) -> d.anchor)
.attr('fill', 'black')
.transition()
.each('end', ->
update
.text((d) -> d.text)
)
exit.remove()
'path.divider':
data: (d) ->
if (d.className == 'padding')
[d]
else
[]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'divider')
.attr('visibility', 'hidden')
update
.attr('d', [
'M', 0, -operatorPadding * 2
'L', operatorWidth, -operatorPadding * 2
].join(' '))
.attr('stroke', dividerColor)
.transition()
.each('end', ->
update
.attr('visibility', 'visible')
)
'path.cost':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('path')
.attr('class', 'cost')
.attr('fill', costColor)
update
.transition()
.attr('d', (d) ->
if d.costHeight < operatorCornerRadius
shaving = operatorCornerRadius -
Math.sqrt(Math.pow(operatorCornerRadius, 2) - Math.pow(operatorCornerRadius - d.costHeight, 2))
[
'M', operatorWidth - shaving, d.height - d.costHeight
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, shaving, d.height - d.costHeight
'Z'
].join(' ')
else
[
'M', 0, d.height - d.costHeight
'L', operatorWidth, d.height - d.costHeight
'L', operatorWidth, d.height - operatorCornerRadius
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, operatorWidth - operatorCornerRadius, d.height
'L', operatorCornerRadius, d.height
'A', operatorCornerRadius, operatorCornerRadius, 0, 0, 1, 0, d.height - operatorCornerRadius
'Z'
].join(' ')
)
'text.cost':
data: (d) ->
if d.alwaysShowCost
y = d.height - d.costHeight + operatorDetailHeight
[
{ text: formatNumber(d.DbHits) + '\u00A0', anchor: 'end', y: y }
{ text: 'db hits', anchor: 'start', y: y }
]
else
[]
selections: (enter, update) ->
enter
.append('text')
.attr('class', 'cost')
.attr('font-size', detailFontSize)
.attr('font-family', standardFont)
.attr('fill', 'white')
update
.attr('x', operatorWidth / 2)
.attr('text-anchor', (d) -> d.anchor)
.transition()
.attr('y', (d) -> d.y)
.each('end', ->
update
.text((d) -> d.text)
)
'rect.outline':
data: (d) -> [d]
selections: (enter, update) ->
enter
.append('rect')
.attr('class', 'outline')
update
.transition()
.attr('width', operatorWidth)
.attr('height', (d) -> d.height)
.attr('rx', operatorCornerRadius)
.attr('ry', operatorCornerRadius)
.attr('fill', 'none')
.attr('stroke-width', 1)
.style('stroke', (d) -> color(d.operatorType)['border-color'])
})
display = (queryPlan) ->
[operators, links] = transform(queryPlan)
[width, height] = layout(operators, links)
render(operators, links, width, height, -> display(queryPlan))
@display = display
@
|
[
{
"context": "eScript 的解析器是从这个语法文件, 用 [Jison](http://github.com/zaach/jison) 生成的.\n# Jison 是个自底而上的解析器生成工具, 和 [Bison](htt",
"end": 62,
"score": 0.9994620084762573,
"start": 57,
"tag": "USERNAME",
"value": "zaach"
},
{
"context": "n\\s*([\\s\\S]*);\\s*\\}/\n\n# 我们方便 Jison 语法生成的 DSL 要感谢... | src/grammar.coffee | sqlwwx/coffeescript-zh | 0 | # CoffeeScript 的解析器是从这个语法文件, 用 [Jison](http://github.com/zaach/jison) 生成的.
# Jison 是个自底而上的解析器生成工具, 和 [Bison](http://www.gnu.org/software/bison) 的风格相似, 不过是用 JavaScript 实现的.
# 它可以辨认 [LALR(1), LR(0), SLR(1) 和 LR(1)](http://en.wikipedia.org/wiki/LR_grammar) 语法.
# 为了创建 Jison 解析器, 我们把匹配模式列在左边, 把对应动作列在右边 (通常是创建语法树的节点).
# 执行的时候, 解析器自左往右地, 从流中取出 token, 然后尝试把 token 序列[匹配](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# 到下面写的语法规则中. 如果可以匹配, 会把取出的 token 缩减成 [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# 的符号 (语法规则前边的名字), 然后继续.
#
# 如果你执行命令 `cake build:parser`, Jison 就会按照我们的规则建立语法解析表, 保存到 `lib/parser.js` 中.
# 唯一的依赖: **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Jison 会给我们的解析器多包装一层函数.
# 如果包装函数只是简单的返回一个值, 我们就可以通过移除包装函数, 直接返回里面的内容来做优化.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# 我们方便 Jison 语法生成的 DSL 要感谢 [Tim Caswell](http://github.com/creationix).
# 每条语法规则带有定义模式的字符串, 可选的动作和额外选项.
# 如果没有指定动作, 就简单的返回上一个 nonterminal 的值.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
patternCount = patternString.split(' ').length
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
# 所有需要在 "yy" 上定义的运行时函数
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
# 构造一个函数, 往第一个参数加上位置数据, 然后返回之.
# 如果该参数不是节点, 就不做修改的返回.
addLocationDataFn = (first, last) ->
if not last
"yy.addLocationDataFn(@#{first})"
else
"yy.addLocationDataFn(@#{first}, @#{last})"
action = action.replace /LOC\(([0-9]*)\)/g, addLocationDataFn('$1')
action = action.replace /LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn('$1', '$2')
[patternString, "$$ = #{addLocationDataFn(1, patternCount)}(#{action});", options]
# 语法规则
# -----------------
# 下面列出了候选的匹配规则. 你可以看到 nonterminal 的名字是键值.
# 每个匹配的动作中, 以 `$` 打头的变量是 Jison 提供的, 对应数字的位置的值. 在这条规则中:
#
# "Expression UNLESS Expression"
#
# `$1` 的值就是第一个 `Expression`, `$2` 的值就是终结符(terminal) `UNLESS` 对应的 token, `$3` 就是的值就是第二个 `Expression`
grammar =
# **Root** 是语法树最顶层的节点. 由于我们是自低而上解析的, 所有解析都会终结于此.
Root: [
o '', -> new Block
o 'Body'
]
# 由任意语句和表达式组成, 被换行符或者分号分隔
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# 块和语句, 占据 **Body** 中的一行
Line: [
o 'Expression'
o 'Statement'
]
# 不能当作表达式的纯语句
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# 我们语言中所有不同类型的表达式. CoffeeScript 的基本组成元素是 **Expression** -- 所有可以成为表达式的东西都融为一个规则.
# 例外的是, **Block** 同时也递归作为其他很多规则的基本构件, 所以没添加到这里.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# 由表达式组成, 缩进的块. 注意 [Rewriter](rewriter.html) 会通过调整 token 流的方法, 把一些后缀式的写法转换成块.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# 标识符字面量, 变量名或者属性.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics 独立于其他 **Literal**, 是因为它们仅用作对象字面量的的键值.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'String'
]
String: [
o 'STRING', -> new Literal $1
o 'STRING_START Body STRING_END', -> new Parens $2
]
Regex: [
o 'REGEX', -> new Literal $1
o 'REGEX_START Invocation REGEX_END', -> $2
]
# 所有直接量. 基本都可以不处理直接变成 JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'Regex'
o 'DEBUGGER', -> new Literal $1
o 'UNDEFINED', -> new Undefined
o 'NULL', -> new Null
o 'BOOL', -> new Bool $1
]
# 变量, 属性或者下标 的赋值
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# 在对象字面量中的赋值. 和一般 **Assign** 规则不同之处是: 这里允许数字或者字符串作为键值.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign LOC(1)(new Value($1)), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign LOC(1)(new Value($1)), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# 函数体中的返回语句.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# 注释块
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# **Code** 节点是函数字面量. 缩进的代码块 **Block** 之前带一个函数箭头, 和一个可选的参数列表.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript 有两个不同的箭头符号. `->` 是给一般函数用的, 而 `=>` 函数会绑定到当前 *this* 的值.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# 可选的行末逗号
OptComma: [
o ''
o ','
]
# 函数可以接受任意长的参数列表
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
o 'ParamList OptComma TERMINATOR Param', -> $1.concat $4
o 'ParamList OptComma INDENT ParamList OptComma OUTDENT', -> $1.concat $4
]
# 函数的一个参数可以正常的定义, 或者用 splat 把剩下的参数汇集到一起.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
o '...', -> new Expansion
]
# 函数参数.
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# 在函数参数之外的 splat.
Splat: [
o 'Expression ...', -> new Splat $1
]
# 可以赋值的变量或者属性.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# 所有可以赋值到的东西.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 可以被当作值的类型 -- 可赋值到的量, 函数调用, 数组下标, "类"等等.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# 总合了大部分访问对象内容的手段: 通过属性, 原型, 数组下标或者数组切片.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [LOC(1)(new Access new Literal('prototype')), LOC(2)(new Access $2)]
o '?:: Identifier', -> [LOC(1)(new Access new Literal('prototype'), 'soak'), LOC(2)(new Access $2)]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# 使用方括号语法访问对象或数组内部.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# 在 CoffeeScript 里, 一个对象字面量是简单的由属性赋值列表组成.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# 对象字面量中的属性赋值, 可以像 JavaScript 那样用逗号分隔, 或者直接用换行分隔.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# 类定义包含可选的原型属性赋值, 和可选的到超类的引用.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# 一般函数调用, 或者链式函数调用.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# 可选的函数存在性检查.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# 函数调用的参数列表.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# 对当前对象 *this* 的引用.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# 对 *this* 的属性的引用.
ThisProperty: [
o '@ Identifier', -> new Value LOC(1)(new Literal('this')), [LOC(2)(new Access($2))], 'this'
]
# 数组字面量.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# inclusive 和 exclusive 范围.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# CoffeeScript 范围字面量.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# 数组切片字面量.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
o 'RangeDots', -> new Range null, null, $1
]
# **ArgList** 既可以是传给函数调用的对象列表, 又可以作为数组字面量的内容
# (特别是逗号分隔的表达式). 新行分隔也可以.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# 块或者 Splat 都是合法的参数.
Arg: [
o 'Expression'
o 'Splat'
o '...', -> new Expansion
]
# 简单的, 逗号分隔的, 必须的参数 (没华丽的语法). 为了使这个规则可以在不支持多行的 **Switch** 块中使用, 我们把它和 **ArgList** 分离开来.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# *try/catch/finally* 异常处理块的各变种.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# catch 子句把赋给异常对象一个名字并执行代码块.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
o 'CATCH Object Block', -> [LOC(2)(new Value($2)), $3]
o 'CATCH Block', -> [null, $2]
]
# 抛出一个异常对象.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# 括号表达式. 注意 **Parenthetical** 是个 **Value** 而不是 **Expression**,
# 所以如果你要把表达式放到一个仅接受值的地方, 总用括号包起来就可以了.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# while 循环的条件部分.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# while 循环一般带个待执行的表达式块, 也可以是后缀式地加到一个表达式后. 没有 do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Expression WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(LOC(1) new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(LOC(1) new Literal 'true').addBody LOC(2) Block.wrap [$2]
]
# 数组, 对象和范围 comprehension 的一般写法.
# Comprehension 一般带个代执行的表达式块, 也可以是后缀式地加到一个表达式后.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: (LOC(2) new Value($2))
o 'FOR Range BY Expression', -> source: (LOC(2) new Value($2)), step: $4
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# 循环中的一个变量, 取于数组中满足条件的值. 支持模式匹配.
ForValue: [
o 'Identifier'
o 'ThisProperty'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 一个数组或者范围 comprehension 包含对应当前元素的变量, 和 (可选的) 对当前下标的引用.
# 在对象 comprehension 的情况下, 则是 *key, value*.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# comprehension 的源是个数组或者对象, 带可选的 guard 从句. 如果是数组 comprehension, 你还可以选择固定间隔的步进.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# 单独的 **When** 从句, 带动作.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# 最基本的 *if* 只含条件和动作. 下面把 if 相关的规则拆分开来, 是为了避免二义性.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse LOC(3,5) new If $4, $5, type: $3
]
# 其他 *if* 表达式的形式, 包含后缀式一行流的 *if* 和 *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
]
# 算术和逻辑操作符, 作用于 1 个或者多个操作数(operand).
# 这里把它们按优先级分组. 确切的优先级规则在页低给出.
# 如果我们可以把大部分都归结到一个泛化的 *Operand OpSymbol Operand* 形式的规则, 这个定义就可以短很多.
# 但为了使优先级生效, 就得分别定义了.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o 'UNARY_MATH Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY_MATH'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY_MATH'
o 'YIELD Statement', -> new Op $1 , $2
o 'YIELD Expression', -> new Op $1 , $2
o 'YIELD FROM Expression', -> new Op $1.concat($2) , $3
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [存在性操作符](http://coffee-js.github.io/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression ** Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2[1..], $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable COMPOUND_ASSIGN TERMINATOR
Expression', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# 优先级
# ----------
# 在上面的操作符比下面的操作符优先级更高. 下面的规则使得 `2 + 3 * 4` 解析成:
#
# 2 + (3 * 4)
#
# 而不是:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::', '?::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['right', '**']
['right', 'UNARY_MATH']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', 'YIELD']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['left', 'POST_IF']
]
# 包装
# -----------
# 既然 **语法** 和 **操作符** 都有了, 我们终于可以创建 **Jison.Parser** 了.
# 我们的做法是遍历所有规则, 把全部终结符 (不在上面的规则中的符号) 标记记为 "token".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# 用 **token** 终结符和 **grammar** 规则初始化 **Parser**, 并指定根规则.
# 这里还逆序排列了操作符列表, 因为 Jison 需要从低到高的优先级排列操作符,
# 而我们的定义顺序是从高到低 (和 [Yacc](http://dinosaur.compilertools.net/yacc/index.html) 一样).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
| 48560 | # CoffeeScript 的解析器是从这个语法文件, 用 [Jison](http://github.com/zaach/jison) 生成的.
# Jison 是个自底而上的解析器生成工具, 和 [Bison](http://www.gnu.org/software/bison) 的风格相似, 不过是用 JavaScript 实现的.
# 它可以辨认 [LALR(1), LR(0), SLR(1) 和 LR(1)](http://en.wikipedia.org/wiki/LR_grammar) 语法.
# 为了创建 Jison 解析器, 我们把匹配模式列在左边, 把对应动作列在右边 (通常是创建语法树的节点).
# 执行的时候, 解析器自左往右地, 从流中取出 token, 然后尝试把 token 序列[匹配](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# 到下面写的语法规则中. 如果可以匹配, 会把取出的 token 缩减成 [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# 的符号 (语法规则前边的名字), 然后继续.
#
# 如果你执行命令 `cake build:parser`, Jison 就会按照我们的规则建立语法解析表, 保存到 `lib/parser.js` 中.
# 唯一的依赖: **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Jison 会给我们的解析器多包装一层函数.
# 如果包装函数只是简单的返回一个值, 我们就可以通过移除包装函数, 直接返回里面的内容来做优化.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# 我们方便 Jison 语法生成的 DSL 要感谢 [<NAME>](http://github.com/creationix).
# 每条语法规则带有定义模式的字符串, 可选的动作和额外选项.
# 如果没有指定动作, 就简单的返回上一个 nonterminal 的值.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
patternCount = patternString.split(' ').length
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
# 所有需要在 "yy" 上定义的运行时函数
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
# 构造一个函数, 往第一个参数加上位置数据, 然后返回之.
# 如果该参数不是节点, 就不做修改的返回.
addLocationDataFn = (first, last) ->
if not last
"yy.addLocationDataFn(@#{first})"
else
"yy.addLocationDataFn(@#{first}, @#{last})"
action = action.replace /LOC\(([0-9]*)\)/g, addLocationDataFn('$1')
action = action.replace /LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn('$1', '$2')
[patternString, "$$ = #{addLocationDataFn(1, patternCount)}(#{action});", options]
# 语法规则
# -----------------
# 下面列出了候选的匹配规则. 你可以看到 nonterminal 的名字是键值.
# 每个匹配的动作中, 以 `$` 打头的变量是 Jison 提供的, 对应数字的位置的值. 在这条规则中:
#
# "Expression UNLESS Expression"
#
# `$1` 的值就是第一个 `Expression`, `$2` 的值就是终结符(terminal) `UNLESS` 对应的 token, `$3` 就是的值就是第二个 `Expression`
grammar =
# **Root** 是语法树最顶层的节点. 由于我们是自低而上解析的, 所有解析都会终结于此.
Root: [
o '', -> new Block
o 'Body'
]
# 由任意语句和表达式组成, 被换行符或者分号分隔
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# 块和语句, 占据 **Body** 中的一行
Line: [
o 'Expression'
o 'Statement'
]
# 不能当作表达式的纯语句
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# 我们语言中所有不同类型的表达式. CoffeeScript 的基本组成元素是 **Expression** -- 所有可以成为表达式的东西都融为一个规则.
# 例外的是, **Block** 同时也递归作为其他很多规则的基本构件, 所以没添加到这里.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# 由表达式组成, 缩进的块. 注意 [Rewriter](rewriter.html) 会通过调整 token 流的方法, 把一些后缀式的写法转换成块.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# 标识符字面量, 变量名或者属性.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics 独立于其他 **Literal**, 是因为它们仅用作对象字面量的的键值.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'String'
]
String: [
o 'STRING', -> new Literal $1
o 'STRING_START Body STRING_END', -> new Parens $2
]
Regex: [
o 'REGEX', -> new Literal $1
o 'REGEX_START Invocation REGEX_END', -> $2
]
# 所有直接量. 基本都可以不处理直接变成 JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'Regex'
o 'DEBUGGER', -> new Literal $1
o 'UNDEFINED', -> new Undefined
o 'NULL', -> new Null
o 'BOOL', -> new Bool $1
]
# 变量, 属性或者下标 的赋值
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# 在对象字面量中的赋值. 和一般 **Assign** 规则不同之处是: 这里允许数字或者字符串作为键值.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign LOC(1)(new Value($1)), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign LOC(1)(new Value($1)), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# 函数体中的返回语句.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# 注释块
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# **Code** 节点是函数字面量. 缩进的代码块 **Block** 之前带一个函数箭头, 和一个可选的参数列表.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript 有两个不同的箭头符号. `->` 是给一般函数用的, 而 `=>` 函数会绑定到当前 *this* 的值.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# 可选的行末逗号
OptComma: [
o ''
o ','
]
# 函数可以接受任意长的参数列表
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
o 'ParamList OptComma TERMINATOR Param', -> $1.concat $4
o 'ParamList OptComma INDENT ParamList OptComma OUTDENT', -> $1.concat $4
]
# 函数的一个参数可以正常的定义, 或者用 splat 把剩下的参数汇集到一起.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
o '...', -> new Expansion
]
# 函数参数.
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# 在函数参数之外的 splat.
Splat: [
o 'Expression ...', -> new Splat $1
]
# 可以赋值的变量或者属性.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# 所有可以赋值到的东西.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 可以被当作值的类型 -- 可赋值到的量, 函数调用, 数组下标, "类"等等.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# 总合了大部分访问对象内容的手段: 通过属性, 原型, 数组下标或者数组切片.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [LOC(1)(new Access new Literal('prototype')), LOC(2)(new Access $2)]
o '?:: Identifier', -> [LOC(1)(new Access new Literal('prototype'), 'soak'), LOC(2)(new Access $2)]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# 使用方括号语法访问对象或数组内部.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# 在 CoffeeScript 里, 一个对象字面量是简单的由属性赋值列表组成.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# 对象字面量中的属性赋值, 可以像 JavaScript 那样用逗号分隔, 或者直接用换行分隔.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# 类定义包含可选的原型属性赋值, 和可选的到超类的引用.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# 一般函数调用, 或者链式函数调用.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# 可选的函数存在性检查.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# 函数调用的参数列表.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# 对当前对象 *this* 的引用.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# 对 *this* 的属性的引用.
ThisProperty: [
o '@ Identifier', -> new Value LOC(1)(new Literal('this')), [LOC(2)(new Access($2))], 'this'
]
# 数组字面量.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# inclusive 和 exclusive 范围.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# CoffeeScript 范围字面量.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# 数组切片字面量.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
o 'RangeDots', -> new Range null, null, $1
]
# **ArgList** 既可以是传给函数调用的对象列表, 又可以作为数组字面量的内容
# (特别是逗号分隔的表达式). 新行分隔也可以.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# 块或者 Splat 都是合法的参数.
Arg: [
o 'Expression'
o 'Splat'
o '...', -> new Expansion
]
# 简单的, 逗号分隔的, 必须的参数 (没华丽的语法). 为了使这个规则可以在不支持多行的 **Switch** 块中使用, 我们把它和 **ArgList** 分离开来.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# *try/catch/finally* 异常处理块的各变种.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# catch 子句把赋给异常对象一个名字并执行代码块.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
o 'CATCH Object Block', -> [LOC(2)(new Value($2)), $3]
o 'CATCH Block', -> [null, $2]
]
# 抛出一个异常对象.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# 括号表达式. 注意 **Parenthetical** 是个 **Value** 而不是 **Expression**,
# 所以如果你要把表达式放到一个仅接受值的地方, 总用括号包起来就可以了.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# while 循环的条件部分.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# while 循环一般带个待执行的表达式块, 也可以是后缀式地加到一个表达式后. 没有 do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Expression WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(LOC(1) new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(LOC(1) new Literal 'true').addBody LOC(2) Block.wrap [$2]
]
# 数组, 对象和范围 comprehension 的一般写法.
# Comprehension 一般带个代执行的表达式块, 也可以是后缀式地加到一个表达式后.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: (LOC(2) new Value($2))
o 'FOR Range BY Expression', -> source: (LOC(2) new Value($2)), step: $4
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# 循环中的一个变量, 取于数组中满足条件的值. 支持模式匹配.
ForValue: [
o 'Identifier'
o 'ThisProperty'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 一个数组或者范围 comprehension 包含对应当前元素的变量, 和 (可选的) 对当前下标的引用.
# 在对象 comprehension 的情况下, 则是 *key, value*.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# comprehension 的源是个数组或者对象, 带可选的 guard 从句. 如果是数组 comprehension, 你还可以选择固定间隔的步进.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# 单独的 **When** 从句, 带动作.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# 最基本的 *if* 只含条件和动作. 下面把 if 相关的规则拆分开来, 是为了避免二义性.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse LOC(3,5) new If $4, $5, type: $3
]
# 其他 *if* 表达式的形式, 包含后缀式一行流的 *if* 和 *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
]
# 算术和逻辑操作符, 作用于 1 个或者多个操作数(operand).
# 这里把它们按优先级分组. 确切的优先级规则在页低给出.
# 如果我们可以把大部分都归结到一个泛化的 *Operand OpSymbol Operand* 形式的规则, 这个定义就可以短很多.
# 但为了使优先级生效, 就得分别定义了.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o 'UNARY_MATH Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY_MATH'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY_MATH'
o 'YIELD Statement', -> new Op $1 , $2
o 'YIELD Expression', -> new Op $1 , $2
o 'YIELD FROM Expression', -> new Op $1.concat($2) , $3
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [存在性操作符](http://coffee-js.github.io/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression ** Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2[1..], $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable COMPOUND_ASSIGN TERMINATOR
Expression', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# 优先级
# ----------
# 在上面的操作符比下面的操作符优先级更高. 下面的规则使得 `2 + 3 * 4` 解析成:
#
# 2 + (3 * 4)
#
# 而不是:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::', '?::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['right', '**']
['right', 'UNARY_MATH']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', 'YIELD']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['left', 'POST_IF']
]
# 包装
# -----------
# 既然 **语法** 和 **操作符** 都有了, 我们终于可以创建 **Jison.Parser** 了.
# 我们的做法是遍历所有规则, 把全部终结符 (不在上面的规则中的符号) 标记记为 "token".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# 用 **token** 终结符和 **grammar** 规则初始化 **Parser**, 并指定根规则.
# 这里还逆序排列了操作符列表, 因为 Jison 需要从低到高的优先级排列操作符,
# 而我们的定义顺序是从高到低 (和 [Yacc](http://dinosaur.compilertools.net/yacc/index.html) 一样).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
| true | # CoffeeScript 的解析器是从这个语法文件, 用 [Jison](http://github.com/zaach/jison) 生成的.
# Jison 是个自底而上的解析器生成工具, 和 [Bison](http://www.gnu.org/software/bison) 的风格相似, 不过是用 JavaScript 实现的.
# 它可以辨认 [LALR(1), LR(0), SLR(1) 和 LR(1)](http://en.wikipedia.org/wiki/LR_grammar) 语法.
# 为了创建 Jison 解析器, 我们把匹配模式列在左边, 把对应动作列在右边 (通常是创建语法树的节点).
# 执行的时候, 解析器自左往右地, 从流中取出 token, 然后尝试把 token 序列[匹配](http://en.wikipedia.org/wiki/Bottom-up_parsing)
# 到下面写的语法规则中. 如果可以匹配, 会把取出的 token 缩减成 [nonterminal](http://en.wikipedia.org/wiki/Terminal_and_nonterminal_symbols)
# 的符号 (语法规则前边的名字), 然后继续.
#
# 如果你执行命令 `cake build:parser`, Jison 就会按照我们的规则建立语法解析表, 保存到 `lib/parser.js` 中.
# 唯一的依赖: **Jison.Parser**.
{Parser} = require 'jison'
# Jison DSL
# ---------
# Jison 会给我们的解析器多包装一层函数.
# 如果包装函数只是简单的返回一个值, 我们就可以通过移除包装函数, 直接返回里面的内容来做优化.
unwrap = /^function\s*\(\)\s*\{\s*return\s*([\s\S]*);\s*\}/
# 我们方便 Jison 语法生成的 DSL 要感谢 [PI:NAME:<NAME>END_PI](http://github.com/creationix).
# 每条语法规则带有定义模式的字符串, 可选的动作和额外选项.
# 如果没有指定动作, 就简单的返回上一个 nonterminal 的值.
o = (patternString, action, options) ->
patternString = patternString.replace /\s{2,}/g, ' '
patternCount = patternString.split(' ').length
return [patternString, '$$ = $1;', options] unless action
action = if match = unwrap.exec action then match[1] else "(#{action}())"
# 所有需要在 "yy" 上定义的运行时函数
action = action.replace /\bnew /g, '$&yy.'
action = action.replace /\b(?:Block\.wrap|extend)\b/g, 'yy.$&'
# 构造一个函数, 往第一个参数加上位置数据, 然后返回之.
# 如果该参数不是节点, 就不做修改的返回.
addLocationDataFn = (first, last) ->
if not last
"yy.addLocationDataFn(@#{first})"
else
"yy.addLocationDataFn(@#{first}, @#{last})"
action = action.replace /LOC\(([0-9]*)\)/g, addLocationDataFn('$1')
action = action.replace /LOC\(([0-9]*),\s*([0-9]*)\)/g, addLocationDataFn('$1', '$2')
[patternString, "$$ = #{addLocationDataFn(1, patternCount)}(#{action});", options]
# 语法规则
# -----------------
# 下面列出了候选的匹配规则. 你可以看到 nonterminal 的名字是键值.
# 每个匹配的动作中, 以 `$` 打头的变量是 Jison 提供的, 对应数字的位置的值. 在这条规则中:
#
# "Expression UNLESS Expression"
#
# `$1` 的值就是第一个 `Expression`, `$2` 的值就是终结符(terminal) `UNLESS` 对应的 token, `$3` 就是的值就是第二个 `Expression`
grammar =
# **Root** 是语法树最顶层的节点. 由于我们是自低而上解析的, 所有解析都会终结于此.
Root: [
o '', -> new Block
o 'Body'
]
# 由任意语句和表达式组成, 被换行符或者分号分隔
Body: [
o 'Line', -> Block.wrap [$1]
o 'Body TERMINATOR Line', -> $1.push $3
o 'Body TERMINATOR'
]
# 块和语句, 占据 **Body** 中的一行
Line: [
o 'Expression'
o 'Statement'
]
# 不能当作表达式的纯语句
Statement: [
o 'Return'
o 'Comment'
o 'STATEMENT', -> new Literal $1
]
# 我们语言中所有不同类型的表达式. CoffeeScript 的基本组成元素是 **Expression** -- 所有可以成为表达式的东西都融为一个规则.
# 例外的是, **Block** 同时也递归作为其他很多规则的基本构件, 所以没添加到这里.
Expression: [
o 'Value'
o 'Invocation'
o 'Code'
o 'Operation'
o 'Assign'
o 'If'
o 'Try'
o 'While'
o 'For'
o 'Switch'
o 'Class'
o 'Throw'
]
# 由表达式组成, 缩进的块. 注意 [Rewriter](rewriter.html) 会通过调整 token 流的方法, 把一些后缀式的写法转换成块.
Block: [
o 'INDENT OUTDENT', -> new Block
o 'INDENT Body OUTDENT', -> $2
]
# 标识符字面量, 变量名或者属性.
Identifier: [
o 'IDENTIFIER', -> new Literal $1
]
# Alphanumerics 独立于其他 **Literal**, 是因为它们仅用作对象字面量的的键值.
AlphaNumeric: [
o 'NUMBER', -> new Literal $1
o 'String'
]
String: [
o 'STRING', -> new Literal $1
o 'STRING_START Body STRING_END', -> new Parens $2
]
Regex: [
o 'REGEX', -> new Literal $1
o 'REGEX_START Invocation REGEX_END', -> $2
]
# 所有直接量. 基本都可以不处理直接变成 JavaScript.
Literal: [
o 'AlphaNumeric'
o 'JS', -> new Literal $1
o 'Regex'
o 'DEBUGGER', -> new Literal $1
o 'UNDEFINED', -> new Undefined
o 'NULL', -> new Null
o 'BOOL', -> new Bool $1
]
# 变量, 属性或者下标 的赋值
Assign: [
o 'Assignable = Expression', -> new Assign $1, $3
o 'Assignable = TERMINATOR Expression', -> new Assign $1, $4
o 'Assignable = INDENT Expression OUTDENT', -> new Assign $1, $4
]
# 在对象字面量中的赋值. 和一般 **Assign** 规则不同之处是: 这里允许数字或者字符串作为键值.
AssignObj: [
o 'ObjAssignable', -> new Value $1
o 'ObjAssignable : Expression', -> new Assign LOC(1)(new Value($1)), $3, 'object'
o 'ObjAssignable :
INDENT Expression OUTDENT', -> new Assign LOC(1)(new Value($1)), $4, 'object'
o 'Comment'
]
ObjAssignable: [
o 'Identifier'
o 'AlphaNumeric'
o 'ThisProperty'
]
# 函数体中的返回语句.
Return: [
o 'RETURN Expression', -> new Return $2
o 'RETURN', -> new Return
]
# 注释块
Comment: [
o 'HERECOMMENT', -> new Comment $1
]
# **Code** 节点是函数字面量. 缩进的代码块 **Block** 之前带一个函数箭头, 和一个可选的参数列表.
Code: [
o 'PARAM_START ParamList PARAM_END FuncGlyph Block', -> new Code $2, $5, $4
o 'FuncGlyph Block', -> new Code [], $2, $1
]
# CoffeeScript 有两个不同的箭头符号. `->` 是给一般函数用的, 而 `=>` 函数会绑定到当前 *this* 的值.
FuncGlyph: [
o '->', -> 'func'
o '=>', -> 'boundfunc'
]
# 可选的行末逗号
OptComma: [
o ''
o ','
]
# 函数可以接受任意长的参数列表
ParamList: [
o '', -> []
o 'Param', -> [$1]
o 'ParamList , Param', -> $1.concat $3
o 'ParamList OptComma TERMINATOR Param', -> $1.concat $4
o 'ParamList OptComma INDENT ParamList OptComma OUTDENT', -> $1.concat $4
]
# 函数的一个参数可以正常的定义, 或者用 splat 把剩下的参数汇集到一起.
Param: [
o 'ParamVar', -> new Param $1
o 'ParamVar ...', -> new Param $1, null, on
o 'ParamVar = Expression', -> new Param $1, $3
o '...', -> new Expansion
]
# 函数参数.
ParamVar: [
o 'Identifier'
o 'ThisProperty'
o 'Array'
o 'Object'
]
# 在函数参数之外的 splat.
Splat: [
o 'Expression ...', -> new Splat $1
]
# 可以赋值的变量或者属性.
SimpleAssignable: [
o 'Identifier', -> new Value $1
o 'Value Accessor', -> $1.add $2
o 'Invocation Accessor', -> new Value $1, [].concat $2
o 'ThisProperty'
]
# 所有可以赋值到的东西.
Assignable: [
o 'SimpleAssignable'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 可以被当作值的类型 -- 可赋值到的量, 函数调用, 数组下标, "类"等等.
Value: [
o 'Assignable'
o 'Literal', -> new Value $1
o 'Parenthetical', -> new Value $1
o 'Range', -> new Value $1
o 'This'
]
# 总合了大部分访问对象内容的手段: 通过属性, 原型, 数组下标或者数组切片.
Accessor: [
o '. Identifier', -> new Access $2
o '?. Identifier', -> new Access $2, 'soak'
o ':: Identifier', -> [LOC(1)(new Access new Literal('prototype')), LOC(2)(new Access $2)]
o '?:: Identifier', -> [LOC(1)(new Access new Literal('prototype'), 'soak'), LOC(2)(new Access $2)]
o '::', -> new Access new Literal 'prototype'
o 'Index'
]
# 使用方括号语法访问对象或数组内部.
Index: [
o 'INDEX_START IndexValue INDEX_END', -> $2
o 'INDEX_SOAK Index', -> extend $2, soak : yes
]
IndexValue: [
o 'Expression', -> new Index $1
o 'Slice', -> new Slice $1
]
# 在 CoffeeScript 里, 一个对象字面量是简单的由属性赋值列表组成.
Object: [
o '{ AssignList OptComma }', -> new Obj $2, $1.generated
]
# 对象字面量中的属性赋值, 可以像 JavaScript 那样用逗号分隔, 或者直接用换行分隔.
AssignList: [
o '', -> []
o 'AssignObj', -> [$1]
o 'AssignList , AssignObj', -> $1.concat $3
o 'AssignList OptComma TERMINATOR AssignObj', -> $1.concat $4
o 'AssignList OptComma INDENT AssignList OptComma OUTDENT', -> $1.concat $4
]
# 类定义包含可选的原型属性赋值, 和可选的到超类的引用.
Class: [
o 'CLASS', -> new Class
o 'CLASS Block', -> new Class null, null, $2
o 'CLASS EXTENDS Expression', -> new Class null, $3
o 'CLASS EXTENDS Expression Block', -> new Class null, $3, $4
o 'CLASS SimpleAssignable', -> new Class $2
o 'CLASS SimpleAssignable Block', -> new Class $2, null, $3
o 'CLASS SimpleAssignable EXTENDS Expression', -> new Class $2, $4
o 'CLASS SimpleAssignable EXTENDS Expression Block', -> new Class $2, $4, $5
]
# 一般函数调用, 或者链式函数调用.
Invocation: [
o 'Value OptFuncExist Arguments', -> new Call $1, $3, $2
o 'Invocation OptFuncExist Arguments', -> new Call $1, $3, $2
o 'SUPER', -> new Call 'super', [new Splat new Literal 'arguments']
o 'SUPER Arguments', -> new Call 'super', $2
]
# 可选的函数存在性检查.
OptFuncExist: [
o '', -> no
o 'FUNC_EXIST', -> yes
]
# 函数调用的参数列表.
Arguments: [
o 'CALL_START CALL_END', -> []
o 'CALL_START ArgList OptComma CALL_END', -> $2
]
# 对当前对象 *this* 的引用.
This: [
o 'THIS', -> new Value new Literal 'this'
o '@', -> new Value new Literal 'this'
]
# 对 *this* 的属性的引用.
ThisProperty: [
o '@ Identifier', -> new Value LOC(1)(new Literal('this')), [LOC(2)(new Access($2))], 'this'
]
# 数组字面量.
Array: [
o '[ ]', -> new Arr []
o '[ ArgList OptComma ]', -> new Arr $2
]
# inclusive 和 exclusive 范围.
RangeDots: [
o '..', -> 'inclusive'
o '...', -> 'exclusive'
]
# CoffeeScript 范围字面量.
Range: [
o '[ Expression RangeDots Expression ]', -> new Range $2, $4, $3
]
# 数组切片字面量.
Slice: [
o 'Expression RangeDots Expression', -> new Range $1, $3, $2
o 'Expression RangeDots', -> new Range $1, null, $2
o 'RangeDots Expression', -> new Range null, $2, $1
o 'RangeDots', -> new Range null, null, $1
]
# **ArgList** 既可以是传给函数调用的对象列表, 又可以作为数组字面量的内容
# (特别是逗号分隔的表达式). 新行分隔也可以.
ArgList: [
o 'Arg', -> [$1]
o 'ArgList , Arg', -> $1.concat $3
o 'ArgList OptComma TERMINATOR Arg', -> $1.concat $4
o 'INDENT ArgList OptComma OUTDENT', -> $2
o 'ArgList OptComma INDENT ArgList OptComma OUTDENT', -> $1.concat $4
]
# 块或者 Splat 都是合法的参数.
Arg: [
o 'Expression'
o 'Splat'
o '...', -> new Expansion
]
# 简单的, 逗号分隔的, 必须的参数 (没华丽的语法). 为了使这个规则可以在不支持多行的 **Switch** 块中使用, 我们把它和 **ArgList** 分离开来.
SimpleArgs: [
o 'Expression'
o 'SimpleArgs , Expression', -> [].concat $1, $3
]
# *try/catch/finally* 异常处理块的各变种.
Try: [
o 'TRY Block', -> new Try $2
o 'TRY Block Catch', -> new Try $2, $3[0], $3[1]
o 'TRY Block FINALLY Block', -> new Try $2, null, null, $4
o 'TRY Block Catch FINALLY Block', -> new Try $2, $3[0], $3[1], $5
]
# catch 子句把赋给异常对象一个名字并执行代码块.
Catch: [
o 'CATCH Identifier Block', -> [$2, $3]
o 'CATCH Object Block', -> [LOC(2)(new Value($2)), $3]
o 'CATCH Block', -> [null, $2]
]
# 抛出一个异常对象.
Throw: [
o 'THROW Expression', -> new Throw $2
]
# 括号表达式. 注意 **Parenthetical** 是个 **Value** 而不是 **Expression**,
# 所以如果你要把表达式放到一个仅接受值的地方, 总用括号包起来就可以了.
Parenthetical: [
o '( Body )', -> new Parens $2
o '( INDENT Body OUTDENT )', -> new Parens $3
]
# while 循环的条件部分.
WhileSource: [
o 'WHILE Expression', -> new While $2
o 'WHILE Expression WHEN Expression', -> new While $2, guard: $4
o 'UNTIL Expression', -> new While $2, invert: true
o 'UNTIL Expression WHEN Expression', -> new While $2, invert: true, guard: $4
]
# while 循环一般带个待执行的表达式块, 也可以是后缀式地加到一个表达式后. 没有 do..while.
While: [
o 'WhileSource Block', -> $1.addBody $2
o 'Statement WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Expression WhileSource', -> $2.addBody LOC(1) Block.wrap([$1])
o 'Loop', -> $1
]
Loop: [
o 'LOOP Block', -> new While(LOC(1) new Literal 'true').addBody $2
o 'LOOP Expression', -> new While(LOC(1) new Literal 'true').addBody LOC(2) Block.wrap [$2]
]
# 数组, 对象和范围 comprehension 的一般写法.
# Comprehension 一般带个代执行的表达式块, 也可以是后缀式地加到一个表达式后.
For: [
o 'Statement ForBody', -> new For $1, $2
o 'Expression ForBody', -> new For $1, $2
o 'ForBody Block', -> new For $2, $1
]
ForBody: [
o 'FOR Range', -> source: (LOC(2) new Value($2))
o 'FOR Range BY Expression', -> source: (LOC(2) new Value($2)), step: $4
o 'ForStart ForSource', -> $2.own = $1.own; $2.name = $1[0]; $2.index = $1[1]; $2
]
ForStart: [
o 'FOR ForVariables', -> $2
o 'FOR OWN ForVariables', -> $3.own = yes; $3
]
# 循环中的一个变量, 取于数组中满足条件的值. 支持模式匹配.
ForValue: [
o 'Identifier'
o 'ThisProperty'
o 'Array', -> new Value $1
o 'Object', -> new Value $1
]
# 一个数组或者范围 comprehension 包含对应当前元素的变量, 和 (可选的) 对当前下标的引用.
# 在对象 comprehension 的情况下, 则是 *key, value*.
ForVariables: [
o 'ForValue', -> [$1]
o 'ForValue , ForValue', -> [$1, $3]
]
# comprehension 的源是个数组或者对象, 带可选的 guard 从句. 如果是数组 comprehension, 你还可以选择固定间隔的步进.
ForSource: [
o 'FORIN Expression', -> source: $2
o 'FOROF Expression', -> source: $2, object: yes
o 'FORIN Expression WHEN Expression', -> source: $2, guard: $4
o 'FOROF Expression WHEN Expression', -> source: $2, guard: $4, object: yes
o 'FORIN Expression BY Expression', -> source: $2, step: $4
o 'FORIN Expression WHEN Expression BY Expression', -> source: $2, guard: $4, step: $6
o 'FORIN Expression BY Expression WHEN Expression', -> source: $2, step: $4, guard: $6
]
Switch: [
o 'SWITCH Expression INDENT Whens OUTDENT', -> new Switch $2, $4
o 'SWITCH Expression INDENT Whens ELSE Block OUTDENT', -> new Switch $2, $4, $6
o 'SWITCH INDENT Whens OUTDENT', -> new Switch null, $3
o 'SWITCH INDENT Whens ELSE Block OUTDENT', -> new Switch null, $3, $5
]
Whens: [
o 'When'
o 'Whens When', -> $1.concat $2
]
# 单独的 **When** 从句, 带动作.
When: [
o 'LEADING_WHEN SimpleArgs Block', -> [[$2, $3]]
o 'LEADING_WHEN SimpleArgs Block TERMINATOR', -> [[$2, $3]]
]
# 最基本的 *if* 只含条件和动作. 下面把 if 相关的规则拆分开来, 是为了避免二义性.
IfBlock: [
o 'IF Expression Block', -> new If $2, $3, type: $1
o 'IfBlock ELSE IF Expression Block', -> $1.addElse LOC(3,5) new If $4, $5, type: $3
]
# 其他 *if* 表达式的形式, 包含后缀式一行流的 *if* 和 *unless*.
If: [
o 'IfBlock'
o 'IfBlock ELSE Block', -> $1.addElse $3
o 'Statement POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
o 'Expression POST_IF Expression', -> new If $3, LOC(1)(Block.wrap [$1]), type: $2, statement: true
]
# 算术和逻辑操作符, 作用于 1 个或者多个操作数(operand).
# 这里把它们按优先级分组. 确切的优先级规则在页低给出.
# 如果我们可以把大部分都归结到一个泛化的 *Operand OpSymbol Operand* 形式的规则, 这个定义就可以短很多.
# 但为了使优先级生效, 就得分别定义了.
Operation: [
o 'UNARY Expression', -> new Op $1 , $2
o 'UNARY_MATH Expression', -> new Op $1 , $2
o '- Expression', (-> new Op '-', $2), prec: 'UNARY_MATH'
o '+ Expression', (-> new Op '+', $2), prec: 'UNARY_MATH'
o 'YIELD Statement', -> new Op $1 , $2
o 'YIELD Expression', -> new Op $1 , $2
o 'YIELD FROM Expression', -> new Op $1.concat($2) , $3
o '-- SimpleAssignable', -> new Op '--', $2
o '++ SimpleAssignable', -> new Op '++', $2
o 'SimpleAssignable --', -> new Op '--', $1, null, true
o 'SimpleAssignable ++', -> new Op '++', $1, null, true
# [存在性操作符](http://coffee-js.github.io/coffee-script/#existence).
o 'Expression ?', -> new Existence $1
o 'Expression + Expression', -> new Op '+' , $1, $3
o 'Expression - Expression', -> new Op '-' , $1, $3
o 'Expression MATH Expression', -> new Op $2, $1, $3
o 'Expression ** Expression', -> new Op $2, $1, $3
o 'Expression SHIFT Expression', -> new Op $2, $1, $3
o 'Expression COMPARE Expression', -> new Op $2, $1, $3
o 'Expression LOGIC Expression', -> new Op $2, $1, $3
o 'Expression RELATION Expression', ->
if $2.charAt(0) is '!'
new Op($2[1..], $1, $3).invert()
else
new Op $2, $1, $3
o 'SimpleAssignable COMPOUND_ASSIGN
Expression', -> new Assign $1, $3, $2
o 'SimpleAssignable COMPOUND_ASSIGN
INDENT Expression OUTDENT', -> new Assign $1, $4, $2
o 'SimpleAssignable COMPOUND_ASSIGN TERMINATOR
Expression', -> new Assign $1, $4, $2
o 'SimpleAssignable EXTENDS Expression', -> new Extends $1, $3
]
# 优先级
# ----------
# 在上面的操作符比下面的操作符优先级更高. 下面的规则使得 `2 + 3 * 4` 解析成:
#
# 2 + (3 * 4)
#
# 而不是:
#
# (2 + 3) * 4
operators = [
['left', '.', '?.', '::', '?::']
['left', 'CALL_START', 'CALL_END']
['nonassoc', '++', '--']
['left', '?']
['right', 'UNARY']
['right', '**']
['right', 'UNARY_MATH']
['left', 'MATH']
['left', '+', '-']
['left', 'SHIFT']
['left', 'RELATION']
['left', 'COMPARE']
['left', 'LOGIC']
['nonassoc', 'INDENT', 'OUTDENT']
['right', 'YIELD']
['right', '=', ':', 'COMPOUND_ASSIGN', 'RETURN', 'THROW', 'EXTENDS']
['right', 'FORIN', 'FOROF', 'BY', 'WHEN']
['right', 'IF', 'ELSE', 'FOR', 'WHILE', 'UNTIL', 'LOOP', 'SUPER', 'CLASS']
['left', 'POST_IF']
]
# 包装
# -----------
# 既然 **语法** 和 **操作符** 都有了, 我们终于可以创建 **Jison.Parser** 了.
# 我们的做法是遍历所有规则, 把全部终结符 (不在上面的规则中的符号) 标记记为 "token".
tokens = []
for name, alternatives of grammar
grammar[name] = for alt in alternatives
for token in alt[0].split ' '
tokens.push token unless grammar[token]
alt[1] = "return #{alt[1]}" if name is 'Root'
alt
# 用 **token** 终结符和 **grammar** 规则初始化 **Parser**, 并指定根规则.
# 这里还逆序排列了操作符列表, 因为 Jison 需要从低到高的优先级排列操作符,
# 而我们的定义顺序是从高到低 (和 [Yacc](http://dinosaur.compilertools.net/yacc/index.html) 一样).
exports.parser = new Parser
tokens : tokens.join ' '
bnf : grammar
operators : operators.reverse()
startSymbol : 'Root'
|
[
{
"context": "ONENTS.LFO] = 'LFO'\n\n @COLORS: []\n @COLORS[@COMPONENTS.NSG] = 0x00D8C7\n @COLORS[@COMPONENTS.OSC] = 0x4A0",
"end": 1653,
"score": 0.5575951933860779,
"start": 1640,
"tag": "EMAIL",
"value": "COMPONENTS.NS"
}
] | source/app/coffee/AppData.coffee | andrevenancio/mod-synth.io | 30 | class AppData
# cookies
@SHOW_TOUR: undefined
@SHOW_KEYBOARD_PANNEL: undefined
@SHOW_MENU_PANNEL: undefined
@SHOW_LABELS: undefined
# TOUR_MODE (necessary to avoid defaulting to Default patch in PatchesPannel)
@TOUR_MODE: false
# pixi
@PIXI:
renderer: null
stage: null
# preloaded assets
@ASSETS: null
# device pixel ratio
@RATIO: if window.devicePixelRatio >= 2 then 2 else 1
# canvas dimentions
@WIDTH: 320 * @RATIO
@HEIGHT: 240 * @RATIO
# icon sizes
@ICON_SIZE_1 = 48 * @RATIO
@ICON_SIZE_2 = 32 * @RATIO
@ICON_SIZE_3 = 72 * @RATIO
@ICON_SPACE1 = 15 * @RATIO
@ICON_SPACE2 = 50 * @RATIO
@ICON_SPACE3 = 40 * @RATIO
# padding
@PADDING: 26 * @RATIO
# minimap itens
@MINIMAP: 4 * @RATIO
# pannel sizes
@SETTINGS_PANNEL_HEIGHT: 100 * @RATIO
@KEYBOARD_PANNEL_HEIGHT: 326 * @RATIO
@MENU_PANNEL: @ICON_SIZE_1 + @PADDING*2
@MENU_PANNEL_BORDER: 4 * @RATIO
@SUBMENU_PANNEL: 300 * @RATIO
@KEYPRESS_ALLOWED: true
# background color
@BG: 0x191919
# line color
@LINE_COLOR: 0xffffff
@LINE_ALPHA: 0.3
@COMPONENTS:
NSG: 0 # noise generator
OSC: 1 # oscillator
ENV: 2 # ADSR envelope
FLT: 3 # filter
PTG: 4 # pattern gate
LFO: 5 # low frequency oscillator
@TITLE: []
@TITLE[@COMPONENTS.NSG] = 'NSG'
@TITLE[@COMPONENTS.OSC] = 'OSC'
@TITLE[@COMPONENTS.ENV] = 'ENV'
@TITLE[@COMPONENTS.FLT] = 'FLT'
@TITLE[@COMPONENTS.PTG] = 'PTG'
@TITLE[@COMPONENTS.LFO] = 'LFO'
@COLORS: []
@COLORS[@COMPONENTS.NSG] = 0x00D8C7
@COLORS[@COMPONENTS.OSC] = 0x4A00FF
@COLORS[@COMPONENTS.ENV] = 0xD43557
@COLORS[@COMPONENTS.FLT] = 0x0BD7E3
@COLORS[@COMPONENTS.PTG] = 0x26E2A7
@COLORS[@COMPONENTS.LFO] = 0xF21141
@WAVE_TYPE:
SINE: 0
TRIANGLE: 1
SQUARE: 2
SAWTOOTH: 3
@NOISE_TYPE:
WHITE: 0
PINK: 1
BROWN: 2
@OCTAVE_TYPE:
THIRTY_TWO: 0
SIXTEEN: 1
EIGHT: 2
FOUR: 3
@FILTER_TYPE:
LOWPASS: 0
HIGHPASS: 1
BANDPASS: 2
LOWSHELF: 3
HIGHSHELF: 4
PEAKING: 5
NOTCH: 6
ALLPASS: 7
@TEXTFORMAT:
TEST_FONT_1:
font: '20px sofia_prolight',
fill: 'white'
align: 'left'
TEST_FONT_2:
font: '20px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
HINT:
font: ( 20 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SMALL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'center'
# 2X
PANNEL_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SUBTITLE:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_DESCRIPTION:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
wordWrap: true
wordWrapWidth: @SUBMENU_PANNEL + @MENU_PANNEL + @PADDING
# 2X
SETTINGS_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_SMB:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_LABEL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_PAD:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER:
font: ( 64 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER_POSTSCRIPT:
font: ( 24 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
PICKER:
font: ( 44 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SOON:
font: ( 30 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
| 198721 | class AppData
# cookies
@SHOW_TOUR: undefined
@SHOW_KEYBOARD_PANNEL: undefined
@SHOW_MENU_PANNEL: undefined
@SHOW_LABELS: undefined
# TOUR_MODE (necessary to avoid defaulting to Default patch in PatchesPannel)
@TOUR_MODE: false
# pixi
@PIXI:
renderer: null
stage: null
# preloaded assets
@ASSETS: null
# device pixel ratio
@RATIO: if window.devicePixelRatio >= 2 then 2 else 1
# canvas dimentions
@WIDTH: 320 * @RATIO
@HEIGHT: 240 * @RATIO
# icon sizes
@ICON_SIZE_1 = 48 * @RATIO
@ICON_SIZE_2 = 32 * @RATIO
@ICON_SIZE_3 = 72 * @RATIO
@ICON_SPACE1 = 15 * @RATIO
@ICON_SPACE2 = 50 * @RATIO
@ICON_SPACE3 = 40 * @RATIO
# padding
@PADDING: 26 * @RATIO
# minimap itens
@MINIMAP: 4 * @RATIO
# pannel sizes
@SETTINGS_PANNEL_HEIGHT: 100 * @RATIO
@KEYBOARD_PANNEL_HEIGHT: 326 * @RATIO
@MENU_PANNEL: @ICON_SIZE_1 + @PADDING*2
@MENU_PANNEL_BORDER: 4 * @RATIO
@SUBMENU_PANNEL: 300 * @RATIO
@KEYPRESS_ALLOWED: true
# background color
@BG: 0x191919
# line color
@LINE_COLOR: 0xffffff
@LINE_ALPHA: 0.3
@COMPONENTS:
NSG: 0 # noise generator
OSC: 1 # oscillator
ENV: 2 # ADSR envelope
FLT: 3 # filter
PTG: 4 # pattern gate
LFO: 5 # low frequency oscillator
@TITLE: []
@TITLE[@COMPONENTS.NSG] = 'NSG'
@TITLE[@COMPONENTS.OSC] = 'OSC'
@TITLE[@COMPONENTS.ENV] = 'ENV'
@TITLE[@COMPONENTS.FLT] = 'FLT'
@TITLE[@COMPONENTS.PTG] = 'PTG'
@TITLE[@COMPONENTS.LFO] = 'LFO'
@COLORS: []
@COLORS[@<EMAIL>G] = 0x00D8C7
@COLORS[@COMPONENTS.OSC] = 0x4A00FF
@COLORS[@COMPONENTS.ENV] = 0xD43557
@COLORS[@COMPONENTS.FLT] = 0x0BD7E3
@COLORS[@COMPONENTS.PTG] = 0x26E2A7
@COLORS[@COMPONENTS.LFO] = 0xF21141
@WAVE_TYPE:
SINE: 0
TRIANGLE: 1
SQUARE: 2
SAWTOOTH: 3
@NOISE_TYPE:
WHITE: 0
PINK: 1
BROWN: 2
@OCTAVE_TYPE:
THIRTY_TWO: 0
SIXTEEN: 1
EIGHT: 2
FOUR: 3
@FILTER_TYPE:
LOWPASS: 0
HIGHPASS: 1
BANDPASS: 2
LOWSHELF: 3
HIGHSHELF: 4
PEAKING: 5
NOTCH: 6
ALLPASS: 7
@TEXTFORMAT:
TEST_FONT_1:
font: '20px sofia_prolight',
fill: 'white'
align: 'left'
TEST_FONT_2:
font: '20px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
HINT:
font: ( 20 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SMALL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'center'
# 2X
PANNEL_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SUBTITLE:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_DESCRIPTION:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
wordWrap: true
wordWrapWidth: @SUBMENU_PANNEL + @MENU_PANNEL + @PADDING
# 2X
SETTINGS_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_SMB:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_LABEL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_PAD:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER:
font: ( 64 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER_POSTSCRIPT:
font: ( 24 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
PICKER:
font: ( 44 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SOON:
font: ( 30 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
| true | class AppData
# cookies
@SHOW_TOUR: undefined
@SHOW_KEYBOARD_PANNEL: undefined
@SHOW_MENU_PANNEL: undefined
@SHOW_LABELS: undefined
# TOUR_MODE (necessary to avoid defaulting to Default patch in PatchesPannel)
@TOUR_MODE: false
# pixi
@PIXI:
renderer: null
stage: null
# preloaded assets
@ASSETS: null
# device pixel ratio
@RATIO: if window.devicePixelRatio >= 2 then 2 else 1
# canvas dimentions
@WIDTH: 320 * @RATIO
@HEIGHT: 240 * @RATIO
# icon sizes
@ICON_SIZE_1 = 48 * @RATIO
@ICON_SIZE_2 = 32 * @RATIO
@ICON_SIZE_3 = 72 * @RATIO
@ICON_SPACE1 = 15 * @RATIO
@ICON_SPACE2 = 50 * @RATIO
@ICON_SPACE3 = 40 * @RATIO
# padding
@PADDING: 26 * @RATIO
# minimap itens
@MINIMAP: 4 * @RATIO
# pannel sizes
@SETTINGS_PANNEL_HEIGHT: 100 * @RATIO
@KEYBOARD_PANNEL_HEIGHT: 326 * @RATIO
@MENU_PANNEL: @ICON_SIZE_1 + @PADDING*2
@MENU_PANNEL_BORDER: 4 * @RATIO
@SUBMENU_PANNEL: 300 * @RATIO
@KEYPRESS_ALLOWED: true
# background color
@BG: 0x191919
# line color
@LINE_COLOR: 0xffffff
@LINE_ALPHA: 0.3
@COMPONENTS:
NSG: 0 # noise generator
OSC: 1 # oscillator
ENV: 2 # ADSR envelope
FLT: 3 # filter
PTG: 4 # pattern gate
LFO: 5 # low frequency oscillator
@TITLE: []
@TITLE[@COMPONENTS.NSG] = 'NSG'
@TITLE[@COMPONENTS.OSC] = 'OSC'
@TITLE[@COMPONENTS.ENV] = 'ENV'
@TITLE[@COMPONENTS.FLT] = 'FLT'
@TITLE[@COMPONENTS.PTG] = 'PTG'
@TITLE[@COMPONENTS.LFO] = 'LFO'
@COLORS: []
@COLORS[@PI:EMAIL:<EMAIL>END_PIG] = 0x00D8C7
@COLORS[@COMPONENTS.OSC] = 0x4A00FF
@COLORS[@COMPONENTS.ENV] = 0xD43557
@COLORS[@COMPONENTS.FLT] = 0x0BD7E3
@COLORS[@COMPONENTS.PTG] = 0x26E2A7
@COLORS[@COMPONENTS.LFO] = 0xF21141
@WAVE_TYPE:
SINE: 0
TRIANGLE: 1
SQUARE: 2
SAWTOOTH: 3
@NOISE_TYPE:
WHITE: 0
PINK: 1
BROWN: 2
@OCTAVE_TYPE:
THIRTY_TWO: 0
SIXTEEN: 1
EIGHT: 2
FOUR: 3
@FILTER_TYPE:
LOWPASS: 0
HIGHPASS: 1
BANDPASS: 2
LOWSHELF: 3
HIGHSHELF: 4
PEAKING: 5
NOTCH: 6
ALLPASS: 7
@TEXTFORMAT:
TEST_FONT_1:
font: '20px sofia_prolight',
fill: 'white'
align: 'left'
TEST_FONT_2:
font: '20px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
HINT:
font: ( 20 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SMALL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'center'
# 2X
PANNEL_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_SUBTITLE:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
MENU_DESCRIPTION:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
wordWrap: true
wordWrapWidth: @SUBMENU_PANNEL + @MENU_PANNEL + @PADDING
# 2X
SETTINGS_TITLE:
font: ( 40 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_SMB:
font: ( 32 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_LABEL:
font: ( 24 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_PAD:
font: ( 28 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER:
font: ( 64 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SETTINGS_NUMBER_POSTSCRIPT:
font: ( 24 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
PICKER:
font: ( 44 * @RATIO ) + 'px letter_gothic_fsregular',
fill: 'white'
align: 'left'
# 2X
SOON:
font: ( 30 * @RATIO ) + 'px sofia_prolight',
fill: 'white'
align: 'left'
|
[
{
"context": "s!\n# Entry for the GitHub Game Off 2013\n# Author : Paul Joannon for H-Bomb\n# <paul.joannon@gmail.com>\n##\n#####\n\nS",
"end": 85,
"score": 0.9998471140861511,
"start": 73,
"tag": "NAME",
"value": "Paul Joannon"
},
{
"context": "me Off 2013\n# Author : Paul Joannon f... | assets/js/coffee/maingame.coffee | MySweetWhomp/demcreepers | 1 | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : Paul Joannon for H-Bomb
# <paul.joannon@gmail.com>
##
#####
Score = 0
KillCount = 0
Waves = 1
Packs =
Count : 2
Value : 15
Bonus = [100, 500]
class Wave
constructor : ->
@HIT = new jaws.Audio audio : 'audio/HIT.ogg', volume : window.DemCreepers.Volumes.FX
@_mobs = []
@_pack = 0
update : (player, map) =>
toDel = []
_.map @_mobs, (mob, index) =>
del = no
_.map player._axes, (axe) =>
if ((do axe._box.rect).collideRect (do mob._box.rect)) and axe._toGo >= 0
axe._toGo = -1
if --mob.pv <= 0
#do mob._DEATH.play
toDel.push index
del = yes
map.add mob
Score += mob.reward * player.Mult
if ++player.Chain is 10
player.Chain = 0
++player.Mult
KillCount += 1
do @HIT.play
if not del
mob.update player, map._map
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_mobs.splice index, 1
getToDraw : (viewport) => _.filter @_mobs, (mob) -> viewport.isPartlyInside mob._sprite
nextPack : =>
class Wave1 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Gob x, y
_.map [1..8], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class Wave2 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Golem x, y
_.map [1..6], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class RandWave extends Wave
constructor : (@nbPacks, @packsValue) ->
super 0
do @regen
genPack : =>
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
n = @packsValue
while n > 0
if n >= 10
rand = _.random 0, 1
if rand
@_mobs.push new window.DemCreepers.Golem x, y
else
_.map [0..9], () =>
@_mobs.push new window.DemCreepers.Gob x, y
n -= 10
else
@_mobs.push new window.DemCreepers.Gob x, y
n -= 1
regen : =>
@_mobs = []
max = Math.round (@nbPacks / 2)
n = _.random 1, max
while n > @nbPacks - @_pack
n = _.random 1, max
_.map [1..n], =>
do @genPack
++@_pack
return
nextPack : =>
if @_pack >= @nbPacks
return no
else
do @regen
return yes
class HUD
constructor : ->
@_letters =new jaws.SpriteSheet
image : 'img/HUD-NUMBERSLETTERS.gif'
frame_size : [15, 15]
orientation : 'right'
@_bg = new jaws.Sprite
image : 'img/HUD.gif'
width: 400
height: 20
scale : 2
x : 0
y : 0
do @createMessages
@_msg = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 300
scale : 2
@_msg2 = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 340
scale : 2
@_end = [no, no]
###
# HP
###
@_hp = new jaws.SpriteList
_.map [0..2], (i) =>
@_hp.push new jaws.Sprite
image : @_letters.frames[0]
x : 85 - i * 17
y : 5
scale : 2
###
# Waves
###
@_waves = new jaws.SpriteList
_.map [0..2], (i) =>
@_waves.push new jaws.Sprite
image : @_letters.frames[0]
x : 250 - i * 17
y : 5
scale : 2
###
# Kills
###
@_kills = new jaws.SpriteList
_.map [0..3], (i) =>
@_kills.push new jaws.Sprite
image : @_letters.frames[0]
x : 410 - i * 17
y : 5
scale : 2
###
# Score
###
@_score = new jaws.SpriteList
_.map [0..10], (i) =>
@_score.push new jaws.Sprite
image : @_letters.frames[0]
x : 750 - i * 17
y : 5
scale : 2
###
# Wave Bonus
###
@_wavebonus = new jaws.SpriteList
createMessages : =>
@_messages =new jaws.Animation
sprite_sheet : 'img/HUD-ANIMATED.gif'
frame_size : [300, 20]
frame_duration : 70
loop : no
anchor : 'center'
subsets :
'wave' : [0, 6]
'perfect' : [6, 13]
on_end : =>
setTimeout (=>
@_end = [no, no]
do @createMessages
), 2000
update : (player) =>
_.map [0..2], (i) =>
(@_hp.at i).setImage @_letters.frames[0]
_.map do ((String player._hp).split '').reverse, (n, i) =>
(@_hp.at i).setImage @_letters.frames[n]
_.map do ((String Waves).split '').reverse, (n, i) =>
(@_waves.at i).setImage @_letters.frames[n]
_.map do ((String Score).split '').reverse, (n, i) =>
(@_score.at i).setImage @_letters.frames[n]
_.map do ((String KillCount).split '').reverse, (n, i) =>
(@_kills.at i).setImage @_letters.frames[n]
if @_end[0]
if @_wavebonus.length is 0
bonus = Bonus[0] - 100
if @_end[1]
bonus += 500 + 500 * (player.PerfectChain - 1)
bonus = (String bonus) + 'pts'
baseX = 400 - (Math.floor (bonus.length / 2)) * 30
if not (bonus.length % 2)
baseX += 15
_.map (bonus.split ''), (n, i) =>
@_wavebonus.push new jaws.Sprite
image : @_letters.frames[window.DemCreepers.Utils.getTileId n]
x : baseX + i * 30
y : 400
scale : 3
anchor : 'center'
@_msg.setImage do @_messages.subsets['wave'].next
@_msg2.setImage do @_messages.subsets['perfect'].next
else if @_wavebonus.length > 0
@_wavebonus.removeIf () => true
draw : =>
do @_bg.draw
do @_hp.draw
do @_waves.draw
do @_score.draw
do @_kills.draw
if @_end[0]
do @_wavebonus.draw
do @_msg.draw
if @_end[1]
do @_msg2.draw
class MainGame
constructor : ->
@_paused = no
@_texts = new jaws.SpriteSheet
image : 'img/HUD---TEXT.gif'
frame_size : [80, 20]
@_quadtree = new jaws.QuadTree
@_update = @titleUpdate
@_draw = @titleDraw
@_title = new jaws.Sprite
image : 'img/HUD---PICTURES---V1.gif'
scale : 2
x : 0
y : 0
@START = new jaws.Audio audio : 'audio/START.ogg', volume : window.DemCreepers.Volumes.FX
@MENU = new jaws.Audio
audio : 'audio/MENU.ogg'
volume : window.DemCreepers.Volumes.Music
loop : yes
setup : =>
do @MENU.play
[rows, cols] = [9, 12]
@_viewport = new jaws.Viewport
x : 0
y : 20
max_x : cols * (window.DemCreepers.Config.TileSize[0] * 2)
max_y : rows * (window.DemCreepers.Config.TileSize[1] * 2)
@_hud = new HUD
@_map = new window.DemCreepers.Map rows, cols
@_player = new window.DemCreepers.Player 600, 450
@_pauseOverlay = new jaws.Sprite
x : 0
y : 0
width : 800
height : 600
color : 'rgba(0,0,0,.5)'
@_pauseText = new jaws.Sprite
image : @_texts.frames[0]
anchor : 'center'
x : 400
y : 300
scale : 2
@_gameOverText = new jaws.Sprite
image : @_texts.frames[2]
anchor : 'center'
x : 400
y : 200
scale : 2
setupEnd : =>
do @updateScores
@Valid = no
@Name = [ 'A' , 'A' , 'A' ]
@Pos = 0
@_Name = new jaws.SpriteList
@_Cursor = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 1]
scale : 2
_.map [0..2], (i) =>
@_Name.push new jaws.Sprite
image : @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
x : (400 - 30) + (i * 20)
y : 300
scale : 2
anchor : 'center'
@_Enter = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 2]
x : (400 - 30) + (3 * 22)
y : 300
scale : 2
nextWave : =>
do @_map.updateForNextWave
if Waves < 2
@_wave = new Wave1
else if Waves < 3
@_wave = new Wave2
else
if not (Waves % 4)
rand = _.random 1, 2
if rand is 1
++Packs.Count
else
Packs.Value += 5
@_wave = new RandWave Packs.Count, Packs.Value
++Waves
Score += Bonus[0]
Bonus[0] += 100
@_hud._end[0] = yes
if not @_player._hit
Score += 500 + 500 * @_player.PerfectChain++
@_hud._end[1] = yes
@_player._hit = no
gameupdate : =>
if (@_overlayText isnt 'gameOverText') and jaws.pressedWithoutRepeat 'space'
@_paused = not @_paused
if @_paused then do @_music.pause else do @_music.play
if not @_paused
if @_wave._mobs.length is 0
@_quadtree = new jaws.QuadTree
if not (do @_wave.nextPack)
do @nextWave
all = _.union (_.map @_wave._mobs, (item) -> item._box), [@_player._box]
all = _.filter all, (x) => @_viewport.isPartlyInside x
try
if all.length > 1
@_quadtree.collide all, all, (a, b) =>
a.coll = b
b.coll = a
### Player ###
if not (@_player.update @_viewport, @_map._map)
@_paused = yes
@_overlayText = 'gameOverText'
do @_music.stop
do @setupEnd
@_update = @endupdate
@_draw = @enddraw
### Monsters ###
@_wave.update @_player, @_map
### Center viewport on Player ###
@_viewport.centerAround @_player._box
### HUD ###
@_hud.update @_player
do @_quadtree.clear
gamedraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
### HUD ###
do @_hud.draw
###
# PAUSE
###
if @_paused
do @_pauseOverlay.draw
do @_pauseText.draw
###
(document.getElementById 'playerX').innerHTML = @_player.x
(document.getElementById 'playerY').innerHTML = @_player.y
(document.getElementById 'viewportX').innerHTML = @_viewport.x
(document.getElementById 'viewportY').innerHTML = @_viewport.y
###
titleUpdate : =>
do @_player.simpleUpdate
### Center viewport on Player ###
@_viewport.centerAround @_player._box
if jaws.pressedWithoutRepeat 'enter'
do @MENU.stop
do @START.play
setTimeout (=>
@_music = new jaws.Audio {
audio : 'audio/GAME_LOOP.ogg'
volume : window.DemCreepers.Volumes.Music
loop : 1
}
do @_music.play
@_update = @gameupdate
@_draw = @gamedraw
@_wave = new Wave1
), 500
titleDraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_title.draw
updateScores : =>
Req = new XMLHttpRequest
Req.onload = =>
@Scores = JSON.parse Req.response
@_Names = []
@_Scores = []
i = 0
x = 50
y = 400
_.map @Scores, (score) =>
@_Names.push new jaws.SpriteList
@_Scores.push new jaws.SpriteList
_.map score.name, (letter, j) =>
@_Names[i].push new jaws.Sprite
anchor : 'center'
x : x + j * 20
y : y
scale : 2
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId letter)]
@_score = new jaws.SpriteList
_.map [0..10], (j) =>
@_Scores[i].push new jaws.Sprite
image : @_hud._letters.frames[0]
x : x + 80 + (10 * 20) - (j * 20)
y : y
scale : 2
anchor : 'center'
_.map do ((String score.value).split '').reverse, (n, j) =>
(@_Scores[i].at j).setImage @_hud._letters.frames[n]
y += 40
if ++i is 5
x += 400
y = 400
Req.open 'get', '/scores', yes
do Req.send
endupdate : =>
if not @Valid
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
@_Cursor.moveTo (400 - 30) + (@Pos * 20), 320
if @Pos < 3
if jaws.pressedWithoutRepeat "#{controls.down}"
if @Name[@Pos] is 'A'
@Name[@Pos] = '9'
else if @Name[@Pos] is '0'
@Name[@Pos] = 'Z'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) - 1
else if jaws.pressedWithoutRepeat "#{controls.up}"
if @Name[@Pos] is 'Z'
@Name[@Pos] = '0'
else if @Name[@Pos] is '9'
@Name[@Pos] = 'A'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) + 1
if jaws.pressedWithoutRepeat "#{controls.left}"
--@Pos if @Pos > 0
else if jaws.pressedWithoutRepeat "#{controls.right}"
++@Pos if @Pos < 3
else if jaws.pressedWithoutRepeat 'enter'
if @Pos < 3
++@Pos
else
@Valid = yes
Req = new XMLHttpRequest
Req.onload = =>
do @updateScores
Req.open 'post', '/score', yes
params = "name=#{@Name.join ''}&score=#{Score}"
Req.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
Req.setRequestHeader "Content-length", params.length
Req.setRequestHeader "Connection", "close"
Req.send params
_.map [0..2], (i) =>
(@_Name.at i).setImage @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
enddraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_hud.draw
do @_pauseOverlay.draw
do @_gameOverText.draw
_.map @_Names, (name) -> do name.draw
_.map @_Scores, (score) -> do score.draw
if not @Valid
do @_Name.draw
do @_Enter.draw
do @_Cursor.draw
update : =>
do @_update
draw : =>
do @_draw
if window.DemCreepers?
window.DemCreepers.MainGame = MainGame | 102414 | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : <NAME> for H-Bomb
# <<EMAIL>>
##
#####
Score = 0
KillCount = 0
Waves = 1
Packs =
Count : 2
Value : 15
Bonus = [100, 500]
class Wave
constructor : ->
@HIT = new jaws.Audio audio : 'audio/HIT.ogg', volume : window.DemCreepers.Volumes.FX
@_mobs = []
@_pack = 0
update : (player, map) =>
toDel = []
_.map @_mobs, (mob, index) =>
del = no
_.map player._axes, (axe) =>
if ((do axe._box.rect).collideRect (do mob._box.rect)) and axe._toGo >= 0
axe._toGo = -1
if --mob.pv <= 0
#do mob._DEATH.play
toDel.push index
del = yes
map.add mob
Score += mob.reward * player.Mult
if ++player.Chain is 10
player.Chain = 0
++player.Mult
KillCount += 1
do @HIT.play
if not del
mob.update player, map._map
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_mobs.splice index, 1
getToDraw : (viewport) => _.filter @_mobs, (mob) -> viewport.isPartlyInside mob._sprite
nextPack : =>
class Wave1 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Gob x, y
_.map [1..8], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class Wave2 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Golem x, y
_.map [1..6], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class RandWave extends Wave
constructor : (@nbPacks, @packsValue) ->
super 0
do @regen
genPack : =>
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
n = @packsValue
while n > 0
if n >= 10
rand = _.random 0, 1
if rand
@_mobs.push new window.DemCreepers.Golem x, y
else
_.map [0..9], () =>
@_mobs.push new window.DemCreepers.Gob x, y
n -= 10
else
@_mobs.push new window.DemCreepers.Gob x, y
n -= 1
regen : =>
@_mobs = []
max = Math.round (@nbPacks / 2)
n = _.random 1, max
while n > @nbPacks - @_pack
n = _.random 1, max
_.map [1..n], =>
do @genPack
++@_pack
return
nextPack : =>
if @_pack >= @nbPacks
return no
else
do @regen
return yes
class HUD
constructor : ->
@_letters =new jaws.SpriteSheet
image : 'img/HUD-NUMBERSLETTERS.gif'
frame_size : [15, 15]
orientation : 'right'
@_bg = new jaws.Sprite
image : 'img/HUD.gif'
width: 400
height: 20
scale : 2
x : 0
y : 0
do @createMessages
@_msg = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 300
scale : 2
@_msg2 = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 340
scale : 2
@_end = [no, no]
###
# HP
###
@_hp = new jaws.SpriteList
_.map [0..2], (i) =>
@_hp.push new jaws.Sprite
image : @_letters.frames[0]
x : 85 - i * 17
y : 5
scale : 2
###
# Waves
###
@_waves = new jaws.SpriteList
_.map [0..2], (i) =>
@_waves.push new jaws.Sprite
image : @_letters.frames[0]
x : 250 - i * 17
y : 5
scale : 2
###
# Kills
###
@_kills = new jaws.SpriteList
_.map [0..3], (i) =>
@_kills.push new jaws.Sprite
image : @_letters.frames[0]
x : 410 - i * 17
y : 5
scale : 2
###
# Score
###
@_score = new jaws.SpriteList
_.map [0..10], (i) =>
@_score.push new jaws.Sprite
image : @_letters.frames[0]
x : 750 - i * 17
y : 5
scale : 2
###
# Wave Bonus
###
@_wavebonus = new jaws.SpriteList
createMessages : =>
@_messages =new jaws.Animation
sprite_sheet : 'img/HUD-ANIMATED.gif'
frame_size : [300, 20]
frame_duration : 70
loop : no
anchor : 'center'
subsets :
'wave' : [0, 6]
'perfect' : [6, 13]
on_end : =>
setTimeout (=>
@_end = [no, no]
do @createMessages
), 2000
update : (player) =>
_.map [0..2], (i) =>
(@_hp.at i).setImage @_letters.frames[0]
_.map do ((String player._hp).split '').reverse, (n, i) =>
(@_hp.at i).setImage @_letters.frames[n]
_.map do ((String Waves).split '').reverse, (n, i) =>
(@_waves.at i).setImage @_letters.frames[n]
_.map do ((String Score).split '').reverse, (n, i) =>
(@_score.at i).setImage @_letters.frames[n]
_.map do ((String KillCount).split '').reverse, (n, i) =>
(@_kills.at i).setImage @_letters.frames[n]
if @_end[0]
if @_wavebonus.length is 0
bonus = Bonus[0] - 100
if @_end[1]
bonus += 500 + 500 * (player.PerfectChain - 1)
bonus = (String bonus) + 'pts'
baseX = 400 - (Math.floor (bonus.length / 2)) * 30
if not (bonus.length % 2)
baseX += 15
_.map (bonus.split ''), (n, i) =>
@_wavebonus.push new jaws.Sprite
image : @_letters.frames[window.DemCreepers.Utils.getTileId n]
x : baseX + i * 30
y : 400
scale : 3
anchor : 'center'
@_msg.setImage do @_messages.subsets['wave'].next
@_msg2.setImage do @_messages.subsets['perfect'].next
else if @_wavebonus.length > 0
@_wavebonus.removeIf () => true
draw : =>
do @_bg.draw
do @_hp.draw
do @_waves.draw
do @_score.draw
do @_kills.draw
if @_end[0]
do @_wavebonus.draw
do @_msg.draw
if @_end[1]
do @_msg2.draw
class MainGame
constructor : ->
@_paused = no
@_texts = new jaws.SpriteSheet
image : 'img/HUD---TEXT.gif'
frame_size : [80, 20]
@_quadtree = new jaws.QuadTree
@_update = @titleUpdate
@_draw = @titleDraw
@_title = new jaws.Sprite
image : 'img/HUD---PICTURES---V1.gif'
scale : 2
x : 0
y : 0
@START = new jaws.Audio audio : 'audio/START.ogg', volume : window.DemCreepers.Volumes.FX
@MENU = new jaws.Audio
audio : 'audio/MENU.ogg'
volume : window.DemCreepers.Volumes.Music
loop : yes
setup : =>
do @MENU.play
[rows, cols] = [9, 12]
@_viewport = new jaws.Viewport
x : 0
y : 20
max_x : cols * (window.DemCreepers.Config.TileSize[0] * 2)
max_y : rows * (window.DemCreepers.Config.TileSize[1] * 2)
@_hud = new HUD
@_map = new window.DemCreepers.Map rows, cols
@_player = new window.DemCreepers.Player 600, 450
@_pauseOverlay = new jaws.Sprite
x : 0
y : 0
width : 800
height : 600
color : 'rgba(0,0,0,.5)'
@_pauseText = new jaws.Sprite
image : @_texts.frames[0]
anchor : 'center'
x : 400
y : 300
scale : 2
@_gameOverText = new jaws.Sprite
image : @_texts.frames[2]
anchor : 'center'
x : 400
y : 200
scale : 2
setupEnd : =>
do @updateScores
@Valid = no
@Name = [ 'A' , 'A' , 'A' ]
@Pos = 0
@_Name = new jaws.SpriteList
@_Cursor = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 1]
scale : 2
_.map [0..2], (i) =>
@_Name.push new jaws.Sprite
image : @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
x : (400 - 30) + (i * 20)
y : 300
scale : 2
anchor : 'center'
@_Enter = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 2]
x : (400 - 30) + (3 * 22)
y : 300
scale : 2
nextWave : =>
do @_map.updateForNextWave
if Waves < 2
@_wave = new Wave1
else if Waves < 3
@_wave = new Wave2
else
if not (Waves % 4)
rand = _.random 1, 2
if rand is 1
++Packs.Count
else
Packs.Value += 5
@_wave = new RandWave Packs.Count, Packs.Value
++Waves
Score += Bonus[0]
Bonus[0] += 100
@_hud._end[0] = yes
if not @_player._hit
Score += 500 + 500 * @_player.PerfectChain++
@_hud._end[1] = yes
@_player._hit = no
gameupdate : =>
if (@_overlayText isnt 'gameOverText') and jaws.pressedWithoutRepeat 'space'
@_paused = not @_paused
if @_paused then do @_music.pause else do @_music.play
if not @_paused
if @_wave._mobs.length is 0
@_quadtree = new jaws.QuadTree
if not (do @_wave.nextPack)
do @nextWave
all = _.union (_.map @_wave._mobs, (item) -> item._box), [@_player._box]
all = _.filter all, (x) => @_viewport.isPartlyInside x
try
if all.length > 1
@_quadtree.collide all, all, (a, b) =>
a.coll = b
b.coll = a
### Player ###
if not (@_player.update @_viewport, @_map._map)
@_paused = yes
@_overlayText = 'gameOverText'
do @_music.stop
do @setupEnd
@_update = @endupdate
@_draw = @enddraw
### Monsters ###
@_wave.update @_player, @_map
### Center viewport on Player ###
@_viewport.centerAround @_player._box
### HUD ###
@_hud.update @_player
do @_quadtree.clear
gamedraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
### HUD ###
do @_hud.draw
###
# PAUSE
###
if @_paused
do @_pauseOverlay.draw
do @_pauseText.draw
###
(document.getElementById 'playerX').innerHTML = @_player.x
(document.getElementById 'playerY').innerHTML = @_player.y
(document.getElementById 'viewportX').innerHTML = @_viewport.x
(document.getElementById 'viewportY').innerHTML = @_viewport.y
###
titleUpdate : =>
do @_player.simpleUpdate
### Center viewport on Player ###
@_viewport.centerAround @_player._box
if jaws.pressedWithoutRepeat 'enter'
do @MENU.stop
do @START.play
setTimeout (=>
@_music = new jaws.Audio {
audio : 'audio/GAME_LOOP.ogg'
volume : window.DemCreepers.Volumes.Music
loop : 1
}
do @_music.play
@_update = @gameupdate
@_draw = @gamedraw
@_wave = new Wave1
), 500
titleDraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_title.draw
updateScores : =>
Req = new XMLHttpRequest
Req.onload = =>
@Scores = JSON.parse Req.response
@_Names = []
@_Scores = []
i = 0
x = 50
y = 400
_.map @Scores, (score) =>
@_Names.push new jaws.SpriteList
@_Scores.push new jaws.SpriteList
_.map score.name, (letter, j) =>
@_Names[i].push new jaws.Sprite
anchor : 'center'
x : x + j * 20
y : y
scale : 2
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId letter)]
@_score = new jaws.SpriteList
_.map [0..10], (j) =>
@_Scores[i].push new jaws.Sprite
image : @_hud._letters.frames[0]
x : x + 80 + (10 * 20) - (j * 20)
y : y
scale : 2
anchor : 'center'
_.map do ((String score.value).split '').reverse, (n, j) =>
(@_Scores[i].at j).setImage @_hud._letters.frames[n]
y += 40
if ++i is 5
x += 400
y = 400
Req.open 'get', '/scores', yes
do Req.send
endupdate : =>
if not @Valid
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
@_Cursor.moveTo (400 - 30) + (@Pos * 20), 320
if @Pos < 3
if jaws.pressedWithoutRepeat "#{controls.down}"
if @Name[@Pos] is 'A'
@Name[@Pos] = '9'
else if @Name[@Pos] is '0'
@Name[@Pos] = 'Z'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) - 1
else if jaws.pressedWithoutRepeat "#{controls.up}"
if @Name[@Pos] is 'Z'
@Name[@Pos] = '0'
else if @Name[@Pos] is '9'
@Name[@Pos] = 'A'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) + 1
if jaws.pressedWithoutRepeat "#{controls.left}"
--@Pos if @Pos > 0
else if jaws.pressedWithoutRepeat "#{controls.right}"
++@Pos if @Pos < 3
else if jaws.pressedWithoutRepeat 'enter'
if @Pos < 3
++@Pos
else
@Valid = yes
Req = new XMLHttpRequest
Req.onload = =>
do @updateScores
Req.open 'post', '/score', yes
params = "name=#{@Name.join ''}&score=#{Score}"
Req.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
Req.setRequestHeader "Content-length", params.length
Req.setRequestHeader "Connection", "close"
Req.send params
_.map [0..2], (i) =>
(@_Name.at i).setImage @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
enddraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_hud.draw
do @_pauseOverlay.draw
do @_gameOverText.draw
_.map @_Names, (name) -> do name.draw
_.map @_Scores, (score) -> do score.draw
if not @Valid
do @_Name.draw
do @_Enter.draw
do @_Cursor.draw
update : =>
do @_update
draw : =>
do @_draw
if window.DemCreepers?
window.DemCreepers.MainGame = MainGame | true | #####
##
# Dem Creepers!
# Entry for the GitHub Game Off 2013
# Author : PI:NAME:<NAME>END_PI for H-Bomb
# <PI:EMAIL:<EMAIL>END_PI>
##
#####
Score = 0
KillCount = 0
Waves = 1
Packs =
Count : 2
Value : 15
Bonus = [100, 500]
class Wave
constructor : ->
@HIT = new jaws.Audio audio : 'audio/HIT.ogg', volume : window.DemCreepers.Volumes.FX
@_mobs = []
@_pack = 0
update : (player, map) =>
toDel = []
_.map @_mobs, (mob, index) =>
del = no
_.map player._axes, (axe) =>
if ((do axe._box.rect).collideRect (do mob._box.rect)) and axe._toGo >= 0
axe._toGo = -1
if --mob.pv <= 0
#do mob._DEATH.play
toDel.push index
del = yes
map.add mob
Score += mob.reward * player.Mult
if ++player.Chain is 10
player.Chain = 0
++player.Mult
KillCount += 1
do @HIT.play
if not del
mob.update player, map._map
toDel = toDel.sort (a, b) => b - a
_.map toDel, (index) =>
@_mobs.splice index, 1
getToDraw : (viewport) => _.filter @_mobs, (mob) -> viewport.isPartlyInside mob._sprite
nextPack : =>
class Wave1 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Gob x, y
_.map [1..8], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class Wave2 extends Wave
constructor : ->
super 0
do @regen
regen : =>
@_mobs = []
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
@_mobs.push new window.DemCreepers.Golem x, y
_.map [1..6], (i) =>
setTimeout (=>
@_mobs.push new window.DemCreepers.Gob x, y
), i * 100
nextPack : =>
++@_pack
if @_pack < 2
do @regen
return yes
else
return no
class RandWave extends Wave
constructor : (@nbPacks, @packsValue) ->
super 0
do @regen
genPack : =>
[x, y] = do window.DemCreepers.Utils.getRandomSpawn
n = @packsValue
while n > 0
if n >= 10
rand = _.random 0, 1
if rand
@_mobs.push new window.DemCreepers.Golem x, y
else
_.map [0..9], () =>
@_mobs.push new window.DemCreepers.Gob x, y
n -= 10
else
@_mobs.push new window.DemCreepers.Gob x, y
n -= 1
regen : =>
@_mobs = []
max = Math.round (@nbPacks / 2)
n = _.random 1, max
while n > @nbPacks - @_pack
n = _.random 1, max
_.map [1..n], =>
do @genPack
++@_pack
return
nextPack : =>
if @_pack >= @nbPacks
return no
else
do @regen
return yes
class HUD
constructor : ->
@_letters =new jaws.SpriteSheet
image : 'img/HUD-NUMBERSLETTERS.gif'
frame_size : [15, 15]
orientation : 'right'
@_bg = new jaws.Sprite
image : 'img/HUD.gif'
width: 400
height: 20
scale : 2
x : 0
y : 0
do @createMessages
@_msg = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 300
scale : 2
@_msg2 = new jaws.Sprite
width : 300
height : 20
anchor : 'center'
x : 400
y : 340
scale : 2
@_end = [no, no]
###
# HP
###
@_hp = new jaws.SpriteList
_.map [0..2], (i) =>
@_hp.push new jaws.Sprite
image : @_letters.frames[0]
x : 85 - i * 17
y : 5
scale : 2
###
# Waves
###
@_waves = new jaws.SpriteList
_.map [0..2], (i) =>
@_waves.push new jaws.Sprite
image : @_letters.frames[0]
x : 250 - i * 17
y : 5
scale : 2
###
# Kills
###
@_kills = new jaws.SpriteList
_.map [0..3], (i) =>
@_kills.push new jaws.Sprite
image : @_letters.frames[0]
x : 410 - i * 17
y : 5
scale : 2
###
# Score
###
@_score = new jaws.SpriteList
_.map [0..10], (i) =>
@_score.push new jaws.Sprite
image : @_letters.frames[0]
x : 750 - i * 17
y : 5
scale : 2
###
# Wave Bonus
###
@_wavebonus = new jaws.SpriteList
createMessages : =>
@_messages =new jaws.Animation
sprite_sheet : 'img/HUD-ANIMATED.gif'
frame_size : [300, 20]
frame_duration : 70
loop : no
anchor : 'center'
subsets :
'wave' : [0, 6]
'perfect' : [6, 13]
on_end : =>
setTimeout (=>
@_end = [no, no]
do @createMessages
), 2000
update : (player) =>
_.map [0..2], (i) =>
(@_hp.at i).setImage @_letters.frames[0]
_.map do ((String player._hp).split '').reverse, (n, i) =>
(@_hp.at i).setImage @_letters.frames[n]
_.map do ((String Waves).split '').reverse, (n, i) =>
(@_waves.at i).setImage @_letters.frames[n]
_.map do ((String Score).split '').reverse, (n, i) =>
(@_score.at i).setImage @_letters.frames[n]
_.map do ((String KillCount).split '').reverse, (n, i) =>
(@_kills.at i).setImage @_letters.frames[n]
if @_end[0]
if @_wavebonus.length is 0
bonus = Bonus[0] - 100
if @_end[1]
bonus += 500 + 500 * (player.PerfectChain - 1)
bonus = (String bonus) + 'pts'
baseX = 400 - (Math.floor (bonus.length / 2)) * 30
if not (bonus.length % 2)
baseX += 15
_.map (bonus.split ''), (n, i) =>
@_wavebonus.push new jaws.Sprite
image : @_letters.frames[window.DemCreepers.Utils.getTileId n]
x : baseX + i * 30
y : 400
scale : 3
anchor : 'center'
@_msg.setImage do @_messages.subsets['wave'].next
@_msg2.setImage do @_messages.subsets['perfect'].next
else if @_wavebonus.length > 0
@_wavebonus.removeIf () => true
draw : =>
do @_bg.draw
do @_hp.draw
do @_waves.draw
do @_score.draw
do @_kills.draw
if @_end[0]
do @_wavebonus.draw
do @_msg.draw
if @_end[1]
do @_msg2.draw
class MainGame
constructor : ->
@_paused = no
@_texts = new jaws.SpriteSheet
image : 'img/HUD---TEXT.gif'
frame_size : [80, 20]
@_quadtree = new jaws.QuadTree
@_update = @titleUpdate
@_draw = @titleDraw
@_title = new jaws.Sprite
image : 'img/HUD---PICTURES---V1.gif'
scale : 2
x : 0
y : 0
@START = new jaws.Audio audio : 'audio/START.ogg', volume : window.DemCreepers.Volumes.FX
@MENU = new jaws.Audio
audio : 'audio/MENU.ogg'
volume : window.DemCreepers.Volumes.Music
loop : yes
setup : =>
do @MENU.play
[rows, cols] = [9, 12]
@_viewport = new jaws.Viewport
x : 0
y : 20
max_x : cols * (window.DemCreepers.Config.TileSize[0] * 2)
max_y : rows * (window.DemCreepers.Config.TileSize[1] * 2)
@_hud = new HUD
@_map = new window.DemCreepers.Map rows, cols
@_player = new window.DemCreepers.Player 600, 450
@_pauseOverlay = new jaws.Sprite
x : 0
y : 0
width : 800
height : 600
color : 'rgba(0,0,0,.5)'
@_pauseText = new jaws.Sprite
image : @_texts.frames[0]
anchor : 'center'
x : 400
y : 300
scale : 2
@_gameOverText = new jaws.Sprite
image : @_texts.frames[2]
anchor : 'center'
x : 400
y : 200
scale : 2
setupEnd : =>
do @updateScores
@Valid = no
@Name = [ 'A' , 'A' , 'A' ]
@Pos = 0
@_Name = new jaws.SpriteList
@_Cursor = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 1]
scale : 2
_.map [0..2], (i) =>
@_Name.push new jaws.Sprite
image : @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
x : (400 - 30) + (i * 20)
y : 300
scale : 2
anchor : 'center'
@_Enter = new jaws.Sprite
anchor : 'center'
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId 'z') + 2]
x : (400 - 30) + (3 * 22)
y : 300
scale : 2
nextWave : =>
do @_map.updateForNextWave
if Waves < 2
@_wave = new Wave1
else if Waves < 3
@_wave = new Wave2
else
if not (Waves % 4)
rand = _.random 1, 2
if rand is 1
++Packs.Count
else
Packs.Value += 5
@_wave = new RandWave Packs.Count, Packs.Value
++Waves
Score += Bonus[0]
Bonus[0] += 100
@_hud._end[0] = yes
if not @_player._hit
Score += 500 + 500 * @_player.PerfectChain++
@_hud._end[1] = yes
@_player._hit = no
gameupdate : =>
if (@_overlayText isnt 'gameOverText') and jaws.pressedWithoutRepeat 'space'
@_paused = not @_paused
if @_paused then do @_music.pause else do @_music.play
if not @_paused
if @_wave._mobs.length is 0
@_quadtree = new jaws.QuadTree
if not (do @_wave.nextPack)
do @nextWave
all = _.union (_.map @_wave._mobs, (item) -> item._box), [@_player._box]
all = _.filter all, (x) => @_viewport.isPartlyInside x
try
if all.length > 1
@_quadtree.collide all, all, (a, b) =>
a.coll = b
b.coll = a
### Player ###
if not (@_player.update @_viewport, @_map._map)
@_paused = yes
@_overlayText = 'gameOverText'
do @_music.stop
do @setupEnd
@_update = @endupdate
@_draw = @enddraw
### Monsters ###
@_wave.update @_player, @_map
### Center viewport on Player ###
@_viewport.centerAround @_player._box
### HUD ###
@_hud.update @_player
do @_quadtree.clear
gamedraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
### HUD ###
do @_hud.draw
###
# PAUSE
###
if @_paused
do @_pauseOverlay.draw
do @_pauseText.draw
###
(document.getElementById 'playerX').innerHTML = @_player.x
(document.getElementById 'playerY').innerHTML = @_player.y
(document.getElementById 'viewportX').innerHTML = @_viewport.x
(document.getElementById 'viewportY').innerHTML = @_viewport.y
###
titleUpdate : =>
do @_player.simpleUpdate
### Center viewport on Player ###
@_viewport.centerAround @_player._box
if jaws.pressedWithoutRepeat 'enter'
do @MENU.stop
do @START.play
setTimeout (=>
@_music = new jaws.Audio {
audio : 'audio/GAME_LOOP.ogg'
volume : window.DemCreepers.Volumes.Music
loop : 1
}
do @_music.play
@_update = @gameupdate
@_draw = @gamedraw
@_wave = new Wave1
), 500
titleDraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_title.draw
updateScores : =>
Req = new XMLHttpRequest
Req.onload = =>
@Scores = JSON.parse Req.response
@_Names = []
@_Scores = []
i = 0
x = 50
y = 400
_.map @Scores, (score) =>
@_Names.push new jaws.SpriteList
@_Scores.push new jaws.SpriteList
_.map score.name, (letter, j) =>
@_Names[i].push new jaws.Sprite
anchor : 'center'
x : x + j * 20
y : y
scale : 2
image : @_hud._letters.frames[(window.DemCreepers.Utils.getTileId letter)]
@_score = new jaws.SpriteList
_.map [0..10], (j) =>
@_Scores[i].push new jaws.Sprite
image : @_hud._letters.frames[0]
x : x + 80 + (10 * 20) - (j * 20)
y : y
scale : 2
anchor : 'center'
_.map do ((String score.value).split '').reverse, (n, j) =>
(@_Scores[i].at j).setImage @_hud._letters.frames[n]
y += 40
if ++i is 5
x += 400
y = 400
Req.open 'get', '/scores', yes
do Req.send
endupdate : =>
if not @Valid
controls = window.DemCreepers.Controls[window.DemCreepers.Config.ActiveControls]
@_Cursor.moveTo (400 - 30) + (@Pos * 20), 320
if @Pos < 3
if jaws.pressedWithoutRepeat "#{controls.down}"
if @Name[@Pos] is 'A'
@Name[@Pos] = '9'
else if @Name[@Pos] is '0'
@Name[@Pos] = 'Z'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) - 1
else if jaws.pressedWithoutRepeat "#{controls.up}"
if @Name[@Pos] is 'Z'
@Name[@Pos] = '0'
else if @Name[@Pos] is '9'
@Name[@Pos] = 'A'
else
@Name[@Pos] = String.fromCharCode (do @Name[@Pos].charCodeAt) + 1
if jaws.pressedWithoutRepeat "#{controls.left}"
--@Pos if @Pos > 0
else if jaws.pressedWithoutRepeat "#{controls.right}"
++@Pos if @Pos < 3
else if jaws.pressedWithoutRepeat 'enter'
if @Pos < 3
++@Pos
else
@Valid = yes
Req = new XMLHttpRequest
Req.onload = =>
do @updateScores
Req.open 'post', '/score', yes
params = "name=#{@Name.join ''}&score=#{Score}"
Req.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
Req.setRequestHeader "Content-length", params.length
Req.setRequestHeader "Connection", "close"
Req.send params
_.map [0..2], (i) =>
(@_Name.at i).setImage @_hud._letters.frames[window.DemCreepers.Utils.getTileId @Name[i]]
enddraw : =>
do jaws.clear
### Draw the ground below everything ###
@_viewport.drawTileMap @_map._ground
### Player ###
window.DemCreepers.DrawBatch.add do @_player.getToDraw
### Ground ###
_.map (do @_map.all), (tile) =>
window.DemCreepers.DrawBatch.add tile
### Monsters ###
window.DemCreepers.DrawBatch.add @_wave.getToDraw @_viewport
@_viewport.apply =>
### Draw all ###
window.DemCreepers.DrawBatch.draw @_viewport
do @_hud.draw
do @_pauseOverlay.draw
do @_gameOverText.draw
_.map @_Names, (name) -> do name.draw
_.map @_Scores, (score) -> do score.draw
if not @Valid
do @_Name.draw
do @_Enter.draw
do @_Cursor.draw
update : =>
do @_update
draw : =>
do @_draw
if window.DemCreepers?
window.DemCreepers.MainGame = MainGame |
[
{
"context": "n 1 hour to check my email.\\\"\\n\" +\n \"\\\"Rachel, can you remind me to check my email next week?\\\"",
"end": 2896,
"score": 0.934705913066864,
"start": 2890,
"tag": "NAME",
"value": "Rachel"
},
{
"context": " \"\\\"Remind me tomorrow noon to have lu... | src/server/services/messagers.coffee | FindBoat/rachel-bot | 0 | moment = require 'moment'
ChatContext = require './chat-context'
Feedback = require './feedbacks'
Reminder = require './reminders'
User = require './users'
bot = require './bots'
generalParser = require './general-parsers'
locationParser = require './location-parsers'
reminderParser = require './reminder-parsers'
tzExtractor = require './tz-extractors'
utils = require './utils'
createUserIfNotPresent = (message, next) ->
User.findOne telegramUserId: message.from.id, (err, user) ->
if err?
console.log err
return
if user?
console.log "User #{message.from.id} @#{message.from.username} exists in system"
next user
return
# Create new user.
console.log "Creating new user: #{message.from.id} @#{message.from.username}"
user = new User
firstName: message.from.first_name
lastName: message.from.last_name
telegramUsername: message.from.username
telegramUserId: message.from.id
user.save (err) ->
if err?
console.log err
return
next user
createChatContextIfNotPresent = (message, user, next) ->
ChatContext.findOne chatId: message.chat.id, (err, chatContext) ->
if err?
console.log err
return
if chatContext?
console.log "Chat Id #{message.chat.id} exists in system"
next chatContext
return
# Create ChatContext.
console.log "Creating new chat context: #{message.chat.id}"
chatContext = new ChatContext
userId: user._id
chatId: message.chat.id
chatContext.save (err) ->
if err?
console.log err
return
next chatContext
waitAndParseLocation = (message, user, chatContext) ->
locationParser.parse message, (err, location) ->
if err?
console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Sorry, I can't understand the location you sent.\n\n Can " +
"you tap the paperclip on the bottom, tap " +
"Location and then tap Send My Current Location.\nOr send your " +
"city, state and country like \"Palo Alto, CA, US\".")
return
console.log "Parsed location: #{JSON.stringify(location)}"
tzExtractor.extractTimeZone location.lat, location.lng, (err, tz) ->
if err?
console.log err
return
console.log "Parsed timezone: #{JSON.stringify(tz)}"
user.location = location
user.timezone = tz
user.save (err) -> if err? then console.log err
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Good job! Your location and timezone is set. Anything you " +
"want me to remind you? Here are examples that might be " +
"helpful:\n\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"Rachel, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with Mark.\"\n")
askLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName}, I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendGreeting = (message, user, chatContext) ->
if user.location.lat?
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant Rachel. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.")
else
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant Rachel. " +
"I can remind you with whatever you want in anytime.\n\n" +
"Now I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom :point_down:, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendHelp = (message) ->
bot.sendMessage
chat_id: message.chat.id
text: ("I'm your assistant Rachel. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.\n\n" +
"Here are examples that I can better understand:\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"Rachel, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with Mark.\"\n\n" +
"/feedback to tell me your feedback.\n" +
"/resetlocation to reset your location and timezone.\n" +
"/listreminders to see all your unnotified reminders.")
cancelReminder = (message, user) ->
Reminder.findOne userId: user._id, null, sort: {createAt: -1}, (err, reminder) ->
reminder.removeWithAgenda (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "I've canceled this reminder."
sendFeedback = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tell me your feedback, I really " +
"appreciate it!\n(Reply \"cancel\" to cancel this.)")
chatContext.status = 'WAIT_FEEDBACK'
chatContext.save (err) -> if err? then console.log err
maybeSaveFeedback = (message, user, chatContext) ->
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
bot.sendMessage
chat_id: message.chat.id
text: "Fine. So what can I do for you #{user.firstName}?"
else
feedback = new Feedback
userId: user._id
feedback: message.text
feedback.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "Thank you so much for your feedback #{user.firstName}!"
sendResetLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
listReminders = (message, user) ->
params =
userId: user._id
reminded: false
Reminder.find(params).sort(remindTime: 1).exec (err, reminders) ->
if err?
console.log err
return
if not reminders? or reminders.length is 0
bot.sendMessage
chat_id: message.chat.id
text: "#{user.firstName}, you don't have any unnotified reminders."
else
str = ''
for reminder in reminders
displayTime = moment(reminder.remindTime).format 'M/D/YYYY hh:mm:ss a'
str += "#{reminder.todo} at #{displayTime}\n"
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, here are your unnotified reminders:" +
"\n\n#{str}")
handleMessage = (message, user, chatContext) ->
# Greeting.
if message.text is '/start'
sendGreeting message, user, chatContext
return
if message.text is '/help' or message.text is 'help'
sendHelp message
return
if message.text is '/feedback'
sendFeedback message, user, chatContext
return
if message.text is '/resetlocation'
sendResetLocation message, user, chatContext
return
if message.text is '/listreminders'
listReminders message, user
return
# Check answer by chatContext.status.
switch chatContext.status
when 'WAIT_LOCATION'
waitAndParseLocation message, user, chatContext
return
when 'WAIT_HRU'
bot.sendMessage
chat_id: message.chat.id
text: "So what can I do for you #{user.firstName}?"
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
return
when 'WAIT_CANCEL_REMINDER'
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
cancelReminder message, user
return
when 'WAIT_FEEDBACK'
maybeSaveFeedback message, user, chatContext
return
# Check location.
if not chatContext.status? and not user.location.lat?
askLocation message, user, chatContext
return
if not message?.text? then return
# Normalize.
normalizedText = message.text
normalizedText = normalizedText.replace /// ^[\W_]+ ///, ''
normalizedText = normalizedText.replace /// [\W_]+$ ///, ''
normalizedText = normalizedText.toLowerCase().replace /// \s+ ///, ' '
# Reminder mode.
if normalizedText.indexOf('remind') isnt -1
console.log 'Reminder mode'
if user.timezone?.dstOffset?
offset = user.timezone.dstOffset + user.timezone.rawOffset
else
offset = 0
offsetDate = moment().add(offset, 'seconds').toDate()
reminderParser.parse normalizedText, offsetDate, (err, res) ->
if err?
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, I'm not sure what you mean. " +
"Here are examples that I can better understand:\n " +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"Rachel, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with Mark.\"\n")
return
displayTime = moment(res.time).format 'M/D/YYYY hh:mm:ss a'
res.time = moment(res.time).add(-offset, 'seconds').toDate()
console.log "ReminderParser returns: #{JSON.stringify(res)}"
reminder = new Reminder
userId: user._id
message: message.text
remindTime: res.time
todo: res.todo
chatId: message.chat.id
reminder.saveWithAgenda user, (err) -> if err? then console.log err
confirm = utils.confirm user.firstName
bot.sendMessage
chat_id: message.chat.id
text: ("#{confirm} I'll remind you to #{res.todo} on #{displayTime}.\n" +
"(Reply \"cancel\" to remove this reminder.)")
chatContext.status = 'WAIT_CANCEL_REMINDER'
chatContext.save (err) -> if err? then console.log err
# General mode.
else
console.log 'General mode'
generalParser.parse normalizedText, user, (err, res) ->
if err?
console.log err
return
if res?
bot.sendMessage
chat_id: message.chat.id
text: res.answer
if res.id is 'hru'
chatContext.status = 'WAIT_HRU'
chatContext.save (err) -> if err? then console.log err
else
bot.sendMessage
chat_id: message.chat.id
text: utils.random user.firstName
return
module.exports =
handle: (message) ->
createUserIfNotPresent message, (user) ->
createChatContextIfNotPresent message, user, (chatContext) ->
handleMessage message, user, chatContext
| 188512 | moment = require 'moment'
ChatContext = require './chat-context'
Feedback = require './feedbacks'
Reminder = require './reminders'
User = require './users'
bot = require './bots'
generalParser = require './general-parsers'
locationParser = require './location-parsers'
reminderParser = require './reminder-parsers'
tzExtractor = require './tz-extractors'
utils = require './utils'
createUserIfNotPresent = (message, next) ->
User.findOne telegramUserId: message.from.id, (err, user) ->
if err?
console.log err
return
if user?
console.log "User #{message.from.id} @#{message.from.username} exists in system"
next user
return
# Create new user.
console.log "Creating new user: #{message.from.id} @#{message.from.username}"
user = new User
firstName: message.from.first_name
lastName: message.from.last_name
telegramUsername: message.from.username
telegramUserId: message.from.id
user.save (err) ->
if err?
console.log err
return
next user
createChatContextIfNotPresent = (message, user, next) ->
ChatContext.findOne chatId: message.chat.id, (err, chatContext) ->
if err?
console.log err
return
if chatContext?
console.log "Chat Id #{message.chat.id} exists in system"
next chatContext
return
# Create ChatContext.
console.log "Creating new chat context: #{message.chat.id}"
chatContext = new ChatContext
userId: user._id
chatId: message.chat.id
chatContext.save (err) ->
if err?
console.log err
return
next chatContext
waitAndParseLocation = (message, user, chatContext) ->
locationParser.parse message, (err, location) ->
if err?
console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Sorry, I can't understand the location you sent.\n\n Can " +
"you tap the paperclip on the bottom, tap " +
"Location and then tap Send My Current Location.\nOr send your " +
"city, state and country like \"Palo Alto, CA, US\".")
return
console.log "Parsed location: #{JSON.stringify(location)}"
tzExtractor.extractTimeZone location.lat, location.lng, (err, tz) ->
if err?
console.log err
return
console.log "Parsed timezone: #{JSON.stringify(tz)}"
user.location = location
user.timezone = tz
user.save (err) -> if err? then console.log err
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Good job! Your location and timezone is set. Anything you " +
"want me to remind you? Here are examples that might be " +
"helpful:\n\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"<NAME>, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with <NAME>.\"\n")
askLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName}, I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendGreeting = (message, user, chatContext) ->
if user.location.lat?
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant <NAME>. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.")
else
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant <NAME>. " +
"I can remind you with whatever you want in anytime.\n\n" +
"Now I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom :point_down:, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendHelp = (message) ->
bot.sendMessage
chat_id: message.chat.id
text: ("I'm your assistant <NAME>. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.\n\n" +
"Here are examples that I can better understand:\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"<NAME>, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with Mark.\"\n\n" +
"/feedback to tell me your feedback.\n" +
"/resetlocation to reset your location and timezone.\n" +
"/listreminders to see all your unnotified reminders.")
cancelReminder = (message, user) ->
Reminder.findOne userId: user._id, null, sort: {createAt: -1}, (err, reminder) ->
reminder.removeWithAgenda (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "I've canceled this reminder."
sendFeedback = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tell me your feedback, I really " +
"appreciate it!\n(Reply \"cancel\" to cancel this.)")
chatContext.status = 'WAIT_FEEDBACK'
chatContext.save (err) -> if err? then console.log err
maybeSaveFeedback = (message, user, chatContext) ->
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
bot.sendMessage
chat_id: message.chat.id
text: "Fine. So what can I do for you #{user.firstName}?"
else
feedback = new Feedback
userId: user._id
feedback: message.text
feedback.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "Thank you so much for your feedback #{user.firstName}!"
sendResetLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
listReminders = (message, user) ->
params =
userId: user._id
reminded: false
Reminder.find(params).sort(remindTime: 1).exec (err, reminders) ->
if err?
console.log err
return
if not reminders? or reminders.length is 0
bot.sendMessage
chat_id: message.chat.id
text: "#{user.firstName}, you don't have any unnotified reminders."
else
str = ''
for reminder in reminders
displayTime = moment(reminder.remindTime).format 'M/D/YYYY hh:mm:ss a'
str += "#{reminder.todo} at #{displayTime}\n"
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, here are your unnotified reminders:" +
"\n\n#{str}")
handleMessage = (message, user, chatContext) ->
# Greeting.
if message.text is '/start'
sendGreeting message, user, chatContext
return
if message.text is '/help' or message.text is 'help'
sendHelp message
return
if message.text is '/feedback'
sendFeedback message, user, chatContext
return
if message.text is '/resetlocation'
sendResetLocation message, user, chatContext
return
if message.text is '/listreminders'
listReminders message, user
return
# Check answer by chatContext.status.
switch chatContext.status
when 'WAIT_LOCATION'
waitAndParseLocation message, user, chatContext
return
when 'WAIT_HRU'
bot.sendMessage
chat_id: message.chat.id
text: "So what can I do for you #{user.firstName}?"
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
return
when 'WAIT_CANCEL_REMINDER'
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
cancelReminder message, user
return
when 'WAIT_FEEDBACK'
maybeSaveFeedback message, user, chatContext
return
# Check location.
if not chatContext.status? and not user.location.lat?
askLocation message, user, chatContext
return
if not message?.text? then return
# Normalize.
normalizedText = message.text
normalizedText = normalizedText.replace /// ^[\W_]+ ///, ''
normalizedText = normalizedText.replace /// [\W_]+$ ///, ''
normalizedText = normalizedText.toLowerCase().replace /// \s+ ///, ' '
# Reminder mode.
if normalizedText.indexOf('remind') isnt -1
console.log 'Reminder mode'
if user.timezone?.dstOffset?
offset = user.timezone.dstOffset + user.timezone.rawOffset
else
offset = 0
offsetDate = moment().add(offset, 'seconds').toDate()
reminderParser.parse normalizedText, offsetDate, (err, res) ->
if err?
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, I'm not sure what you mean. " +
"Here are examples that I can better understand:\n " +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"<NAME>, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with <NAME>.\"\n")
return
displayTime = moment(res.time).format 'M/D/YYYY hh:mm:ss a'
res.time = moment(res.time).add(-offset, 'seconds').toDate()
console.log "ReminderParser returns: #{JSON.stringify(res)}"
reminder = new Reminder
userId: user._id
message: message.text
remindTime: res.time
todo: res.todo
chatId: message.chat.id
reminder.saveWithAgenda user, (err) -> if err? then console.log err
confirm = utils.confirm user.firstName
bot.sendMessage
chat_id: message.chat.id
text: ("#{confirm} I'll remind you to #{res.todo} on #{displayTime}.\n" +
"(Reply \"cancel\" to remove this reminder.)")
chatContext.status = 'WAIT_CANCEL_REMINDER'
chatContext.save (err) -> if err? then console.log err
# General mode.
else
console.log 'General mode'
generalParser.parse normalizedText, user, (err, res) ->
if err?
console.log err
return
if res?
bot.sendMessage
chat_id: message.chat.id
text: res.answer
if res.id is 'hru'
chatContext.status = 'WAIT_HRU'
chatContext.save (err) -> if err? then console.log err
else
bot.sendMessage
chat_id: message.chat.id
text: utils.random user.firstName
return
module.exports =
handle: (message) ->
createUserIfNotPresent message, (user) ->
createChatContextIfNotPresent message, user, (chatContext) ->
handleMessage message, user, chatContext
| true | moment = require 'moment'
ChatContext = require './chat-context'
Feedback = require './feedbacks'
Reminder = require './reminders'
User = require './users'
bot = require './bots'
generalParser = require './general-parsers'
locationParser = require './location-parsers'
reminderParser = require './reminder-parsers'
tzExtractor = require './tz-extractors'
utils = require './utils'
createUserIfNotPresent = (message, next) ->
User.findOne telegramUserId: message.from.id, (err, user) ->
if err?
console.log err
return
if user?
console.log "User #{message.from.id} @#{message.from.username} exists in system"
next user
return
# Create new user.
console.log "Creating new user: #{message.from.id} @#{message.from.username}"
user = new User
firstName: message.from.first_name
lastName: message.from.last_name
telegramUsername: message.from.username
telegramUserId: message.from.id
user.save (err) ->
if err?
console.log err
return
next user
createChatContextIfNotPresent = (message, user, next) ->
ChatContext.findOne chatId: message.chat.id, (err, chatContext) ->
if err?
console.log err
return
if chatContext?
console.log "Chat Id #{message.chat.id} exists in system"
next chatContext
return
# Create ChatContext.
console.log "Creating new chat context: #{message.chat.id}"
chatContext = new ChatContext
userId: user._id
chatId: message.chat.id
chatContext.save (err) ->
if err?
console.log err
return
next chatContext
waitAndParseLocation = (message, user, chatContext) ->
locationParser.parse message, (err, location) ->
if err?
console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Sorry, I can't understand the location you sent.\n\n Can " +
"you tap the paperclip on the bottom, tap " +
"Location and then tap Send My Current Location.\nOr send your " +
"city, state and country like \"Palo Alto, CA, US\".")
return
console.log "Parsed location: #{JSON.stringify(location)}"
tzExtractor.extractTimeZone location.lat, location.lng, (err, tz) ->
if err?
console.log err
return
console.log "Parsed timezone: #{JSON.stringify(tz)}"
user.location = location
user.timezone = tz
user.save (err) -> if err? then console.log err
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: ("Good job! Your location and timezone is set. Anything you " +
"want me to remind you? Here are examples that might be " +
"helpful:\n\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"PI:NAME:<NAME>END_PI, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with PI:NAME:<NAME>END_PI.\"\n")
askLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName}, I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendGreeting = (message, user, chatContext) ->
if user.location.lat?
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant PI:NAME:<NAME>END_PI. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.")
else
bot.sendMessage
chat_id: message.chat.id
text: ("Hi #{user.firstName},\n\nI'm your assistant PI:NAME:<NAME>END_PI. " +
"I can remind you with whatever you want in anytime.\n\n" +
"Now I need to know your location to set up " +
"the timezone for you.\n\nPlease tap the paperclip on the " +
"bottom :point_down:, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
sendHelp = (message) ->
bot.sendMessage
chat_id: message.chat.id
text: ("I'm your assistant PI:NAME:<NAME>END_PI. " +
"I can remind you with whatever you want in anytime. Just " +
"tell me something like \"Remind me to clear home tomorrow " +
"at noon\" and I'll set up a reminder for you.\n\n" +
"Here are examples that I can better understand:\n" +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"PI:NAME:<NAME>END_PI, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with Mark.\"\n\n" +
"/feedback to tell me your feedback.\n" +
"/resetlocation to reset your location and timezone.\n" +
"/listreminders to see all your unnotified reminders.")
cancelReminder = (message, user) ->
Reminder.findOne userId: user._id, null, sort: {createAt: -1}, (err, reminder) ->
reminder.removeWithAgenda (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "I've canceled this reminder."
sendFeedback = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tell me your feedback, I really " +
"appreciate it!\n(Reply \"cancel\" to cancel this.)")
chatContext.status = 'WAIT_FEEDBACK'
chatContext.save (err) -> if err? then console.log err
maybeSaveFeedback = (message, user, chatContext) ->
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
bot.sendMessage
chat_id: message.chat.id
text: "Fine. So what can I do for you #{user.firstName}?"
else
feedback = new Feedback
userId: user._id
feedback: message.text
feedback.save (err) -> if err? then console.log err
bot.sendMessage
chat_id: message.chat.id
text: "Thank you so much for your feedback #{user.firstName}!"
sendResetLocation = (message, user, chatContext) ->
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, please tap the paperclip on the " +
"bottom, tap Location and then tap Send My " +
"Current Location.\nOr you can just send your city, state " +
"and country like \"Palo Alto, CA, US\".")
chatContext.status = 'WAIT_LOCATION'
chatContext.save (err) -> if err? then console.log err
listReminders = (message, user) ->
params =
userId: user._id
reminded: false
Reminder.find(params).sort(remindTime: 1).exec (err, reminders) ->
if err?
console.log err
return
if not reminders? or reminders.length is 0
bot.sendMessage
chat_id: message.chat.id
text: "#{user.firstName}, you don't have any unnotified reminders."
else
str = ''
for reminder in reminders
displayTime = moment(reminder.remindTime).format 'M/D/YYYY hh:mm:ss a'
str += "#{reminder.todo} at #{displayTime}\n"
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, here are your unnotified reminders:" +
"\n\n#{str}")
handleMessage = (message, user, chatContext) ->
# Greeting.
if message.text is '/start'
sendGreeting message, user, chatContext
return
if message.text is '/help' or message.text is 'help'
sendHelp message
return
if message.text is '/feedback'
sendFeedback message, user, chatContext
return
if message.text is '/resetlocation'
sendResetLocation message, user, chatContext
return
if message.text is '/listreminders'
listReminders message, user
return
# Check answer by chatContext.status.
switch chatContext.status
when 'WAIT_LOCATION'
waitAndParseLocation message, user, chatContext
return
when 'WAIT_HRU'
bot.sendMessage
chat_id: message.chat.id
text: "So what can I do for you #{user.firstName}?"
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
return
when 'WAIT_CANCEL_REMINDER'
chatContext.status = null
chatContext.save (err) -> if err? then console.log err
if message.text?.toLowerCase() is 'cancel'
cancelReminder message, user
return
when 'WAIT_FEEDBACK'
maybeSaveFeedback message, user, chatContext
return
# Check location.
if not chatContext.status? and not user.location.lat?
askLocation message, user, chatContext
return
if not message?.text? then return
# Normalize.
normalizedText = message.text
normalizedText = normalizedText.replace /// ^[\W_]+ ///, ''
normalizedText = normalizedText.replace /// [\W_]+$ ///, ''
normalizedText = normalizedText.toLowerCase().replace /// \s+ ///, ' '
# Reminder mode.
if normalizedText.indexOf('remind') isnt -1
console.log 'Reminder mode'
if user.timezone?.dstOffset?
offset = user.timezone.dstOffset + user.timezone.rawOffset
else
offset = 0
offsetDate = moment().add(offset, 'seconds').toDate()
reminderParser.parse normalizedText, offsetDate, (err, res) ->
if err?
bot.sendMessage
chat_id: message.chat.id
text: ("#{user.firstName}, I'm not sure what you mean. " +
"Here are examples that I can better understand:\n " +
"\"Please remind me in 1 hour to check my email.\"\n" +
"\"PI:NAME:<NAME>END_PI, can you remind me to check my email next week?\"\n" +
"\"Remind me tomorrow noon to have lunch with PI:NAME:<NAME>END_PI.\"\n")
return
displayTime = moment(res.time).format 'M/D/YYYY hh:mm:ss a'
res.time = moment(res.time).add(-offset, 'seconds').toDate()
console.log "ReminderParser returns: #{JSON.stringify(res)}"
reminder = new Reminder
userId: user._id
message: message.text
remindTime: res.time
todo: res.todo
chatId: message.chat.id
reminder.saveWithAgenda user, (err) -> if err? then console.log err
confirm = utils.confirm user.firstName
bot.sendMessage
chat_id: message.chat.id
text: ("#{confirm} I'll remind you to #{res.todo} on #{displayTime}.\n" +
"(Reply \"cancel\" to remove this reminder.)")
chatContext.status = 'WAIT_CANCEL_REMINDER'
chatContext.save (err) -> if err? then console.log err
# General mode.
else
console.log 'General mode'
generalParser.parse normalizedText, user, (err, res) ->
if err?
console.log err
return
if res?
bot.sendMessage
chat_id: message.chat.id
text: res.answer
if res.id is 'hru'
chatContext.status = 'WAIT_HRU'
chatContext.save (err) -> if err? then console.log err
else
bot.sendMessage
chat_id: message.chat.id
text: utils.random user.firstName
return
module.exports =
handle: (message) ->
createUserIfNotPresent message, (user) ->
createChatContextIfNotPresent message, user, (chatContext) ->
handleMessage message, user, chatContext
|
[
{
"context": ")\n ```\n neo\n .createLabel(1, ['person', 'programmer'])\n ```\n ###\n createLabel: createLabe",
"end": 1134,
"score": 0.6129687428474426,
"start": 1127,
"tag": "NAME",
"value": "program"
},
{
"context": "s-on-a-node)\n ```\n neo\n .updateLab... | src/label.coffee | kievechua/js-neo4j | 2 | utils = require './utils'
_ = require 'lodash'
module.exports =
# ###Listing labels for a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-listing-labels-for-a-node)
```
neo.readLabel(1)
```
###
# ###List all labels
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-list-all-labels)
```
neo.readLabel()
```
###
readLabel: readLabel = (nodeId) ->
if nodeId
url = "#{@url}/db/data/node/#{nodeId}/labels"
else
url = "#{@url}/db/data/labels"
utils.get(url, (result) -> result.body)
rLabel: readLabel
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-a-label-to-a-node)
```
neo
.createLabel(1, 'person')
```
###
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-multiple-labels-to-a-node)
```
neo
.createLabel(1, ['person', 'programmer'])
```
###
createLabel: createLabel = (nodeId, label) ->
if _.isString label
label = label.match /[A-Za-z]+/
label = JSON.stringify(label[0])
else if _.isArray label
label = _.map label, (l) -> l.match(/[A-Za-z]+/)[0]
utils.post("#{@url}/db/data/node/#{nodeId}/labels", label, (result) -> result.ok)
cLabel: createLabel
# ###Replacing labels on a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.updateLabel(1, 'person')
```
###
updateLabel: updateLabel = (nodeId, labels) ->
unless _.isArray labels then throw new Error("Labels #{labels} must be array")
utils.put("#{@url}/db/data/node/#{nodeId}/labels", labels, (result) -> result.ok)
uLabel: updateLabel
# ###Removing a label from a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.deleteLabel(1, 'person')
```
###
deleteLabel: deleteLabel = (nodeId, label) ->
utils.del("#{@url}/db/data/node/#{nodeId}/labels/#{label}", (result) -> result.ok)
dLabel: deleteLabel
| 50323 | utils = require './utils'
_ = require 'lodash'
module.exports =
# ###Listing labels for a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-listing-labels-for-a-node)
```
neo.readLabel(1)
```
###
# ###List all labels
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-list-all-labels)
```
neo.readLabel()
```
###
readLabel: readLabel = (nodeId) ->
if nodeId
url = "#{@url}/db/data/node/#{nodeId}/labels"
else
url = "#{@url}/db/data/labels"
utils.get(url, (result) -> result.body)
rLabel: readLabel
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-a-label-to-a-node)
```
neo
.createLabel(1, 'person')
```
###
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-multiple-labels-to-a-node)
```
neo
.createLabel(1, ['person', '<NAME>mer'])
```
###
createLabel: createLabel = (nodeId, label) ->
if _.isString label
label = label.match /[A-Za-z]+/
label = JSON.stringify(label[0])
else if _.isArray label
label = _.map label, (l) -> l.match(/[A-Za-z]+/)[0]
utils.post("#{@url}/db/data/node/#{nodeId}/labels", label, (result) -> result.ok)
cLabel: createLabel
# ###Replacing labels on a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.updateLabel(1, 'person')
```
###
updateLabel: updateLabel = (nodeId, labels) ->
unless _.isArray labels then throw new Error("Labels #{labels} must be array")
utils.put("#{@url}/db/data/node/#{nodeId}/labels", labels, (result) -> result.ok)
uLabel: updateLabel
# ###Removing a label from a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.deleteLabel(1, 'person')
```
###
deleteLabel: deleteLabel = (nodeId, label) ->
utils.del("#{@url}/db/data/node/#{nodeId}/labels/#{label}", (result) -> result.ok)
dLabel: deleteLabel
| true | utils = require './utils'
_ = require 'lodash'
module.exports =
# ###Listing labels for a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-listing-labels-for-a-node)
```
neo.readLabel(1)
```
###
# ###List all labels
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-list-all-labels)
```
neo.readLabel()
```
###
readLabel: readLabel = (nodeId) ->
if nodeId
url = "#{@url}/db/data/node/#{nodeId}/labels"
else
url = "#{@url}/db/data/labels"
utils.get(url, (result) -> result.body)
rLabel: readLabel
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-a-label-to-a-node)
```
neo
.createLabel(1, 'person')
```
###
# ###Adding a label to a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-adding-multiple-labels-to-a-node)
```
neo
.createLabel(1, ['person', 'PI:NAME:<NAME>END_PImer'])
```
###
createLabel: createLabel = (nodeId, label) ->
if _.isString label
label = label.match /[A-Za-z]+/
label = JSON.stringify(label[0])
else if _.isArray label
label = _.map label, (l) -> l.match(/[A-Za-z]+/)[0]
utils.post("#{@url}/db/data/node/#{nodeId}/labels", label, (result) -> result.ok)
cLabel: createLabel
# ###Replacing labels on a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.updateLabel(1, 'person')
```
###
updateLabel: updateLabel = (nodeId, labels) ->
unless _.isArray labels then throw new Error("Labels #{labels} must be array")
utils.put("#{@url}/db/data/node/#{nodeId}/labels", labels, (result) -> result.ok)
uLabel: updateLabel
# ###Removing a label from a node
###
[Details](http://docs.neo4j.org/chunked/milestone/rest-api-node-labels.html#rest-api-replacing-labels-on-a-node)
```
neo
.deleteLabel(1, 'person')
```
###
deleteLabel: deleteLabel = (nodeId, label) ->
utils.del("#{@url}/db/data/node/#{nodeId}/labels/#{label}", (result) -> result.ok)
dLabel: deleteLabel
|
[
{
"context": "le migrations\n#\n# Nodize CMS\n# https://github.com/hypee/nodize\n#\n# Copyright 2012, Hypee\n# http://hypee.c",
"end": 113,
"score": 0.9995768070220947,
"start": 108,
"tag": "USERNAME",
"value": "hypee"
},
{
"context": "ttps://github.com/hypee/nodize\n#\n# Copyright 2... | modules/ionize/libs/nodize_db.coffee | nodize/nodizecms | 32 | # Nodize database management library
#
# Also used to handle migrations
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012, Hypee
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
sequelize = null
config = null
init = ->
if not sequelize
console.log "sequelize initialization"
Sequelize = require 'sequelize'
nconf = require 'nconf'
#
# Looking for specific settings for the current theme
#
fs = require 'fs'
#
# If we are in test mode, a specific database setting files must be defined
#
switch process.env.NODE_ENV
when 'test'
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.test.json'
else
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.json'
try
result = fs.statSync themeDatabaseSettingsFile
#
# Using theme's settings
#
databaseSettingsFile = themeDatabaseSettingsFile
catch error
#
# Using default's settings
#
databaseSettingsFile = 'settings/database.json'
#
# Retrieve database configuration from json setting file
#
nconf.add( 'config', {type: 'file', file:databaseSettingsFile } )
config = nconf
console.log "Using database settings from",databaseSettingsFile,"->",config.get('database')
# Connecting to the database
sequelize = new Sequelize( config.get('database'),config.get('user'), config.get('password'),
{
host: config.get('host')
port: if config.get('port') then config.get('port') else 3306
logging: config.get('logging')
dialect: config.get('dialect')
storage: global.__applicationPath+'/database/db.sqlite'
define: { timestamps: false, freezeTableName: true }
maxConcurrentQueries:50
pool: { maxConnections: 5, maxIdleTime : 30 }
}
)
#
# TableVersion definition
#
TableVersion = sequelize.define 'tableVersion',
name : Sequelize.STRING
version : Sequelize.INTEGER
#
# Create tableVersion if doesn't exists
#
sequelize.sync()
.error ->
console.log "nodize_db | Sync error"
.success ->
# Action to run once the "tableVersion" has been created
initializeTables( sequelize )
sequelize.TableVersion = TableVersion
#
# Migrations management
#
# Retrieving object to make low level database calls for migrations
queryInterface = sequelize.getMigrator().queryInterface
class Migrator
constructor: (table) ->
@table = table
setTable: (table) ->
@table = table
addColumn: (name, datatype) ->
# console.log "[#{@table}] adding column"
queryInterface.addColumn( @table, name, {type:datatype, allowNull : true} )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
removeColumn: (name) ->
# console.log "[#{@table}] removing column"
queryInterface.removeColumn( @table, name )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
doMigrations: (tableName, migrations ) ->
@table = tableName
#
# Search for table version
#
sequelize.TableVersion.find( { where:{'name':tableName} } )
.on "success", (tableVersion) ->
#
# Last element of "migrations" array has to be the last version
#
lastVersion = migrations[ migrations.length-1 ].version
if tableVersion
#
# We have a version for this table, we check if migration are needed
#
for migration in migrations
if lastVersion >= migration.version > tableVersion.version
console.log "[#{tableName}] applying upgrade to version #{migration.version}"
migration.code()
#
# Version update if needed
#
if tableVersion.version<lastVersion
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "[#{tableVersion.name}] updated to version ", tableVersion.version
.on 'failure', (err) ->
console.log "Database error", err
else
#
# No version found for this table, we expect to have the last version (just created)
#
tableVersion = TableVersion.build()
tableVersion.name = tableName
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "Table '#{tableVersion.name}' created, @version #{tableVersion.version}"
.on 'failure', (err) ->
console.log "Database error", err
.on "failure", (err) ->
console.log "fail", err
sequelize.migrator = new Migrator
sequelize.getMigrator = (tableName) ->
migrator = new Migrator( tableName )
initializeTables = (db) ->
global.DB = db
#
# Retrieve models
#
Article = db.import( __dirname + "/../models/model_article" )
Article_lang = db.import( __dirname + "/../models/model_articleLang" )
Article_media = db.import( __dirname + "/../models/model_articleMedia" )
Article_type = db.import( __dirname + "/../models/model_articleType" )
Article_category = db.import( __dirname + "/../models/model_articleCategory" )
Category = db.import( __dirname + "/../models/model_category" )
Category_lang = db.import( __dirname + "/../models/model_categoryLang" )
Lang = db.import( __dirname + "/../models/model_lang" )
Menu = db.import( __dirname + "/../models/model_menu" )
Media = db.import( __dirname + "/../models/model_media" )
Page = db.import( __dirname + "/../models/model_page" )
Page_article = db.import( __dirname + "/../models/model_pageArticle" )
Page_lang = db.import( __dirname + "/../models/model_pageLang" )
User = db.import( __dirname + "/../models/model_user" )
User_group = db.import( __dirname + "/../models/model_userGroup" )
#
# Run migrations
#
Article.migrate()
Article_category.migrate()
Article_lang.migrate()
Article_media.migrate()
Article_type.migrate()
Category.migrate()
Category_lang.migrate()
Lang.migrate()
Media.migrate()
Menu.migrate()
Page.migrate()
Page_article.migrate()
Page_lang.migrate()
User.migrate()
User_group.migrate()
#
# Associations, not used right now
# Seems to need an "id" field to work
#
Page.hasMany( Page_lang, {as:"Langs", foreignKey: 'id_page'} )
User.hasOne( User_group, {as:"Group", foreignKey: 'id_group'} )
#
# Remapping id fields, for compatibility w/ Ionize (www.ionizecms.com) database,
# we might break compatibily in later version to have cleaner DB structure
#
DB.query( "UPDATE page SET id = id_page" )
DB.query( "UPDATE menu SET id = id_menu")
#DB.query( "UPDATE article_lang SET id = id_article" )
#
# Give a global access to these DB objects
#
global.Article = Article
global.Article_lang = Article_lang
global.Article_media = Article_media
global.Article_type = Article_type
global.Article_category = Article_category
global.Category = Category
global.Category_lang = Category_lang
global.Lang = Lang
global.Menu = Menu
global.Media = Media
global.Page = Page
global.Page_lang = Page_lang
global.Page_article = Page_article
global.User = User
global.User_group = User_group
#
# Keeping a in-memory static array of langs,
# for simplicity & speed
#
updateStaticLangs = ->
Lang.findAll({order:'ordering'})
.on 'success', (langs) ->
global.Static_lang_default = lang.lang for lang in langs when lang.def is 1
global.Static_langs = (lang.lang for lang in langs)
global.Static_langs_records = langs
.on 'failure', (err) ->
console.log 'database error ', err
global.Static_langs = 'en'
global.Static_langs_records = ['en']
global.Static_lang_default = 'en'
#
# Creating a basic structure if the database is empty
#
initDatabase = ->
#
# Generating a simple random password
#
randomString = ->
#chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
chars = "0123456789AB"
string_length = 5;
randomString = '';
for i in [1..string_length]
rnum = Math.floor(Math.random() * chars.length)
randomString += chars.substring(rnum,rnum+1)
return randomString
#
# Create SuperAdmin group
#
createGroup = ->
user_group = User_group.build()
user_group.group_name = "SuperAdmin"
user_group.id_group = 1
user_group.level = 10000
user_group.save()
.on "success", (user_group)->
console.log "SuperAdmin group created"
createAdmin( user_group )
.on "failure", (err) ->
console.log "Error on group creation", err
#
# Creating admin user
#
createAdmin = (group) ->
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
password = randomString()
hash = hmac.update password
crypted = hash.digest(encoding="base64")
user = User.build()
user.username = "admin"
user.password = crypted
user.id_group = group.id_group
user.save()
.on "success", ->
console.log "Default user created, login = admin, password =", password
createLang()
.on "failure", (err) ->
console.log "Error on database initialization :", err
#
# Creating lang
#
createLang =->
lang = Lang.build()
lang.lang = "en"
lang.name = "English"
lang.online = 1
lang.def = 1
lang.ordering = 1
lang.save()
.on "success", ->
console.log "Default lang created"
updateStaticLangs()
createMenu()
#
# Creating menus
#
createMenu = ->
menu = Menu.build()
menu.title = "Main Menu"
menu.name = "main"
menu.ordering = 1
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
.on 'success', ->
console.log "Default menu created"
menu = Menu.build()
menu.title = "System"
menu.name = "system"
menu.ordering = 2
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
#
# Start process
#
createGroup()
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
#
# Langs have been modified, we rebuild the static array
#
.on 'langsUpdate', (message) ->
updateStaticLangs()
#
# Creating tables that doesn't exist in database
#
DB.sync()
.on "success", ->
User.count()
.on "success", (count)->
#
# Create default base records
#
if count is 0
initDatabase()
#
# Normal boot
#
else
updateStaticLangs()
.on "failure", (err) ->
console.log "Database synchronisation error :", err
init()
#console.log sequelize.getMigrator().queryInterface
module.exports = sequelize
exports.config = config
exports.boot = "BooYTa"
| 44854 | # Nodize database management library
#
# Also used to handle migrations
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012, <NAME>
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
sequelize = null
config = null
init = ->
if not sequelize
console.log "sequelize initialization"
Sequelize = require 'sequelize'
nconf = require 'nconf'
#
# Looking for specific settings for the current theme
#
fs = require 'fs'
#
# If we are in test mode, a specific database setting files must be defined
#
switch process.env.NODE_ENV
when 'test'
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.test.json'
else
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.json'
try
result = fs.statSync themeDatabaseSettingsFile
#
# Using theme's settings
#
databaseSettingsFile = themeDatabaseSettingsFile
catch error
#
# Using default's settings
#
databaseSettingsFile = 'settings/database.json'
#
# Retrieve database configuration from json setting file
#
nconf.add( 'config', {type: 'file', file:databaseSettingsFile } )
config = nconf
console.log "Using database settings from",databaseSettingsFile,"->",config.get('database')
# Connecting to the database
sequelize = new Sequelize( config.get('database'),config.get('user'), config.get('password'),
{
host: config.get('host')
port: if config.get('port') then config.get('port') else 3306
logging: config.get('logging')
dialect: config.get('dialect')
storage: global.__applicationPath+'/database/db.sqlite'
define: { timestamps: false, freezeTableName: true }
maxConcurrentQueries:50
pool: { maxConnections: 5, maxIdleTime : 30 }
}
)
#
# TableVersion definition
#
TableVersion = sequelize.define 'tableVersion',
name : Sequelize.STRING
version : Sequelize.INTEGER
#
# Create tableVersion if doesn't exists
#
sequelize.sync()
.error ->
console.log "nodize_db | Sync error"
.success ->
# Action to run once the "tableVersion" has been created
initializeTables( sequelize )
sequelize.TableVersion = TableVersion
#
# Migrations management
#
# Retrieving object to make low level database calls for migrations
queryInterface = sequelize.getMigrator().queryInterface
class Migrator
constructor: (table) ->
@table = table
setTable: (table) ->
@table = table
addColumn: (name, datatype) ->
# console.log "[#{@table}] adding column"
queryInterface.addColumn( @table, name, {type:datatype, allowNull : true} )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
removeColumn: (name) ->
# console.log "[#{@table}] removing column"
queryInterface.removeColumn( @table, name )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
doMigrations: (tableName, migrations ) ->
@table = tableName
#
# Search for table version
#
sequelize.TableVersion.find( { where:{'name':tableName} } )
.on "success", (tableVersion) ->
#
# Last element of "migrations" array has to be the last version
#
lastVersion = migrations[ migrations.length-1 ].version
if tableVersion
#
# We have a version for this table, we check if migration are needed
#
for migration in migrations
if lastVersion >= migration.version > tableVersion.version
console.log "[#{tableName}] applying upgrade to version #{migration.version}"
migration.code()
#
# Version update if needed
#
if tableVersion.version<lastVersion
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "[#{tableVersion.name}] updated to version ", tableVersion.version
.on 'failure', (err) ->
console.log "Database error", err
else
#
# No version found for this table, we expect to have the last version (just created)
#
tableVersion = TableVersion.build()
tableVersion.name = tableName
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "Table '#{tableVersion.name}' created, @version #{tableVersion.version}"
.on 'failure', (err) ->
console.log "Database error", err
.on "failure", (err) ->
console.log "fail", err
sequelize.migrator = new Migrator
sequelize.getMigrator = (tableName) ->
migrator = new Migrator( tableName )
initializeTables = (db) ->
global.DB = db
#
# Retrieve models
#
Article = db.import( __dirname + "/../models/model_article" )
Article_lang = db.import( __dirname + "/../models/model_articleLang" )
Article_media = db.import( __dirname + "/../models/model_articleMedia" )
Article_type = db.import( __dirname + "/../models/model_articleType" )
Article_category = db.import( __dirname + "/../models/model_articleCategory" )
Category = db.import( __dirname + "/../models/model_category" )
Category_lang = db.import( __dirname + "/../models/model_categoryLang" )
Lang = db.import( __dirname + "/../models/model_lang" )
Menu = db.import( __dirname + "/../models/model_menu" )
Media = db.import( __dirname + "/../models/model_media" )
Page = db.import( __dirname + "/../models/model_page" )
Page_article = db.import( __dirname + "/../models/model_pageArticle" )
Page_lang = db.import( __dirname + "/../models/model_pageLang" )
User = db.import( __dirname + "/../models/model_user" )
User_group = db.import( __dirname + "/../models/model_userGroup" )
#
# Run migrations
#
Article.migrate()
Article_category.migrate()
Article_lang.migrate()
Article_media.migrate()
Article_type.migrate()
Category.migrate()
Category_lang.migrate()
Lang.migrate()
Media.migrate()
Menu.migrate()
Page.migrate()
Page_article.migrate()
Page_lang.migrate()
User.migrate()
User_group.migrate()
#
# Associations, not used right now
# Seems to need an "id" field to work
#
Page.hasMany( Page_lang, {as:"Langs", foreignKey: 'id_page'} )
User.hasOne( User_group, {as:"Group", foreignKey: 'id_group'} )
#
# Remapping id fields, for compatibility w/ Ionize (www.ionizecms.com) database,
# we might break compatibily in later version to have cleaner DB structure
#
DB.query( "UPDATE page SET id = id_page" )
DB.query( "UPDATE menu SET id = id_menu")
#DB.query( "UPDATE article_lang SET id = id_article" )
#
# Give a global access to these DB objects
#
global.Article = Article
global.Article_lang = Article_lang
global.Article_media = Article_media
global.Article_type = Article_type
global.Article_category = Article_category
global.Category = Category
global.Category_lang = Category_lang
global.Lang = Lang
global.Menu = Menu
global.Media = Media
global.Page = Page
global.Page_lang = Page_lang
global.Page_article = Page_article
global.User = User
global.User_group = User_group
#
# Keeping a in-memory static array of langs,
# for simplicity & speed
#
updateStaticLangs = ->
Lang.findAll({order:'ordering'})
.on 'success', (langs) ->
global.Static_lang_default = lang.lang for lang in langs when lang.def is 1
global.Static_langs = (lang.lang for lang in langs)
global.Static_langs_records = langs
.on 'failure', (err) ->
console.log 'database error ', err
global.Static_langs = 'en'
global.Static_langs_records = ['en']
global.Static_lang_default = 'en'
#
# Creating a basic structure if the database is empty
#
initDatabase = ->
#
# Generating a simple random password
#
randomString = ->
#chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
chars = "0123456789AB"
string_length = 5;
randomString = '';
for i in [1..string_length]
rnum = Math.floor(Math.random() * chars.length)
randomString += chars.substring(rnum,rnum+1)
return randomString
#
# Create SuperAdmin group
#
createGroup = ->
user_group = User_group.build()
user_group.group_name = "SuperAdmin"
user_group.id_group = 1
user_group.level = 10000
user_group.save()
.on "success", (user_group)->
console.log "SuperAdmin group created"
createAdmin( user_group )
.on "failure", (err) ->
console.log "Error on group creation", err
#
# Creating admin user
#
createAdmin = (group) ->
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
password = <PASSWORD>()
hash = hmac.update password
crypted = hash.digest(encoding="base64")
user = User.build()
user.username = "admin"
user.password = <PASSWORD>
user.id_group = group.id_group
user.save()
.on "success", ->
console.log "Default user created, login = admin, password =", <PASSWORD>
createLang()
.on "failure", (err) ->
console.log "Error on database initialization :", err
#
# Creating lang
#
createLang =->
lang = Lang.build()
lang.lang = "en"
lang.name = "English"
lang.online = 1
lang.def = 1
lang.ordering = 1
lang.save()
.on "success", ->
console.log "Default lang created"
updateStaticLangs()
createMenu()
#
# Creating menus
#
createMenu = ->
menu = Menu.build()
menu.title = "Main Menu"
menu.name = "main"
menu.ordering = 1
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
.on 'success', ->
console.log "Default menu created"
menu = Menu.build()
menu.title = "System"
menu.name = "system"
menu.ordering = 2
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
#
# Start process
#
createGroup()
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
#
# Langs have been modified, we rebuild the static array
#
.on 'langsUpdate', (message) ->
updateStaticLangs()
#
# Creating tables that doesn't exist in database
#
DB.sync()
.on "success", ->
User.count()
.on "success", (count)->
#
# Create default base records
#
if count is 0
initDatabase()
#
# Normal boot
#
else
updateStaticLangs()
.on "failure", (err) ->
console.log "Database synchronisation error :", err
init()
#console.log sequelize.getMigrator().queryInterface
module.exports = sequelize
exports.config = config
exports.boot = "BooYTa"
| true | # Nodize database management library
#
# Also used to handle migrations
#
# Nodize CMS
# https://github.com/hypee/nodize
#
# Copyright 2012, PI:NAME:<NAME>END_PI
# http://hypee.com
#
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT
#
sequelize = null
config = null
init = ->
if not sequelize
console.log "sequelize initialization"
Sequelize = require 'sequelize'
nconf = require 'nconf'
#
# Looking for specific settings for the current theme
#
fs = require 'fs'
#
# If we are in test mode, a specific database setting files must be defined
#
switch process.env.NODE_ENV
when 'test'
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.test.json'
else
themeDatabaseSettingsFile = 'themes/'+__nodizeTheme+'/settings/database.json'
try
result = fs.statSync themeDatabaseSettingsFile
#
# Using theme's settings
#
databaseSettingsFile = themeDatabaseSettingsFile
catch error
#
# Using default's settings
#
databaseSettingsFile = 'settings/database.json'
#
# Retrieve database configuration from json setting file
#
nconf.add( 'config', {type: 'file', file:databaseSettingsFile } )
config = nconf
console.log "Using database settings from",databaseSettingsFile,"->",config.get('database')
# Connecting to the database
sequelize = new Sequelize( config.get('database'),config.get('user'), config.get('password'),
{
host: config.get('host')
port: if config.get('port') then config.get('port') else 3306
logging: config.get('logging')
dialect: config.get('dialect')
storage: global.__applicationPath+'/database/db.sqlite'
define: { timestamps: false, freezeTableName: true }
maxConcurrentQueries:50
pool: { maxConnections: 5, maxIdleTime : 30 }
}
)
#
# TableVersion definition
#
TableVersion = sequelize.define 'tableVersion',
name : Sequelize.STRING
version : Sequelize.INTEGER
#
# Create tableVersion if doesn't exists
#
sequelize.sync()
.error ->
console.log "nodize_db | Sync error"
.success ->
# Action to run once the "tableVersion" has been created
initializeTables( sequelize )
sequelize.TableVersion = TableVersion
#
# Migrations management
#
# Retrieving object to make low level database calls for migrations
queryInterface = sequelize.getMigrator().queryInterface
class Migrator
constructor: (table) ->
@table = table
setTable: (table) ->
@table = table
addColumn: (name, datatype) ->
# console.log "[#{@table}] adding column"
queryInterface.addColumn( @table, name, {type:datatype, allowNull : true} )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
removeColumn: (name) ->
# console.log "[#{@table}] removing column"
queryInterface.removeColumn( @table, name )
# .on 'success', ->
# console.log "success"
.on 'failure', (err) ->
console.log "error", err
doMigrations: (tableName, migrations ) ->
@table = tableName
#
# Search for table version
#
sequelize.TableVersion.find( { where:{'name':tableName} } )
.on "success", (tableVersion) ->
#
# Last element of "migrations" array has to be the last version
#
lastVersion = migrations[ migrations.length-1 ].version
if tableVersion
#
# We have a version for this table, we check if migration are needed
#
for migration in migrations
if lastVersion >= migration.version > tableVersion.version
console.log "[#{tableName}] applying upgrade to version #{migration.version}"
migration.code()
#
# Version update if needed
#
if tableVersion.version<lastVersion
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "[#{tableVersion.name}] updated to version ", tableVersion.version
.on 'failure', (err) ->
console.log "Database error", err
else
#
# No version found for this table, we expect to have the last version (just created)
#
tableVersion = TableVersion.build()
tableVersion.name = tableName
tableVersion.version = lastVersion
tableVersion.save()
.on 'success', (tableVersion) ->
console.log "Table '#{tableVersion.name}' created, @version #{tableVersion.version}"
.on 'failure', (err) ->
console.log "Database error", err
.on "failure", (err) ->
console.log "fail", err
sequelize.migrator = new Migrator
sequelize.getMigrator = (tableName) ->
migrator = new Migrator( tableName )
initializeTables = (db) ->
global.DB = db
#
# Retrieve models
#
Article = db.import( __dirname + "/../models/model_article" )
Article_lang = db.import( __dirname + "/../models/model_articleLang" )
Article_media = db.import( __dirname + "/../models/model_articleMedia" )
Article_type = db.import( __dirname + "/../models/model_articleType" )
Article_category = db.import( __dirname + "/../models/model_articleCategory" )
Category = db.import( __dirname + "/../models/model_category" )
Category_lang = db.import( __dirname + "/../models/model_categoryLang" )
Lang = db.import( __dirname + "/../models/model_lang" )
Menu = db.import( __dirname + "/../models/model_menu" )
Media = db.import( __dirname + "/../models/model_media" )
Page = db.import( __dirname + "/../models/model_page" )
Page_article = db.import( __dirname + "/../models/model_pageArticle" )
Page_lang = db.import( __dirname + "/../models/model_pageLang" )
User = db.import( __dirname + "/../models/model_user" )
User_group = db.import( __dirname + "/../models/model_userGroup" )
#
# Run migrations
#
Article.migrate()
Article_category.migrate()
Article_lang.migrate()
Article_media.migrate()
Article_type.migrate()
Category.migrate()
Category_lang.migrate()
Lang.migrate()
Media.migrate()
Menu.migrate()
Page.migrate()
Page_article.migrate()
Page_lang.migrate()
User.migrate()
User_group.migrate()
#
# Associations, not used right now
# Seems to need an "id" field to work
#
Page.hasMany( Page_lang, {as:"Langs", foreignKey: 'id_page'} )
User.hasOne( User_group, {as:"Group", foreignKey: 'id_group'} )
#
# Remapping id fields, for compatibility w/ Ionize (www.ionizecms.com) database,
# we might break compatibily in later version to have cleaner DB structure
#
DB.query( "UPDATE page SET id = id_page" )
DB.query( "UPDATE menu SET id = id_menu")
#DB.query( "UPDATE article_lang SET id = id_article" )
#
# Give a global access to these DB objects
#
global.Article = Article
global.Article_lang = Article_lang
global.Article_media = Article_media
global.Article_type = Article_type
global.Article_category = Article_category
global.Category = Category
global.Category_lang = Category_lang
global.Lang = Lang
global.Menu = Menu
global.Media = Media
global.Page = Page
global.Page_lang = Page_lang
global.Page_article = Page_article
global.User = User
global.User_group = User_group
#
# Keeping a in-memory static array of langs,
# for simplicity & speed
#
updateStaticLangs = ->
Lang.findAll({order:'ordering'})
.on 'success', (langs) ->
global.Static_lang_default = lang.lang for lang in langs when lang.def is 1
global.Static_langs = (lang.lang for lang in langs)
global.Static_langs_records = langs
.on 'failure', (err) ->
console.log 'database error ', err
global.Static_langs = 'en'
global.Static_langs_records = ['en']
global.Static_lang_default = 'en'
#
# Creating a basic structure if the database is empty
#
initDatabase = ->
#
# Generating a simple random password
#
randomString = ->
#chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz"
chars = "0123456789AB"
string_length = 5;
randomString = '';
for i in [1..string_length]
rnum = Math.floor(Math.random() * chars.length)
randomString += chars.substring(rnum,rnum+1)
return randomString
#
# Create SuperAdmin group
#
createGroup = ->
user_group = User_group.build()
user_group.group_name = "SuperAdmin"
user_group.id_group = 1
user_group.level = 10000
user_group.save()
.on "success", (user_group)->
console.log "SuperAdmin group created"
createAdmin( user_group )
.on "failure", (err) ->
console.log "Error on group creation", err
#
# Creating admin user
#
createAdmin = (group) ->
crypto = require "crypto"
hmac = crypto.createHmac("sha1", __sessionSecret)
password = PI:PASSWORD:<PASSWORD>END_PI()
hash = hmac.update password
crypted = hash.digest(encoding="base64")
user = User.build()
user.username = "admin"
user.password = PI:PASSWORD:<PASSWORD>END_PI
user.id_group = group.id_group
user.save()
.on "success", ->
console.log "Default user created, login = admin, password =", PI:PASSWORD:<PASSWORD>END_PI
createLang()
.on "failure", (err) ->
console.log "Error on database initialization :", err
#
# Creating lang
#
createLang =->
lang = Lang.build()
lang.lang = "en"
lang.name = "English"
lang.online = 1
lang.def = 1
lang.ordering = 1
lang.save()
.on "success", ->
console.log "Default lang created"
updateStaticLangs()
createMenu()
#
# Creating menus
#
createMenu = ->
menu = Menu.build()
menu.title = "Main Menu"
menu.name = "main"
menu.ordering = 1
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
.on 'success', ->
console.log "Default menu created"
menu = Menu.build()
menu.title = "System"
menu.name = "system"
menu.ordering = 2
menu.save()
.on "success", (menu) ->
menu.id_menu = menu.id
menu.save()
#
# Start process
#
createGroup()
# ---------------------------
# EVENTS
#
__nodizeEvents
#
# Page has been updated, we could store pages in a static JSON array
# TODO: should probably be in backend module
#
.on 'pageSave', (message)->
#console.log( "PageSave event in mod_ionize -> ", message )
return
#
# Langs have been modified, we rebuild the static array
#
.on 'langsUpdate', (message) ->
updateStaticLangs()
#
# Creating tables that doesn't exist in database
#
DB.sync()
.on "success", ->
User.count()
.on "success", (count)->
#
# Create default base records
#
if count is 0
initDatabase()
#
# Normal boot
#
else
updateStaticLangs()
.on "failure", (err) ->
console.log "Database synchronisation error :", err
init()
#console.log sequelize.getMigrator().queryInterface
module.exports = sequelize
exports.config = config
exports.boot = "BooYTa"
|
[
{
"context": "plicit default role property on element.\n# @author Ethan Cohen <@evcohen>\n###\n\n# -------------------------------",
"end": 161,
"score": 0.9998894333839417,
"start": 150,
"tag": "NAME",
"value": "Ethan Cohen"
},
{
"context": " role property on element.\n# @author Eth... | src/tests/rules/no-redundant-roles.coffee | danielbayley/eslint-plugin-coffee | 21 | ### eslint-env jest ###
###*
# @fileoverview Enforce explicit role property is not the
# same as implicit default role property on element.
# @author Ethan Cohen <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-redundant-roles'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError = (element, implicitRole) ->
message: "The element #{element} has an implicit role of #{implicitRole}. Defining this explicitly is redundant and should be avoided."
type: 'JSXOpeningElement'
ruleName = 'jsx-a11y/no-redundant-roles'
alwaysValid = [
code: '<div />'
,
code: '<button role="main" />'
,
code: '<MyComponent role="button" />'
,
code: '<button role={"#{foo}button"} />'
]
neverValid = [
code: '<button role="button" />', errors: [expectedError 'button', 'button']
,
code: '<body role="DOCUMENT" />', errors: [expectedError 'body', 'document']
]
ruleTester.run "#{ruleName}:recommended", rule,
valid: [...alwaysValid, {code: '<nav role="navigation" />'}].map(
parserOptionsMapper
)
invalid: neverValid.map parserOptionsMapper
noNavExceptionsOptions = nav: []
ruleTester.run "#{ruleName}:recommended", rule,
valid:
alwaysValid
.map(ruleOptionsMapperFactory noNavExceptionsOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
code: '<nav role="navigation" />'
errors: [expectedError 'nav', 'navigation']
]
.map ruleOptionsMapperFactory noNavExceptionsOptions
.map parserOptionsMapper
| 212330 | ### eslint-env jest ###
###*
# @fileoverview Enforce explicit role property is not the
# same as implicit default role property on element.
# @author <NAME> <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-redundant-roles'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError = (element, implicitRole) ->
message: "The element #{element} has an implicit role of #{implicitRole}. Defining this explicitly is redundant and should be avoided."
type: 'JSXOpeningElement'
ruleName = 'jsx-a11y/no-redundant-roles'
alwaysValid = [
code: '<div />'
,
code: '<button role="main" />'
,
code: '<MyComponent role="button" />'
,
code: '<button role={"#{foo}button"} />'
]
neverValid = [
code: '<button role="button" />', errors: [expectedError 'button', 'button']
,
code: '<body role="DOCUMENT" />', errors: [expectedError 'body', 'document']
]
ruleTester.run "#{ruleName}:recommended", rule,
valid: [...alwaysValid, {code: '<nav role="navigation" />'}].map(
parserOptionsMapper
)
invalid: neverValid.map parserOptionsMapper
noNavExceptionsOptions = nav: []
ruleTester.run "#{ruleName}:recommended", rule,
valid:
alwaysValid
.map(ruleOptionsMapperFactory noNavExceptionsOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
code: '<nav role="navigation" />'
errors: [expectedError 'nav', 'navigation']
]
.map ruleOptionsMapperFactory noNavExceptionsOptions
.map parserOptionsMapper
| true | ### eslint-env jest ###
###*
# @fileoverview Enforce explicit role property is not the
# same as implicit default role property on element.
# @author PI:NAME:<NAME>END_PI <@evcohen>
###
# -----------------------------------------------------------------------------
# Requirements
# -----------------------------------------------------------------------------
path = require 'path'
{RuleTester} = require 'eslint'
{
default: parserOptionsMapper
} = require '../eslint-plugin-jsx-a11y-parser-options-mapper'
rule = require 'eslint-plugin-jsx-a11y/lib/rules/no-redundant-roles'
{
default: ruleOptionsMapperFactory
} = require '../eslint-plugin-jsx-a11y-rule-options-mapper-factory'
# -----------------------------------------------------------------------------
# Tests
# -----------------------------------------------------------------------------
### eslint-disable coffee/no-template-curly-in-string ###
ruleTester = new RuleTester parser: path.join __dirname, '../../..'
expectedError = (element, implicitRole) ->
message: "The element #{element} has an implicit role of #{implicitRole}. Defining this explicitly is redundant and should be avoided."
type: 'JSXOpeningElement'
ruleName = 'jsx-a11y/no-redundant-roles'
alwaysValid = [
code: '<div />'
,
code: '<button role="main" />'
,
code: '<MyComponent role="button" />'
,
code: '<button role={"#{foo}button"} />'
]
neverValid = [
code: '<button role="button" />', errors: [expectedError 'button', 'button']
,
code: '<body role="DOCUMENT" />', errors: [expectedError 'body', 'document']
]
ruleTester.run "#{ruleName}:recommended", rule,
valid: [...alwaysValid, {code: '<nav role="navigation" />'}].map(
parserOptionsMapper
)
invalid: neverValid.map parserOptionsMapper
noNavExceptionsOptions = nav: []
ruleTester.run "#{ruleName}:recommended", rule,
valid:
alwaysValid
.map(ruleOptionsMapperFactory noNavExceptionsOptions)
.map(parserOptionsMapper)
invalid:
[
...neverValid
,
code: '<nav role="navigation" />'
errors: [expectedError 'nav', 'navigation']
]
.map ruleOptionsMapperFactory noNavExceptionsOptions
.map parserOptionsMapper
|
[
{
"context": "ess:\n type: 'string'\n default: '192.168.1.1'\n rokuUserId:\n type: 'string'\n ",
"end": 531,
"score": 0.9997105002403259,
"start": 520,
"tag": "IP_ADDRESS",
"value": "192.168.1.1"
},
{
"context": "rId:\n type: 'string'\n ... | lib/roku-deploy.coffee | briandunnington/roku-deploy | 0 | RokuDeployView = require './roku-deploy-view'
{CompositeDisposable} = require 'atom'
fs = require 'fs'
Archiver = require 'archiver'
request = require 'request'
module.exports = RokuDeploy =
rokuDeployView: null
modalPanel: null
subscriptions: null
rokuAddress: null
rokuPassword: null
rokuUserId: null
excludedPaths: null
outputDirectory: null
srcDirectory: null
separator: if process.platform != 'win32' then '/' else '\\'
config:
rokuAddress:
type: 'string'
default: '192.168.1.1'
rokuUserId:
type: 'string'
default: 'rokudev'
rokuPassword:
type: 'string'
default: '1111'
excludedPaths:
type: 'string'
default: 'out'
outputDirectory:
type: 'string'
default: 'out'
srcDirectory:
type: 'string'
default: '.'
activate: (state) ->
@rokuDeployView = new RokuDeployView(state.rokuDeployViewState)
@modalPanel = atom.workspace.addModalPanel(item: @rokuDeployView.getElement(), visible: false)
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deply.srcDirectory')
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
console.log 'roku-deploy activated'
# Register command that shows this view
@subscriptions.add atom.commands.add 'atom-workspace', 'roku-deploy:deployRoku': => @deployRoku()
deactivate: ->
@modalPanel.destroy()
@subscriptions.dispose()
@rokuDeployView.destroy()
serialize: ->
rokuDeployViewState: @rokuDeployView.serialize()
addToZip: (dir) ->
console.log dir.getRealPathSync()
@zip.directory dir.getRealPathSync(), dir.getBaseName()
zipPackage: ->
console.log 'zipPackage called.'
request.post('http://' + module.exports.rokuAddress + ':8060/keypress/Home').on('response', (response)->
if response != undefined
console.log "Response returned"
if response != undefined && response.statusCode != undefined && response.statusCode == 200
console.log "Response returned 200"
module.exports.zipCore()
else
atom.notifications.addError('Sending Home command did not succeed. See console for details.')
if response != undefined
console.log response.body
else
console.log "No response returned."
)
zipCore: ->
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
if(dir!=undefined)
p = dir.getRealPathSync()
bundlePath = p + @separator + @outputDirectory + @separator
try
stat = fs.lstatSync(bundlePath)
catch error
console.log 'out directory not found, creating.'
fs.mkdirSync(bundlePath)
stat = fs.lstatSync(bundlePath)
if(not stat.isDirectory())
console.log 'failed to create out directory.'
return
zipFile = fs.createWriteStream(bundlePath+'bundle.zip')
@zip = Archiver('zip')
zipFile.on('close',@zipComplete)
@zip.on('error',(err) -> throw err)
@zip.pipe(zipFile)
splitExcludedPaths = @excludedPaths.split(',')
upperExcludedPaths = []
splitExcludedPaths.forEach (ep) -> upperExcludedPaths.push(ep.trim().toLocaleUpperCase())
@addToZip directory for directory in dir.getEntriesSync() when directory.isDirectory() and upperExcludedPaths.indexOf(directory.getBaseName().toLocaleUpperCase()) == -1 and not directory.getBaseName().startsWith('.')
params = {expand: true, cwd: dir.getRealPathSync(), src: ['manifest'],dest:''}
@zip.bulk params
@zip.finalize()
zipComplete: ->
console.log "Zipping complete"
atom.notifications.addInfo("Bundling completed. Starting deploy . . .")
addrs = 'http://'+ module.exports.rokuAddress + '/plugin_install'
console.log addrs
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
p = dir.getRealPathSync()
bundlePath = p + module.exports.separator + module.exports.outputDirectory + module.exports.separator
rokuOptions =
url : addrs
formData :
mysubmit : 'Replace'
archive : fs.createReadStream(bundlePath+'bundle.zip')
request.post(rokuOptions,module.exports.requestCallback).auth(module.exports.rokuUserId,module.exports.rokuPassword,false)
console.log 'Request started'
requestCallback: (error,response,body) ->
if response != undefined && response.statusCode != undefined && response.statusCode == 200
if response.body.indexOf("Identical to previous version -- not replacing.") != -1
atom.notifications.addWarning("Deploy cancelled by Roku: the package is identical to the package already on the Roku.")
else
console.log "Successfully deployed"
atom.notifications.addSuccess('Deployed to '+module.exports.rokuAddress)
else
atom.notifications.addFatalError("Failed to deploy to " + module.exports.rokuAddress + " see console output for details.")
console.log error
if response != undefined
console.log response.body
setRokuAddress: (address, userId,pwd)->
module.exports.rokuAddress = address
module.exports.rokuUserId = userId
moduel.exports.rokuPassword = pwd
# Diplay input for setting roku address
deployRoku: ->
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deploy.srcDirectory')
@zipPackage()
| 295 | RokuDeployView = require './roku-deploy-view'
{CompositeDisposable} = require 'atom'
fs = require 'fs'
Archiver = require 'archiver'
request = require 'request'
module.exports = RokuDeploy =
rokuDeployView: null
modalPanel: null
subscriptions: null
rokuAddress: null
rokuPassword: null
rokuUserId: null
excludedPaths: null
outputDirectory: null
srcDirectory: null
separator: if process.platform != 'win32' then '/' else '\\'
config:
rokuAddress:
type: 'string'
default: '192.168.1.1'
rokuUserId:
type: 'string'
default: 'rokudev'
rokuPassword:
type: 'string'
default: '<PASSWORD>'
excludedPaths:
type: 'string'
default: 'out'
outputDirectory:
type: 'string'
default: 'out'
srcDirectory:
type: 'string'
default: '.'
activate: (state) ->
@rokuDeployView = new RokuDeployView(state.rokuDeployViewState)
@modalPanel = atom.workspace.addModalPanel(item: @rokuDeployView.getElement(), visible: false)
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deply.srcDirectory')
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
console.log 'roku-deploy activated'
# Register command that shows this view
@subscriptions.add atom.commands.add 'atom-workspace', 'roku-deploy:deployRoku': => @deployRoku()
deactivate: ->
@modalPanel.destroy()
@subscriptions.dispose()
@rokuDeployView.destroy()
serialize: ->
rokuDeployViewState: @rokuDeployView.serialize()
addToZip: (dir) ->
console.log dir.getRealPathSync()
@zip.directory dir.getRealPathSync(), dir.getBaseName()
zipPackage: ->
console.log 'zipPackage called.'
request.post('http://' + module.exports.rokuAddress + ':8060/keypress/Home').on('response', (response)->
if response != undefined
console.log "Response returned"
if response != undefined && response.statusCode != undefined && response.statusCode == 200
console.log "Response returned 200"
module.exports.zipCore()
else
atom.notifications.addError('Sending Home command did not succeed. See console for details.')
if response != undefined
console.log response.body
else
console.log "No response returned."
)
zipCore: ->
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
if(dir!=undefined)
p = dir.getRealPathSync()
bundlePath = p + @separator + @outputDirectory + @separator
try
stat = fs.lstatSync(bundlePath)
catch error
console.log 'out directory not found, creating.'
fs.mkdirSync(bundlePath)
stat = fs.lstatSync(bundlePath)
if(not stat.isDirectory())
console.log 'failed to create out directory.'
return
zipFile = fs.createWriteStream(bundlePath+'bundle.zip')
@zip = Archiver('zip')
zipFile.on('close',@zipComplete)
@zip.on('error',(err) -> throw err)
@zip.pipe(zipFile)
splitExcludedPaths = @excludedPaths.split(',')
upperExcludedPaths = []
splitExcludedPaths.forEach (ep) -> upperExcludedPaths.push(ep.trim().toLocaleUpperCase())
@addToZip directory for directory in dir.getEntriesSync() when directory.isDirectory() and upperExcludedPaths.indexOf(directory.getBaseName().toLocaleUpperCase()) == -1 and not directory.getBaseName().startsWith('.')
params = {expand: true, cwd: dir.getRealPathSync(), src: ['manifest'],dest:''}
@zip.bulk params
@zip.finalize()
zipComplete: ->
console.log "Zipping complete"
atom.notifications.addInfo("Bundling completed. Starting deploy . . .")
addrs = 'http://'+ module.exports.rokuAddress + '/plugin_install'
console.log addrs
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
p = dir.getRealPathSync()
bundlePath = p + module.exports.separator + module.exports.outputDirectory + module.exports.separator
rokuOptions =
url : addrs
formData :
mysubmit : 'Replace'
archive : fs.createReadStream(bundlePath+'bundle.zip')
request.post(rokuOptions,module.exports.requestCallback).auth(module.exports.rokuUserId,module.exports.rokuPassword,false)
console.log 'Request started'
requestCallback: (error,response,body) ->
if response != undefined && response.statusCode != undefined && response.statusCode == 200
if response.body.indexOf("Identical to previous version -- not replacing.") != -1
atom.notifications.addWarning("Deploy cancelled by Roku: the package is identical to the package already on the Roku.")
else
console.log "Successfully deployed"
atom.notifications.addSuccess('Deployed to '+module.exports.rokuAddress)
else
atom.notifications.addFatalError("Failed to deploy to " + module.exports.rokuAddress + " see console output for details.")
console.log error
if response != undefined
console.log response.body
setRokuAddress: (address, userId,pwd)->
module.exports.rokuAddress = address
module.exports.rokuUserId = userId
moduel.exports.rokuPassword = <PASSWORD>
# Diplay input for setting roku address
deployRoku: ->
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deploy.srcDirectory')
@zipPackage()
| true | RokuDeployView = require './roku-deploy-view'
{CompositeDisposable} = require 'atom'
fs = require 'fs'
Archiver = require 'archiver'
request = require 'request'
module.exports = RokuDeploy =
rokuDeployView: null
modalPanel: null
subscriptions: null
rokuAddress: null
rokuPassword: null
rokuUserId: null
excludedPaths: null
outputDirectory: null
srcDirectory: null
separator: if process.platform != 'win32' then '/' else '\\'
config:
rokuAddress:
type: 'string'
default: '192.168.1.1'
rokuUserId:
type: 'string'
default: 'rokudev'
rokuPassword:
type: 'string'
default: 'PI:PASSWORD:<PASSWORD>END_PI'
excludedPaths:
type: 'string'
default: 'out'
outputDirectory:
type: 'string'
default: 'out'
srcDirectory:
type: 'string'
default: '.'
activate: (state) ->
@rokuDeployView = new RokuDeployView(state.rokuDeployViewState)
@modalPanel = atom.workspace.addModalPanel(item: @rokuDeployView.getElement(), visible: false)
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deply.srcDirectory')
# Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable
@subscriptions = new CompositeDisposable
console.log 'roku-deploy activated'
# Register command that shows this view
@subscriptions.add atom.commands.add 'atom-workspace', 'roku-deploy:deployRoku': => @deployRoku()
deactivate: ->
@modalPanel.destroy()
@subscriptions.dispose()
@rokuDeployView.destroy()
serialize: ->
rokuDeployViewState: @rokuDeployView.serialize()
addToZip: (dir) ->
console.log dir.getRealPathSync()
@zip.directory dir.getRealPathSync(), dir.getBaseName()
zipPackage: ->
console.log 'zipPackage called.'
request.post('http://' + module.exports.rokuAddress + ':8060/keypress/Home').on('response', (response)->
if response != undefined
console.log "Response returned"
if response != undefined && response.statusCode != undefined && response.statusCode == 200
console.log "Response returned 200"
module.exports.zipCore()
else
atom.notifications.addError('Sending Home command did not succeed. See console for details.')
if response != undefined
console.log response.body
else
console.log "No response returned."
)
zipCore: ->
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
if(dir!=undefined)
p = dir.getRealPathSync()
bundlePath = p + @separator + @outputDirectory + @separator
try
stat = fs.lstatSync(bundlePath)
catch error
console.log 'out directory not found, creating.'
fs.mkdirSync(bundlePath)
stat = fs.lstatSync(bundlePath)
if(not stat.isDirectory())
console.log 'failed to create out directory.'
return
zipFile = fs.createWriteStream(bundlePath+'bundle.zip')
@zip = Archiver('zip')
zipFile.on('close',@zipComplete)
@zip.on('error',(err) -> throw err)
@zip.pipe(zipFile)
splitExcludedPaths = @excludedPaths.split(',')
upperExcludedPaths = []
splitExcludedPaths.forEach (ep) -> upperExcludedPaths.push(ep.trim().toLocaleUpperCase())
@addToZip directory for directory in dir.getEntriesSync() when directory.isDirectory() and upperExcludedPaths.indexOf(directory.getBaseName().toLocaleUpperCase()) == -1 and not directory.getBaseName().startsWith('.')
params = {expand: true, cwd: dir.getRealPathSync(), src: ['manifest'],dest:''}
@zip.bulk params
@zip.finalize()
zipComplete: ->
console.log "Zipping complete"
atom.notifications.addInfo("Bundling completed. Starting deploy . . .")
addrs = 'http://'+ module.exports.rokuAddress + '/plugin_install'
console.log addrs
dirs = atom.project.getDirectories()
dir = dirs[0].getSubdirectory(module.exports.srcDirectory)
p = dir.getRealPathSync()
bundlePath = p + module.exports.separator + module.exports.outputDirectory + module.exports.separator
rokuOptions =
url : addrs
formData :
mysubmit : 'Replace'
archive : fs.createReadStream(bundlePath+'bundle.zip')
request.post(rokuOptions,module.exports.requestCallback).auth(module.exports.rokuUserId,module.exports.rokuPassword,false)
console.log 'Request started'
requestCallback: (error,response,body) ->
if response != undefined && response.statusCode != undefined && response.statusCode == 200
if response.body.indexOf("Identical to previous version -- not replacing.") != -1
atom.notifications.addWarning("Deploy cancelled by Roku: the package is identical to the package already on the Roku.")
else
console.log "Successfully deployed"
atom.notifications.addSuccess('Deployed to '+module.exports.rokuAddress)
else
atom.notifications.addFatalError("Failed to deploy to " + module.exports.rokuAddress + " see console output for details.")
console.log error
if response != undefined
console.log response.body
setRokuAddress: (address, userId,pwd)->
module.exports.rokuAddress = address
module.exports.rokuUserId = userId
moduel.exports.rokuPassword = PI:PASSWORD:<PASSWORD>END_PI
# Diplay input for setting roku address
deployRoku: ->
@rokuAddress = atom.config.get('roku-deploy.rokuAddress')
@rokuUserId = atom.config.get('roku-deploy.rokuUserId')
@rokuPassword = atom.config.get('roku-deploy.rokuPassword')
@excludedPaths = atom.config.get('roku-deploy.excludedPaths')
@outputDirectory = atom.config.get('roku-deploy.outputDirectory')
@srcDirectory = atom.config.get('roku-deploy.srcDirectory')
@zipPackage()
|
[
{
"context": "###\n backbone-orm.js 0.5.12\n Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm\n Lice",
"end": 58,
"score": 0.9993396401405334,
"start": 50,
"tag": "NAME",
"value": "Vidigami"
},
{
"context": " Copyright (c) 2013 Vidigami - https://github.com/v... | src/node/model_type_id.coffee | michaelBenin/backbone-orm | 1 | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 Vidigami - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
crypto = require 'crypto'
# @private
module.exports = class ModelTypeID
constructor: ->
@enabled = false
@ids = {}
configure: (options={}) =>
@enabled = options.enabled
return @
reset: =>
@ids = {}
return @
modelID: (model_type) =>
try url = _.result(new model_type, 'url') catch e
name_url = "#{url or ''}_#{model_type.model_name}"
return crypto.createHash('md5').update(name_url).digest('hex')
generate: (model_type) =>
unless id = model_type.model_type_id # manual setting
id = @modelID(model_type)
if @enabled and @ids[id] and @ids[id] isnt model_type
throw new Error("Duplicate model name / url combination: #{model_type.model_name}, #{_.result(new model_type, 'url')}. Set a unique model_name property on one of the conflicting models.")
@ids[id] = model_type
return id
| 125081 | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 <NAME> - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
crypto = require 'crypto'
# @private
module.exports = class ModelTypeID
constructor: ->
@enabled = false
@ids = {}
configure: (options={}) =>
@enabled = options.enabled
return @
reset: =>
@ids = {}
return @
modelID: (model_type) =>
try url = _.result(new model_type, 'url') catch e
name_url = "#{url or ''}_#{model_type.model_name}"
return crypto.createHash('md5').update(name_url).digest('hex')
generate: (model_type) =>
unless id = model_type.model_type_id # manual setting
id = @modelID(model_type)
if @enabled and @ids[id] and @ids[id] isnt model_type
throw new Error("Duplicate model name / url combination: #{model_type.model_name}, #{_.result(new model_type, 'url')}. Set a unique model_name property on one of the conflicting models.")
@ids[id] = model_type
return id
| true | ###
backbone-orm.js 0.5.12
Copyright (c) 2013 PI:NAME:<NAME>END_PI - https://github.com/vidigami/backbone-orm
License: MIT (http://www.opensource.org/licenses/mit-license.php)
Dependencies: Backbone.js, Underscore.js, and Moment.js.
###
_ = require 'underscore'
crypto = require 'crypto'
# @private
module.exports = class ModelTypeID
constructor: ->
@enabled = false
@ids = {}
configure: (options={}) =>
@enabled = options.enabled
return @
reset: =>
@ids = {}
return @
modelID: (model_type) =>
try url = _.result(new model_type, 'url') catch e
name_url = "#{url or ''}_#{model_type.model_name}"
return crypto.createHash('md5').update(name_url).digest('hex')
generate: (model_type) =>
unless id = model_type.model_type_id # manual setting
id = @modelID(model_type)
if @enabled and @ids[id] and @ids[id] isnt model_type
throw new Error("Duplicate model name / url combination: #{model_type.model_name}, #{_.result(new model_type, 'url')}. Set a unique model_name property on one of the conflicting models.")
@ids[id] = model_type
return id
|
[
{
"context": "erwriteExisting\n\n\t\t\t\t\tattributes: [\n\t\t\t\t\t\t{ key: \"name\", type: \"string\", required: true }\n\t\t\t\t\t\t{ key: \"",
"end": 308,
"score": 0.8066259026527405,
"start": 304,
"tag": "NAME",
"value": "name"
},
{
"context": "erwriteExisting\n\n\t\t\t\t\tattri... | config.coffee | mpneuried/simple-dynamo | 1 | CONFIG =
"_BASIC":
server:
port: 3000
host: null
aws:
accessKeyId: "-"
secretAccessKey: "-"
dynamo:
region: "eu-west-1"
tables:
"User":
name: "users"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "name", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Users":
name: "u"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "name", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Rooms":
name: "r"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
attributes: [
{ key: "name", type: "string", required: true }
{ key: "users", type: "array" }
{ key: "foo", type: "array" }
]
"Messages":
name: "messages"
hashKey: "user_id"
rangeKey: "_t"
rangeKeyType: "N"
attributes: [
{ key: "_t", type: "number" }
, { key: "lastlogin", type: "number" }
]
"mt":
name: "many"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs1":
name: "test_log1"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs2":
name: "test_log2"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs1":
name: "test_log1"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs2":
name: "test_log2"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"c_mt":
name: "cmt"
hashKey: "id"
hashKeyType: "S"
combineTableTo: "test_rangecombined"
rangeKey: "_t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( "cmt" + attributes.user_id )
return
attributes: [
{ key: "user_id", type: "string", required: true }
{ key: "title", type: "string" }
]
portOverwrite = {}
if _CONFIG_PORT
portOverwrite =
server:
port: _CONFIG_PORT
module.exports = utils.extend( true, CONFIG[ "_BASIC" ], CONFIG[ _CONFIG_TYPE ] or {}, portOverwrite )
| 30045 | CONFIG =
"_BASIC":
server:
port: 3000
host: null
aws:
accessKeyId: "-"
secretAccessKey: "-"
dynamo:
region: "eu-west-1"
tables:
"User":
name: "users"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "<NAME>", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Users":
name: "u"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "<NAME>", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Rooms":
name: "r"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
attributes: [
{ key: "<NAME>", type: "string", required: true }
{ key: "users", type: "array" }
{ key: "foo", type: "array" }
]
"Messages":
name: "messages"
hashKey: "user_id"
rangeKey: "_t"
rangeKeyType: "N"
attributes: [
{ key: "_t", type: "number" }
, { key: "lastlogin", type: "number" }
]
"mt":
name: "many"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs1":
name: "test_log1"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs2":
name: "test_log2"
hashKey: "<KEY>"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs1":
name: "test_log1"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs2":
name: "test_log2"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"c_mt":
name: "cmt"
hashKey: "id"
hashKeyType: "S"
combineTableTo: "test_rangecombined"
rangeKey: "_t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( "cmt" + attributes.user_id )
return
attributes: [
{ key: "user_id", type: "string", required: true }
{ key: "<NAME>", type: "string" }
]
portOverwrite = {}
if _CONFIG_PORT
portOverwrite =
server:
port: _CONFIG_PORT
module.exports = utils.extend( true, CONFIG[ "_BASIC" ], CONFIG[ _CONFIG_TYPE ] or {}, portOverwrite )
| true | CONFIG =
"_BASIC":
server:
port: 3000
host: null
aws:
accessKeyId: "-"
secretAccessKey: "-"
dynamo:
region: "eu-west-1"
tables:
"User":
name: "users"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "PI:NAME:<NAME>END_PI", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Users":
name: "u"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
# overwriteExisting
attributes: [
{ key: "PI:NAME:<NAME>END_PI", type: "string", required: true }
{ key: "age", type: "number" }
{ key: "lastlogin", type: "number" }
]
"Rooms":
name: "r"
combineTableTo: "combined"
hashKey: "_id"
overwriteExistingHash: false
attributes: [
{ key: "PI:NAME:<NAME>END_PI", type: "string", required: true }
{ key: "users", type: "array" }
{ key: "foo", type: "array" }
]
"Messages":
name: "messages"
hashKey: "user_id"
rangeKey: "_t"
rangeKeyType: "N"
attributes: [
{ key: "_t", type: "number" }
, { key: "lastlogin", type: "number" }
]
"mt":
name: "many"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs1":
name: "test_log1"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"Logs2":
name: "test_log2"
hashKey: "PI:KEY:<KEY>END_PI"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs1":
name: "test_log1"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"C_Logs2":
name: "test_log2"
combineTableTo: "test_rangecombined"
hashKey: "id"
hashKeyType: "S"
rangeKey: "t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( attributes.user )
return
attributes: [
{ key: "user", type: "string", required: true }
{ key: "title", type: "string" }
]
"c_mt":
name: "cmt"
hashKey: "id"
hashKeyType: "S"
combineTableTo: "test_rangecombined"
rangeKey: "_t"
rangeKeyType: "N"
fnCreateHash: ( attributes, cb )->
cb( "cmt" + attributes.user_id )
return
attributes: [
{ key: "user_id", type: "string", required: true }
{ key: "PI:NAME:<NAME>END_PI", type: "string" }
]
portOverwrite = {}
if _CONFIG_PORT
portOverwrite =
server:
port: _CONFIG_PORT
module.exports = utils.extend( true, CONFIG[ "_BASIC" ], CONFIG[ _CONFIG_TYPE ] or {}, portOverwrite )
|
[
{
"context": "homepage-srvr\n web page for bace\n\n copyright mark hahn 2013\n MIT license\n https://github.com/mark-",
"end": 82,
"score": 0.9998342990875244,
"start": 73,
"tag": "NAME",
"value": "mark hahn"
},
{
"context": " hahn 2013\n MIT license\n https://githu... | src/server/homepage-srvr.coffee | mark-hahn/bace | 1 | ###
file: src/server/homepage-srvr
web page for bace
copyright mark hahn 2013
MIT license
https://github.com/mark-hahn/bace/
###
tea = require 'teacup'
{render, doctype,html,head,meta,title,style,body,
div,link,script,h4,img,table,tr,td,text,iframe} = tea
exports.render = ->
render ->
doctype 5
html ->
head ->
meta "http-equiv": "Content-Type", content:"text/html; charset=UTF-8"
title "Bace"
link href:"/lib/page.css", rel:"stylesheet", type:"text/css", media:"screen"
body ->
div id:"logoStart", style:"position:absolute; top:3px; left:10px; font-Size:14px",
'(Waiting for log in)'
div id:'page', ->
script src:"/lib/jquery-1.10.2.js"
script src:"/socket.io/socket.io.js"
script src:"/ace/src-noconflict/ace.js"
script src:"/lib/teacup.js"
script src:"/lib/underscore.js"
script src:"/lib/underscore.string.js"
script src:"/lib/popup-client.js"
script src:"/lib/socket-client.js"
script src:"/lib/user-client.js"
script src:"/lib/helpers-client.js"
script src:"/lib/multibox-client.js"
script src:"/lib/header-client.js"
script src:"/lib/cmdbox-client.js"
script src:"/lib/dirbox-client.js"
script src:"/lib/settings-client.js"
script src:"/lib/main-client.js"
script src:"/lib/edit-client.js"
| 50496 | ###
file: src/server/homepage-srvr
web page for bace
copyright <NAME> 2013
MIT license
https://github.com/mark-hahn/bace/
###
tea = require 'teacup'
{render, doctype,html,head,meta,title,style,body,
div,link,script,h4,img,table,tr,td,text,iframe} = tea
exports.render = ->
render ->
doctype 5
html ->
head ->
meta "http-equiv": "Content-Type", content:"text/html; charset=UTF-8"
title "Bace"
link href:"/lib/page.css", rel:"stylesheet", type:"text/css", media:"screen"
body ->
div id:"logoStart", style:"position:absolute; top:3px; left:10px; font-Size:14px",
'(Waiting for log in)'
div id:'page', ->
script src:"/lib/jquery-1.10.2.js"
script src:"/socket.io/socket.io.js"
script src:"/ace/src-noconflict/ace.js"
script src:"/lib/teacup.js"
script src:"/lib/underscore.js"
script src:"/lib/underscore.string.js"
script src:"/lib/popup-client.js"
script src:"/lib/socket-client.js"
script src:"/lib/user-client.js"
script src:"/lib/helpers-client.js"
script src:"/lib/multibox-client.js"
script src:"/lib/header-client.js"
script src:"/lib/cmdbox-client.js"
script src:"/lib/dirbox-client.js"
script src:"/lib/settings-client.js"
script src:"/lib/main-client.js"
script src:"/lib/edit-client.js"
| true | ###
file: src/server/homepage-srvr
web page for bace
copyright PI:NAME:<NAME>END_PI 2013
MIT license
https://github.com/mark-hahn/bace/
###
tea = require 'teacup'
{render, doctype,html,head,meta,title,style,body,
div,link,script,h4,img,table,tr,td,text,iframe} = tea
exports.render = ->
render ->
doctype 5
html ->
head ->
meta "http-equiv": "Content-Type", content:"text/html; charset=UTF-8"
title "Bace"
link href:"/lib/page.css", rel:"stylesheet", type:"text/css", media:"screen"
body ->
div id:"logoStart", style:"position:absolute; top:3px; left:10px; font-Size:14px",
'(Waiting for log in)'
div id:'page', ->
script src:"/lib/jquery-1.10.2.js"
script src:"/socket.io/socket.io.js"
script src:"/ace/src-noconflict/ace.js"
script src:"/lib/teacup.js"
script src:"/lib/underscore.js"
script src:"/lib/underscore.string.js"
script src:"/lib/popup-client.js"
script src:"/lib/socket-client.js"
script src:"/lib/user-client.js"
script src:"/lib/helpers-client.js"
script src:"/lib/multibox-client.js"
script src:"/lib/header-client.js"
script src:"/lib/cmdbox-client.js"
script src:"/lib/dirbox-client.js"
script src:"/lib/settings-client.js"
script src:"/lib/main-client.js"
script src:"/lib/edit-client.js"
|
[
{
"context": "de fogos de artifício;\"\n comboDJ:\n name: \"Combo DevilJail\"\n price: 15\n color: \"#b362b0\"\n tex",
"end": 3525,
"score": 0.999792218208313,
"start": 3510,
"tag": "NAME",
"value": "Combo DevilJail"
}
] | devilservers-xmas-store-project/script.coffee | FelixLuciano/arquivo | 0 | $ ->
$("*[animated]").each ( index, callback ) ->
$this = $ this
$.each callback.attributes, ( index, callback ) ->
$val = callback.value.split " "
if callback.name == "animated"
$this
.addClass("animated " + $val[0] )
.css("animation-delay", $val[1] + "s" )
.css("animation-duration", $val[2] + "s" )
$("#messageSlider #indexes div").on "click", ->
$this = $ this
$attr = ( attr ) ->
return $this.children( "." + attr ).text()
$("#messageSlider #text").fadeOut ->
$( this ).children().empty()
$( this ).children("h1").prepend $attr("title")
$( this ).children("h4").prepend $attr("text")
.delay( 10 ).fadeIn()
$("#messageSlider #indexes div").removeClass "selected"
$this.addClass "selected"
$("#messageSlider #indexes div:first").trigger "click"
$(".card").each ->
$this = this
attr = ( attr ) ->
return $( "." + attr, $this ).text().split(" | ")
source = "\
<div class='title'></div>\
<div class='text'></div>"
$ this
.prepend source
.css {
backgroundImage: "url( #{attr("fundo")[0]} )"
backgroundColor: attr("fundo")[1] }
$ ".title", this
.prepend attr("titulo")[0]
$ ".text", this
.prepend attr("texto")[0]
.css {
marginTop: ( Math.round( $( $this ).width() * .1 ) / .1 ) * .5 }
$ ".fundo, .titulo, .texto", this
.remove()
$("#purchase-cancel") .on "click", ->
$ "#shop"
.removeClass "purchase-mode"
.addClass "cards-mode"
$ "#cards"
.show()
$ "#purchaseScreen"
.hide()
$.fn.mSwitch = ( a, b ) ->
mSwitch = {
id: $(this).attr("id") + "-mSwitch",
value: a,
checked: new String
}
if ( a == true )
mSwitch.checked = "checked"
$ this
.prepend "\
<input type='checkbox' class='mSwitch' id='" + mSwitch.id + "'" + mSwitch.checked + ">\
<label for=" + mSwitch.id + ">\
<div class='mSwitch-checkedTrack'></div>\
<div class='mSwitch-thumb'></div>\
</label>\
"
.addClass "mSwitch-content"
.attr { value: mSwitch.value }
$ "label", this
.on "click", ->
if( $( this ).parent().attr("value") == "true" )
$( this ).parent().attr({ value: false })
$b = false
else
$( this ).parent().attr({ value: true })
$b = true
b( $b )
paymentForm = "pagseguro"
$("#payService-switcher").mSwitch false , ( a ) ->
if a == true
$("#pagseguro").removeClass "selected"
$("#moip").addClass "selected"
paymentForm = "moip"
else
$("#moip").removeClass "selected"
$("#pagseguro").addClass "selected"
paymentForm = "pagseguro"
$("*[ openLink ]").on "click", ->
attr = $( this ).attr("openLink").split(" | ")
window.open attr[0], attr[1], attr[2]
shopItems =
comboDG:
name: "Combo DevilGames2"
price: 15
color: "#b36262"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Uma key de Glorius Equilibrium;<br />
- Uma caixa de RI's;<br />
- Lançador de fogos de artifício;"
comboDP:
name: "Combo DevilPlay"
price: 15
color: "#62b365"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Kit armas;<br />
- Lançador de fogos de artifício;"
comboDJ:
name: "Combo DevilJail"
price: 15
color: "#b362b0"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Bonus de $25.000 ao ativar;<br />"
purchaseScreen = ( item ) ->
$ "#shop"
.removeClass "cards-mode"
.addClass "purchase-mode"
$ "#cards"
.hide()
$ "#purchaseScreen"
.show()
$ "body"
.animate {
scrollTop: $("#shop").offset().top - 20, 500 }
$ "#purchaseScreen .left .header"
.css {
backgroundImage: "url(images/#{item}.png)"
backgroundColor: shopItems[item].color }
$ "#purchaseScreen .left .info .name"
.empty()
.prepend shopItems[item].name
$ "#purchaseScreen .left .info .price"
.empty()
.prepend "R$ #{shopItems[item].price}"
$ "#purchaseScreen .right"
.empty()
.prepend shopItems[item].text
.css {
borderRightColor: shopItems[item].color }
$("#checkTerms").on "click", ->
if $( this ).is ":checked"
$ "#purchase-buy"
.removeClass "buy-notAllowed"
.addClass "buy-allowed"
$("#purchaseScreen #purchase-buy").on "click", ->
console.log "#{shopItems[item].name} via #{paymentForm}"
else
$ "#purchase-buy"
.removeClass "buy-allowed"
.addClass "buy-notAllowed"
$("#purchaseScreen #purchase-buy").off "click"
$(".card").on "click", ->
purchaseScreen $( this ).attr "shop" | 71950 | $ ->
$("*[animated]").each ( index, callback ) ->
$this = $ this
$.each callback.attributes, ( index, callback ) ->
$val = callback.value.split " "
if callback.name == "animated"
$this
.addClass("animated " + $val[0] )
.css("animation-delay", $val[1] + "s" )
.css("animation-duration", $val[2] + "s" )
$("#messageSlider #indexes div").on "click", ->
$this = $ this
$attr = ( attr ) ->
return $this.children( "." + attr ).text()
$("#messageSlider #text").fadeOut ->
$( this ).children().empty()
$( this ).children("h1").prepend $attr("title")
$( this ).children("h4").prepend $attr("text")
.delay( 10 ).fadeIn()
$("#messageSlider #indexes div").removeClass "selected"
$this.addClass "selected"
$("#messageSlider #indexes div:first").trigger "click"
$(".card").each ->
$this = this
attr = ( attr ) ->
return $( "." + attr, $this ).text().split(" | ")
source = "\
<div class='title'></div>\
<div class='text'></div>"
$ this
.prepend source
.css {
backgroundImage: "url( #{attr("fundo")[0]} )"
backgroundColor: attr("fundo")[1] }
$ ".title", this
.prepend attr("titulo")[0]
$ ".text", this
.prepend attr("texto")[0]
.css {
marginTop: ( Math.round( $( $this ).width() * .1 ) / .1 ) * .5 }
$ ".fundo, .titulo, .texto", this
.remove()
$("#purchase-cancel") .on "click", ->
$ "#shop"
.removeClass "purchase-mode"
.addClass "cards-mode"
$ "#cards"
.show()
$ "#purchaseScreen"
.hide()
$.fn.mSwitch = ( a, b ) ->
mSwitch = {
id: $(this).attr("id") + "-mSwitch",
value: a,
checked: new String
}
if ( a == true )
mSwitch.checked = "checked"
$ this
.prepend "\
<input type='checkbox' class='mSwitch' id='" + mSwitch.id + "'" + mSwitch.checked + ">\
<label for=" + mSwitch.id + ">\
<div class='mSwitch-checkedTrack'></div>\
<div class='mSwitch-thumb'></div>\
</label>\
"
.addClass "mSwitch-content"
.attr { value: mSwitch.value }
$ "label", this
.on "click", ->
if( $( this ).parent().attr("value") == "true" )
$( this ).parent().attr({ value: false })
$b = false
else
$( this ).parent().attr({ value: true })
$b = true
b( $b )
paymentForm = "pagseguro"
$("#payService-switcher").mSwitch false , ( a ) ->
if a == true
$("#pagseguro").removeClass "selected"
$("#moip").addClass "selected"
paymentForm = "moip"
else
$("#moip").removeClass "selected"
$("#pagseguro").addClass "selected"
paymentForm = "pagseguro"
$("*[ openLink ]").on "click", ->
attr = $( this ).attr("openLink").split(" | ")
window.open attr[0], attr[1], attr[2]
shopItems =
comboDG:
name: "Combo DevilGames2"
price: 15
color: "#b36262"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Uma key de Glorius Equilibrium;<br />
- Uma caixa de RI's;<br />
- Lançador de fogos de artifício;"
comboDP:
name: "Combo DevilPlay"
price: 15
color: "#62b365"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Kit armas;<br />
- Lançador de fogos de artifício;"
comboDJ:
name: "<NAME>"
price: 15
color: "#b362b0"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Bonus de $25.000 ao ativar;<br />"
purchaseScreen = ( item ) ->
$ "#shop"
.removeClass "cards-mode"
.addClass "purchase-mode"
$ "#cards"
.hide()
$ "#purchaseScreen"
.show()
$ "body"
.animate {
scrollTop: $("#shop").offset().top - 20, 500 }
$ "#purchaseScreen .left .header"
.css {
backgroundImage: "url(images/#{item}.png)"
backgroundColor: shopItems[item].color }
$ "#purchaseScreen .left .info .name"
.empty()
.prepend shopItems[item].name
$ "#purchaseScreen .left .info .price"
.empty()
.prepend "R$ #{shopItems[item].price}"
$ "#purchaseScreen .right"
.empty()
.prepend shopItems[item].text
.css {
borderRightColor: shopItems[item].color }
$("#checkTerms").on "click", ->
if $( this ).is ":checked"
$ "#purchase-buy"
.removeClass "buy-notAllowed"
.addClass "buy-allowed"
$("#purchaseScreen #purchase-buy").on "click", ->
console.log "#{shopItems[item].name} via #{paymentForm}"
else
$ "#purchase-buy"
.removeClass "buy-allowed"
.addClass "buy-notAllowed"
$("#purchaseScreen #purchase-buy").off "click"
$(".card").on "click", ->
purchaseScreen $( this ).attr "shop" | true | $ ->
$("*[animated]").each ( index, callback ) ->
$this = $ this
$.each callback.attributes, ( index, callback ) ->
$val = callback.value.split " "
if callback.name == "animated"
$this
.addClass("animated " + $val[0] )
.css("animation-delay", $val[1] + "s" )
.css("animation-duration", $val[2] + "s" )
$("#messageSlider #indexes div").on "click", ->
$this = $ this
$attr = ( attr ) ->
return $this.children( "." + attr ).text()
$("#messageSlider #text").fadeOut ->
$( this ).children().empty()
$( this ).children("h1").prepend $attr("title")
$( this ).children("h4").prepend $attr("text")
.delay( 10 ).fadeIn()
$("#messageSlider #indexes div").removeClass "selected"
$this.addClass "selected"
$("#messageSlider #indexes div:first").trigger "click"
$(".card").each ->
$this = this
attr = ( attr ) ->
return $( "." + attr, $this ).text().split(" | ")
source = "\
<div class='title'></div>\
<div class='text'></div>"
$ this
.prepend source
.css {
backgroundImage: "url( #{attr("fundo")[0]} )"
backgroundColor: attr("fundo")[1] }
$ ".title", this
.prepend attr("titulo")[0]
$ ".text", this
.prepend attr("texto")[0]
.css {
marginTop: ( Math.round( $( $this ).width() * .1 ) / .1 ) * .5 }
$ ".fundo, .titulo, .texto", this
.remove()
$("#purchase-cancel") .on "click", ->
$ "#shop"
.removeClass "purchase-mode"
.addClass "cards-mode"
$ "#cards"
.show()
$ "#purchaseScreen"
.hide()
$.fn.mSwitch = ( a, b ) ->
mSwitch = {
id: $(this).attr("id") + "-mSwitch",
value: a,
checked: new String
}
if ( a == true )
mSwitch.checked = "checked"
$ this
.prepend "\
<input type='checkbox' class='mSwitch' id='" + mSwitch.id + "'" + mSwitch.checked + ">\
<label for=" + mSwitch.id + ">\
<div class='mSwitch-checkedTrack'></div>\
<div class='mSwitch-thumb'></div>\
</label>\
"
.addClass "mSwitch-content"
.attr { value: mSwitch.value }
$ "label", this
.on "click", ->
if( $( this ).parent().attr("value") == "true" )
$( this ).parent().attr({ value: false })
$b = false
else
$( this ).parent().attr({ value: true })
$b = true
b( $b )
paymentForm = "pagseguro"
$("#payService-switcher").mSwitch false , ( a ) ->
if a == true
$("#pagseguro").removeClass "selected"
$("#moip").addClass "selected"
paymentForm = "moip"
else
$("#moip").removeClass "selected"
$("#pagseguro").addClass "selected"
paymentForm = "pagseguro"
$("*[ openLink ]").on "click", ->
attr = $( this ).attr("openLink").split(" | ")
window.open attr[0], attr[1], attr[2]
shopItems =
comboDG:
name: "Combo DevilGames2"
price: 15
color: "#b36262"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Uma key de Glorius Equilibrium;<br />
- Uma caixa de RI's;<br />
- Lançador de fogos de artifício;"
comboDP:
name: "Combo DevilPlay"
price: 15
color: "#62b365"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Kit armas;<br />
- Lançador de fogos de artifício;"
comboDJ:
name: "PI:NAME:<NAME>END_PI"
price: 15
color: "#b362b0"
text: "
- Uma de key Vip Dima de 35 dias;<br />
- Duas caixas de itens;<br />
- Bonus de $25.000 ao ativar;<br />"
purchaseScreen = ( item ) ->
$ "#shop"
.removeClass "cards-mode"
.addClass "purchase-mode"
$ "#cards"
.hide()
$ "#purchaseScreen"
.show()
$ "body"
.animate {
scrollTop: $("#shop").offset().top - 20, 500 }
$ "#purchaseScreen .left .header"
.css {
backgroundImage: "url(images/#{item}.png)"
backgroundColor: shopItems[item].color }
$ "#purchaseScreen .left .info .name"
.empty()
.prepend shopItems[item].name
$ "#purchaseScreen .left .info .price"
.empty()
.prepend "R$ #{shopItems[item].price}"
$ "#purchaseScreen .right"
.empty()
.prepend shopItems[item].text
.css {
borderRightColor: shopItems[item].color }
$("#checkTerms").on "click", ->
if $( this ).is ":checked"
$ "#purchase-buy"
.removeClass "buy-notAllowed"
.addClass "buy-allowed"
$("#purchaseScreen #purchase-buy").on "click", ->
console.log "#{shopItems[item].name} via #{paymentForm}"
else
$ "#purchase-buy"
.removeClass "buy-allowed"
.addClass "buy-notAllowed"
$("#purchaseScreen #purchase-buy").off "click"
$(".card").on "click", ->
purchaseScreen $( this ).attr "shop" |
[
{
"context": "ken: 1234\n default: true\n key: 'value'\n imageUrl: 'http://www.some.other.image",
"end": 331,
"score": 0.7051968574523926,
"start": 326,
"tag": "KEY",
"value": "value"
}
] | spec/unit/braintree/unknown_payment_method_spec.coffee | StreamCo/braintree_node | 0 | require('../../spec_helper')
{UnknownPaymentMethod} = require('../../../lib/braintree/unknown_payment_method')
describe "UnknownPaymentMethod", ->
describe "imageUrl", ->
it "returns the correct image url", ->
response =
unknownPaymentMethod:
token: 1234
default: true
key: 'value'
imageUrl: 'http://www.some.other.image.com'
unknownPaymentMethod = new UnknownPaymentMethod(response)
assert.equal(unknownPaymentMethod.token, 1234)
assert.isTrue(unknownPaymentMethod.default)
assert.equal(
unknownPaymentMethod.imageUrl,
"https://assets.braintreegateway.com/payment_method_logo/unknown.png"
)
| 44474 | require('../../spec_helper')
{UnknownPaymentMethod} = require('../../../lib/braintree/unknown_payment_method')
describe "UnknownPaymentMethod", ->
describe "imageUrl", ->
it "returns the correct image url", ->
response =
unknownPaymentMethod:
token: 1234
default: true
key: '<KEY>'
imageUrl: 'http://www.some.other.image.com'
unknownPaymentMethod = new UnknownPaymentMethod(response)
assert.equal(unknownPaymentMethod.token, 1234)
assert.isTrue(unknownPaymentMethod.default)
assert.equal(
unknownPaymentMethod.imageUrl,
"https://assets.braintreegateway.com/payment_method_logo/unknown.png"
)
| true | require('../../spec_helper')
{UnknownPaymentMethod} = require('../../../lib/braintree/unknown_payment_method')
describe "UnknownPaymentMethod", ->
describe "imageUrl", ->
it "returns the correct image url", ->
response =
unknownPaymentMethod:
token: 1234
default: true
key: 'PI:KEY:<KEY>END_PI'
imageUrl: 'http://www.some.other.image.com'
unknownPaymentMethod = new UnknownPaymentMethod(response)
assert.equal(unknownPaymentMethod.token, 1234)
assert.isTrue(unknownPaymentMethod.default)
assert.equal(
unknownPaymentMethod.imageUrl,
"https://assets.braintreegateway.com/payment_method_logo/unknown.png"
)
|
[
{
"context": "bel>\n <label>Password <input type=\"password\" name=\"password\"></label>\n <button",
"end": 640,
"score": 0.9918874502182007,
"start": 632,
"tag": "PASSWORD",
"value": "password"
},
{
"context": " <label>Password <input type=\"passwor... | spec/script_spec.coffee | ghuntley/zombie | 1 | { Vows, assert, brains, Browser } = require("./helpers")
Vows.describe("Scripts").addBatch
"basic":
topic: ->
brains.get "/script/living", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script src="/sammy.js"></script>
<script src="/app.js"></script>
</head>
<body>
<div id="main">
<a href="/script/dead">Kill</a>
<form action="#/dead" method="post">
<label>Email <input type="text" name="email"></label>
<label>Password <input type="password" name="password"></label>
<button>Sign Me Up</button>
</form>
</div>
<div class="now">Walking Aimlessly</div>
</body>
</html>
"""
brains.get "/app.js", (req, res)->
res.send """
Sammy("#main", function(app) {
app.get("#/", function(context) {
document.title = "The Living";
});
app.get("#/dead", function(context) {
context.swap("The Living Dead");
});
app.post("#/dead", function(context) {
document.title = "Signed up";
});
});
$(function() { Sammy("#main").run("#/") });
"""
"run app":
Browser.wants "http://localhost:3003/script/living"
"should execute route": (browser)->
assert.equal browser.document.title, "The Living"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"move around":
topic: (browser)->
browser.visit browser.location.href + "dead", @callback
"should execute route": (browser)->
assert.equal browser.text("#main"), "The Living Dead"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/dead"
"live events":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.fill "Email", "armbiter@zombies"
browser.fill "Password", "br41nz"
browser.pressButton "Sign Me Up"
browser.wait 500, @callback
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"should process event": (browser)->
assert.equal browser.document.title, "Signed up"
"evaluate":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.evaluate "document.title"
"should evaluate in context and return value": (title)->
assert.equal title, "The Living"
.addBatch
"evaluating":
"context":
topic: ->
brains.get "/script/context", (req, res)->
res.send """
<html>
<script>var foo = 1</script>
<script>window.foo = foo + 1</script>
<script>document.title = this.foo</script>
<script>
setTimeout(function() {
document.title = foo + window.foo
});</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/context", @callback
"should be shared by all scripts": (browser)->
assert.equal browser.text("title"), "4"
"window":
topic: ->
brains.get "/script/window", (req, res)->
res.send """
<html>
<script>document.title = [window == this, this == window.window, this == top, top == window.top, this == parent, top == window.parent].join(',')</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/window", @callback
"should be the same as this, top and parent": (browser)->
assert.equal browser.text("title"), "true,true,true,true,true,true"
"global and function":
topic: ->
brains.get "/script/global_and_fn", (req, res)->
res.send """
<html>
<script>
var foo;
(function() {
if (!foo)
foo = "foo";
})()
document.title = foo;
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/global_and_fn", @callback
"should not fail with an error": (browser)->
assert.isEmpty browser.errors
"should set global variable": (browser)->
assert.equal browser.text("title"), "foo"
"order":
topic: ->
brains.get "/script/order", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/order.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/order.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser
browser.wants "http://localhost:3003/script/order", @callback
"should run scripts in order regardless of source": (browser)->
assert.equal browser.text("title"), "ZeroOneTwo"
"eval":
topic: ->
brains.get "/script/eval", (req, res)->
res.send """
<html>
<script>
var foo = "One";
(function() {
var bar = "Two"; // standard eval sees this
var e = eval; // this 'eval' only sees global scope
try {
var baz = e("bar");
} catch (ex) {
var baz = "Three";
}
// In spite of local variable, global scope eval finds global foo
var foo = "NotOne";
var e_foo = e("foo");
var qux = window.eval.call(window, "foo");
console.log(qux)
document.title = eval('e_foo + bar + baz + qux');
})();
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/eval", @callback
"should evaluate in global scope": (browser)->
assert.equal browser.document.title, "OneTwoThreeFour"
.addBatch
"failing":
"incomplete":
topic: ->
brains.get "/script/incomplete", (req, res)->
res.send "<script>1+</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/incomplete", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Unexpected end of input"
"error":
topic: ->
brains.get "/script/error", (req, res)->
res.send "<script>(function(foo) { foo.bar })()</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/error", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Cannot read property 'bar' of undefined"
.addBatch
"loading":
"with entities":
topic: ->
brains.get "/script/split", (req, res)->
res.send """
<html>
<script>foo = 1 < 2 ? 1 : 2; '&'; document.title = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/split", @callback
"should run full script": (browser)->
assert.equal browser.text("title"), "1"
###
# NOTE: htmlparser can't deal with CDATA sections
"with CDATA":
topic: ->
brains.get "/script/cdata", (req, res)-> res.send """
<html>
<script>foo = 2; <![CDATA[ document.title ]]> = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/cdata", @callback
"should run full script": (browser)-> assert.equal browser.text("title"), "2"
###
# NOTE: htmlparser can't deal with document.write.
###
"using document.write":
topic: ->
brains.get "/script/write", (req, res)-> res.send """
<html>
<head>
<script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script>
</head>
<body>
<script>
$(function() { document.title = "Script document.write" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/write", @callback
"should run script": (browser)-> assert.equal browser.document.title, "Script document.write"
###
"using appendChild":
topic: ->
brains.get "/script/append", (req, res)->
res.send """
<html>
<head>
<script>
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = '/jquery.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
</script>
</head>
<body>
<script>
$(function() { document.title = "Script appendChild" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/append", @callback
"should run script": (browser)->
assert.equal browser.document.title, "Script appendChild"
"scripts disabled":
topic: ->
brains.get "/script/no-scripts", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/no-scripts.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/no-scripts.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser(runScripts: false)
browser.wants "http://localhost:3003/script/order", @callback
"should not run scripts": (browser)->
assert.equal browser.document.title, "Zero"
.addBatch
"file:// uri scheme":
Browser.wants "file://" + __dirname + "/data/file_scheme.html"
topic: (browser)->
browser.wait 100, @callback
"should run scripts with file url src": (browser)->
assert.equal browser.document.title, "file://"
.addBatch
"new Image":
Browser.wants "http://localhost:3003/script/living"
"should construct an img tag": (browser)->
assert.equal browser.evaluate("new Image").tagName, "IMG"
"should construct an img tag with width and height": (browser)->
assert.equal browser.evaluate("new Image(1, 1)").height, 1
.export(module)
| 157446 | { Vows, assert, brains, Browser } = require("./helpers")
Vows.describe("Scripts").addBatch
"basic":
topic: ->
brains.get "/script/living", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script src="/sammy.js"></script>
<script src="/app.js"></script>
</head>
<body>
<div id="main">
<a href="/script/dead">Kill</a>
<form action="#/dead" method="post">
<label>Email <input type="text" name="email"></label>
<label>Password <input type="<PASSWORD>" name="<PASSWORD>"></label>
<button>Sign Me Up</button>
</form>
</div>
<div class="now">Walking Aimlessly</div>
</body>
</html>
"""
brains.get "/app.js", (req, res)->
res.send """
Sammy("#main", function(app) {
app.get("#/", function(context) {
document.title = "The Living";
});
app.get("#/dead", function(context) {
context.swap("The Living Dead");
});
app.post("#/dead", function(context) {
document.title = "Signed up";
});
});
$(function() { Sammy("#main").run("#/") });
"""
"run app":
Browser.wants "http://localhost:3003/script/living"
"should execute route": (browser)->
assert.equal browser.document.title, "The Living"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"move around":
topic: (browser)->
browser.visit browser.location.href + "dead", @callback
"should execute route": (browser)->
assert.equal browser.text("#main"), "The Living Dead"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/dead"
"live events":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.fill "Email", "<EMAIL>"
browser.fill "Password", "<PASSWORD>"
browser.pressButton "Sign Me Up"
browser.wait 500, @callback
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"should process event": (browser)->
assert.equal browser.document.title, "Signed up"
"evaluate":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.evaluate "document.title"
"should evaluate in context and return value": (title)->
assert.equal title, "The Living"
.addBatch
"evaluating":
"context":
topic: ->
brains.get "/script/context", (req, res)->
res.send """
<html>
<script>var foo = 1</script>
<script>window.foo = foo + 1</script>
<script>document.title = this.foo</script>
<script>
setTimeout(function() {
document.title = foo + window.foo
});</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/context", @callback
"should be shared by all scripts": (browser)->
assert.equal browser.text("title"), "4"
"window":
topic: ->
brains.get "/script/window", (req, res)->
res.send """
<html>
<script>document.title = [window == this, this == window.window, this == top, top == window.top, this == parent, top == window.parent].join(',')</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/window", @callback
"should be the same as this, top and parent": (browser)->
assert.equal browser.text("title"), "true,true,true,true,true,true"
"global and function":
topic: ->
brains.get "/script/global_and_fn", (req, res)->
res.send """
<html>
<script>
var foo;
(function() {
if (!foo)
foo = "foo";
})()
document.title = foo;
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/global_and_fn", @callback
"should not fail with an error": (browser)->
assert.isEmpty browser.errors
"should set global variable": (browser)->
assert.equal browser.text("title"), "foo"
"order":
topic: ->
brains.get "/script/order", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/order.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/order.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser
browser.wants "http://localhost:3003/script/order", @callback
"should run scripts in order regardless of source": (browser)->
assert.equal browser.text("title"), "ZeroOneTwo"
"eval":
topic: ->
brains.get "/script/eval", (req, res)->
res.send """
<html>
<script>
var foo = "One";
(function() {
var bar = "Two"; // standard eval sees this
var e = eval; // this 'eval' only sees global scope
try {
var baz = e("bar");
} catch (ex) {
var baz = "Three";
}
// In spite of local variable, global scope eval finds global foo
var foo = "NotOne";
var e_foo = e("foo");
var qux = window.eval.call(window, "foo");
console.log(qux)
document.title = eval('e_foo + bar + baz + qux');
})();
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/eval", @callback
"should evaluate in global scope": (browser)->
assert.equal browser.document.title, "OneTwoThreeFour"
.addBatch
"failing":
"incomplete":
topic: ->
brains.get "/script/incomplete", (req, res)->
res.send "<script>1+</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/incomplete", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Unexpected end of input"
"error":
topic: ->
brains.get "/script/error", (req, res)->
res.send "<script>(function(foo) { foo.bar })()</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/error", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Cannot read property 'bar' of undefined"
.addBatch
"loading":
"with entities":
topic: ->
brains.get "/script/split", (req, res)->
res.send """
<html>
<script>foo = 1 < 2 ? 1 : 2; '&'; document.title = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/split", @callback
"should run full script": (browser)->
assert.equal browser.text("title"), "1"
###
# NOTE: htmlparser can't deal with CDATA sections
"with CDATA":
topic: ->
brains.get "/script/cdata", (req, res)-> res.send """
<html>
<script>foo = 2; <![CDATA[ document.title ]]> = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/cdata", @callback
"should run full script": (browser)-> assert.equal browser.text("title"), "2"
###
# NOTE: htmlparser can't deal with document.write.
###
"using document.write":
topic: ->
brains.get "/script/write", (req, res)-> res.send """
<html>
<head>
<script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script>
</head>
<body>
<script>
$(function() { document.title = "Script document.write" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/write", @callback
"should run script": (browser)-> assert.equal browser.document.title, "Script document.write"
###
"using appendChild":
topic: ->
brains.get "/script/append", (req, res)->
res.send """
<html>
<head>
<script>
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = '/jquery.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
</script>
</head>
<body>
<script>
$(function() { document.title = "Script appendChild" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/append", @callback
"should run script": (browser)->
assert.equal browser.document.title, "Script appendChild"
"scripts disabled":
topic: ->
brains.get "/script/no-scripts", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/no-scripts.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/no-scripts.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser(runScripts: false)
browser.wants "http://localhost:3003/script/order", @callback
"should not run scripts": (browser)->
assert.equal browser.document.title, "Zero"
.addBatch
"file:// uri scheme":
Browser.wants "file://" + __dirname + "/data/file_scheme.html"
topic: (browser)->
browser.wait 100, @callback
"should run scripts with file url src": (browser)->
assert.equal browser.document.title, "file://"
.addBatch
"new Image":
Browser.wants "http://localhost:3003/script/living"
"should construct an img tag": (browser)->
assert.equal browser.evaluate("new Image").tagName, "IMG"
"should construct an img tag with width and height": (browser)->
assert.equal browser.evaluate("new Image(1, 1)").height, 1
.export(module)
| true | { Vows, assert, brains, Browser } = require("./helpers")
Vows.describe("Scripts").addBatch
"basic":
topic: ->
brains.get "/script/living", (req, res)->
res.send """
<html>
<head>
<script src="/jquery.js"></script>
<script src="/sammy.js"></script>
<script src="/app.js"></script>
</head>
<body>
<div id="main">
<a href="/script/dead">Kill</a>
<form action="#/dead" method="post">
<label>Email <input type="text" name="email"></label>
<label>Password <input type="PI:PASSWORD:<PASSWORD>END_PI" name="PI:PASSWORD:<PASSWORD>END_PI"></label>
<button>Sign Me Up</button>
</form>
</div>
<div class="now">Walking Aimlessly</div>
</body>
</html>
"""
brains.get "/app.js", (req, res)->
res.send """
Sammy("#main", function(app) {
app.get("#/", function(context) {
document.title = "The Living";
});
app.get("#/dead", function(context) {
context.swap("The Living Dead");
});
app.post("#/dead", function(context) {
document.title = "Signed up";
});
});
$(function() { Sammy("#main").run("#/") });
"""
"run app":
Browser.wants "http://localhost:3003/script/living"
"should execute route": (browser)->
assert.equal browser.document.title, "The Living"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"move around":
topic: (browser)->
browser.visit browser.location.href + "dead", @callback
"should execute route": (browser)->
assert.equal browser.text("#main"), "The Living Dead"
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/dead"
"live events":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.fill "Email", "PI:EMAIL:<EMAIL>END_PI"
browser.fill "Password", "PI:PASSWORD:<PASSWORD>END_PI"
browser.pressButton "Sign Me Up"
browser.wait 500, @callback
"should change location": (browser)->
assert.equal browser.location.href, "http://localhost:3003/script/living#/"
"should process event": (browser)->
assert.equal browser.document.title, "Signed up"
"evaluate":
Browser.wants "http://localhost:3003/script/living"
topic: (browser)->
browser.evaluate "document.title"
"should evaluate in context and return value": (title)->
assert.equal title, "The Living"
.addBatch
"evaluating":
"context":
topic: ->
brains.get "/script/context", (req, res)->
res.send """
<html>
<script>var foo = 1</script>
<script>window.foo = foo + 1</script>
<script>document.title = this.foo</script>
<script>
setTimeout(function() {
document.title = foo + window.foo
});</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/context", @callback
"should be shared by all scripts": (browser)->
assert.equal browser.text("title"), "4"
"window":
topic: ->
brains.get "/script/window", (req, res)->
res.send """
<html>
<script>document.title = [window == this, this == window.window, this == top, top == window.top, this == parent, top == window.parent].join(',')</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/window", @callback
"should be the same as this, top and parent": (browser)->
assert.equal browser.text("title"), "true,true,true,true,true,true"
"global and function":
topic: ->
brains.get "/script/global_and_fn", (req, res)->
res.send """
<html>
<script>
var foo;
(function() {
if (!foo)
foo = "foo";
})()
document.title = foo;
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/global_and_fn", @callback
"should not fail with an error": (browser)->
assert.isEmpty browser.errors
"should set global variable": (browser)->
assert.equal browser.text("title"), "foo"
"order":
topic: ->
brains.get "/script/order", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/order.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/order.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser
browser.wants "http://localhost:3003/script/order", @callback
"should run scripts in order regardless of source": (browser)->
assert.equal browser.text("title"), "ZeroOneTwo"
"eval":
topic: ->
brains.get "/script/eval", (req, res)->
res.send """
<html>
<script>
var foo = "One";
(function() {
var bar = "Two"; // standard eval sees this
var e = eval; // this 'eval' only sees global scope
try {
var baz = e("bar");
} catch (ex) {
var baz = "Three";
}
// In spite of local variable, global scope eval finds global foo
var foo = "NotOne";
var e_foo = e("foo");
var qux = window.eval.call(window, "foo");
console.log(qux)
document.title = eval('e_foo + bar + baz + qux');
})();
</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/eval", @callback
"should evaluate in global scope": (browser)->
assert.equal browser.document.title, "OneTwoThreeFour"
.addBatch
"failing":
"incomplete":
topic: ->
brains.get "/script/incomplete", (req, res)->
res.send "<script>1+</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/incomplete", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Unexpected end of input"
"error":
topic: ->
brains.get "/script/error", (req, res)->
res.send "<script>(function(foo) { foo.bar })()</script>"
browser = new Browser
browser.wants "http://localhost:3003/script/error", @callback
"should propagate error to window": (browser)->
assert.equal browser.error.message, "Cannot read property 'bar' of undefined"
.addBatch
"loading":
"with entities":
topic: ->
brains.get "/script/split", (req, res)->
res.send """
<html>
<script>foo = 1 < 2 ? 1 : 2; '&'; document.title = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/split", @callback
"should run full script": (browser)->
assert.equal browser.text("title"), "1"
###
# NOTE: htmlparser can't deal with CDATA sections
"with CDATA":
topic: ->
brains.get "/script/cdata", (req, res)-> res.send """
<html>
<script>foo = 2; <![CDATA[ document.title ]]> = foo</script>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/cdata", @callback
"should run full script": (browser)-> assert.equal browser.text("title"), "2"
###
# NOTE: htmlparser can't deal with document.write.
###
"using document.write":
topic: ->
brains.get "/script/write", (req, res)-> res.send """
<html>
<head>
<script>document.write(unescape(\'%3Cscript src="/jquery.js"%3E%3C/script%3E\'));</script>
</head>
<body>
<script>
$(function() { document.title = "Script document.write" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/write", @callback
"should run script": (browser)-> assert.equal browser.document.title, "Script document.write"
###
"using appendChild":
topic: ->
brains.get "/script/append", (req, res)->
res.send """
<html>
<head>
<script>
var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true;
s.src = '/jquery.js';
(document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(s);
</script>
</head>
<body>
<script>
$(function() { document.title = "Script appendChild" });
</script>
</body>
</html>
"""
browser = new Browser
browser.wants "http://localhost:3003/script/append", @callback
"should run script": (browser)->
assert.equal browser.document.title, "Script appendChild"
"scripts disabled":
topic: ->
brains.get "/script/no-scripts", (req, res)->
res.send """
<html>
<head>
<title>Zero</title>
<script src="/script/no-scripts.js"></script>
</head>
<body>
<script>
document.title = document.title + "Two";</script>
</body>
</html>
"""
brains.get "/script/no-scripts.js", (req, res)->
res.send "document.title = document.title + 'One'"
browser = new Browser(runScripts: false)
browser.wants "http://localhost:3003/script/order", @callback
"should not run scripts": (browser)->
assert.equal browser.document.title, "Zero"
.addBatch
"file:// uri scheme":
Browser.wants "file://" + __dirname + "/data/file_scheme.html"
topic: (browser)->
browser.wait 100, @callback
"should run scripts with file url src": (browser)->
assert.equal browser.document.title, "file://"
.addBatch
"new Image":
Browser.wants "http://localhost:3003/script/living"
"should construct an img tag": (browser)->
assert.equal browser.evaluate("new Image").tagName, "IMG"
"should construct an img tag with width and height": (browser)->
assert.equal browser.evaluate("new Image(1, 1)").height, 1
.export(module)
|
[
{
"context": "if error\n resource.updateAttributes @params[@resourceName], (error) =>\n @respondWithStatus !!!error ",
"end": 22314,
"score": 0.5221518278121948,
"start": 22302,
"tag": "USERNAME",
"value": "resourceName"
},
{
"context": "rn callback.call @, error, null if... | dist/tower.coffee | ludicast/tower | 1 |
window.global ||= window
module = global.module || {}
global.Tower = Tower = {}
Tower.version = "0.3.0"
Tower.logger = console
require './support'
require './application'
require './client/application'
require './store'
require './client/store'
require './model'
require './view'
require './client/view'
require './controller'
require './client/controller'
require './http'
require './middleware'
class Tower.Controller extends Tower.Class
@include Tower.Support.Callbacks
@extend Tower.Support.EventEmitter
@include Tower.Support.EventEmitter
@instance: ->
@_instance ||= new @
@metadata: ->
@_metadata ||= {}
constructor: ->
@constructor._instance = @
@headers = {}
@status = 200
@request = null
@response = null
@params = {}
@query = {}
@resourceName = @constructor.resourceName()
@resourceType = @constructor.resourceType()
@collectionName = @constructor.collectionName()
@formats = _.keys(@constructor.mimes())
if @constructor._belongsTo
@hasParent = true
else
@hasParent = false
require './controller/callbacks'
require './controller/helpers'
require './controller/instrumentation'
require './controller/params'
require './controller/redirecting'
require './controller/rendering'
require './controller/resourceful'
require './controller/responder'
require './controller/responding'
Tower.Controller.include Tower.Controller.Callbacks
Tower.Controller.include Tower.Controller.Helpers
Tower.Controller.include Tower.Controller.Instrumentation
Tower.Controller.include Tower.Controller.Params
Tower.Controller.include Tower.Controller.Redirecting
Tower.Controller.include Tower.Controller.Rendering
Tower.Controller.include Tower.Controller.Resourceful
Tower.Controller.include Tower.Controller.Responding
Tower.HTTP = {}
require './http/agent'
require './http/cookies'
require './http/param'
require './http/route'
require './http/request'
require './http/response'
require './http/url'
class Tower.Model extends Tower.Class
# @example All configuration options
# class App.User extends Tower.Model
# @configure
#
# @example Configure using a function
# class App.User extends Tower.Model
# @configure ->
# defaultStore: Tower.Store.Memory
@configure: (object) ->
@config ||= {}
object = object.call @ if typeof object == "function"
_.extend @config, object
@
# @example All default options
# class App.User extends Tower.Model
# @defaults store: Tower.Store.Memory, scope: @desc("createdAt")
@defaults: (object) ->
@default(key, value) for key, value of object
@_defaults
# @example All default options
# class App.User extends Tower.Model
# @default "store", Tower.Store.Memory
# @default "scope", @desc("createdAt")
@default: (key, value) ->
@_defaults ||= {}
@_defaults[key] = value
constructor: (attrs, options) ->
@initialize attrs, options
initialize: (attrs = {}, options = {}) ->
definitions = @constructor.fields()
attributes = {}
for name, definition of definitions
attributes[name] = definition.defaultValue(@) unless attrs.hasOwnProperty(name)
@attributes = attributes
@changes = {}
@errors = {}
@readOnly = if options.hasOwnProperty("readOnly") then options.readOnly else false
@persistent = if options.hasOwnProperty("persistent") then options.persisted else false
@attributes[key] = value for key, value of attrs
require './model/scope'
require './model/criteria'
require './model/dirty'
require './model/conversion'
require './model/inheritance'
require './model/relation'
require './model/relations'
require './model/attribute'
require './model/attributes'
require './model/persistence'
require './model/scopes'
require './model/serialization'
require './model/validator'
require './model/validations'
require './model/timestamp'
require './model/locale/en'
Tower.Model.include Tower.Support.Callbacks
Tower.Model.include Tower.Model.Conversion
Tower.Model.include Tower.Model.Dirty
Tower.Model.include Tower.Model.Criteria
Tower.Model.include Tower.Model.Scopes
Tower.Model.include Tower.Model.Persistence
Tower.Model.include Tower.Model.Inheritance
Tower.Model.include Tower.Model.Serialization
Tower.Model.include Tower.Model.Relations
Tower.Model.include Tower.Model.Validations
Tower.Model.include Tower.Model.Attributes
Tower.Model.include Tower.Model.Timestamp
require 'underscore.logger'
global._ = require 'underscore'
_.mixin(require('underscore.string'))
Tower.version = JSON.parse(require("fs").readFileSync(require("path").normalize("#{__dirname}/../../package.json"))).version
Tower.logger = _console
require './support'
require './application'
require './server/application'
require './store'
require './server/store'
require './model'
require './view'
require './controller'
require './server/controller'
require './http'
require './middleware'
require './server/middleware'
require './server/command'
require './server/generator'
Tower.Model.defaultStore = Tower.Store.MongoDB
Tower.View.store(new Tower.Store.FileSystem(["app/views"]))
Tower.root = process.cwd()
Tower.publicPath = process.cwd() + "/public"
Tower.publicCacheDuration = 60 * 1000
Tower.sessionSecret = "tower-session-secret"
Tower.cookieSecret = "tower-cookie-secret"
Tower.render = (string, options = {}) ->
require("mint").render(options.type, string, options)
Tower.domain = "localhost"
Tower.date = ->
require('moment')(arguments...)._d
Tower.run = (argv) ->
(new Tower.Command.Server(argv)).run()
Tower.Support = {}
require './support/array'
require './support/callbacks'
require './support/class'
require './support/eventEmitter'
require './support/i18n'
require './support/number'
require './support/object'
require './support/regexp'
require './support/string'
require './support/url'
require './support/locale/en'
class Tower.View extends Tower.Class
@extend
cache: {}
engine: "coffee"
prettyPrint: false
loadPaths: ["app/views"]
componentSuffix: "widget"
hintClass: "hint"
hintTag: "figure"
labelClass: "label"
requiredClass: "required"
requiredAbbr: "*"
requiredTitle: "Required"
errorClass: "error"
errorTag: "output"
validClass: null
optionalClass: "optional"
optionalAbbr: ""
optionalTitle: "Optional"
labelMethod: "humanize"
labelAttribute: "toLabel"
validationMaxLimit: 255
defaultTextFieldSize: null
defaultTextAreaWidth: 300
allFieldsRequiredByDefault: true
fieldListTag: "ol"
fieldListClass: "fields"
fieldTag: "li"
separator: "-"
breadcrumb: " - "
includeBlankForSelectByDefault: true
collectionLabelMethods: ["toLabel", "displayName", "fullName", "name", "title", "toString"]
i18nLookupsByDefault: true
escapeHtmlEntitiesInHintsAndLabels: false
renameNestedAttributes: true
inlineValidations: true
autoIdForm: true
fieldsetClass: "fieldset"
fieldClass: "field"
validateClass: "validate"
legendClass: "legend"
formClass: "form"
idEnabledOn: ["input", "field"] # %w(field label error hint)
widgetsPath: "shared/widgets"
navClass: "list-item"
includeAria: true
activeClass: "active"
navTag: "li"
termsTag: "dl"
termClass: "term"
termKeyClass: "key"
termValueClass: "value"
hintIsPopup: false
listTag: "ul"
pageHeaderId: "header"
pageTitleId: "title"
autoIdNav: false
pageSubtitleId: "subtitle"
widgetClass: "widget"
headerClass: "header"
titleClass: "title"
subtitleClass: "subtitle"
contentClass: "content"
defaultHeaderLevel: 3
termSeparator: ":"
richInput: false
submitFieldsetClass: "submit-fieldset"
addLabel: "+"
removeLabel: "-"
cycleFields: false
alwaysIncludeHintTag: false
alwaysIncludeErrorTag: true
requireIfValidatesPresence: true
localizeWithNamespace: false
localizeWithNestedModel: false
localizeWithInheritance: true
defaultComponentHeaderLevel: 3
helpers: []
metaTags: [
"description",
"keywords",
"author",
"copyright",
"category",
"robots"
]
store: (store) ->
@_store = store if store
@_store ||= new Tower.Store.Memory(name: "view")
renderers: {}
constructor: (context = {}) ->
@_context = context
require './view/helpers'
require './view/rendering'
require './view/component'
require './view/table'
require './view/form'
require './view/helpers/assetHelper'
require './view/helpers/componentHelper'
require './view/helpers/elementHelper'
require './view/helpers/headHelper'
require './view/helpers/renderingHelper'
require './view/helpers/stringHelper'
Tower.View.include Tower.View.Rendering
Tower.View.include Tower.View.Helpers
Tower.View.include Tower.View.AssetHelper
Tower.View.include Tower.View.ComponentHelper
Tower.View.include Tower.View.HeadHelper
Tower.View.include Tower.View.RenderingHelper
Tower.View.include Tower.View.StringHelper
Tower.View.helpers.push Tower.View.AssetHelper
Tower.View.helpers.push Tower.View.ComponentHelper
Tower.View.helpers.push Tower.View.HeadHelper
Tower.View.helpers.push Tower.View.RenderingHelper
Tower.View.helpers.push Tower.View.StringHelper
require './controller/elements'
require './controller/events'
require './controller/handlers'
Tower.Controller.include Tower.Controller.Elements
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.Handlers
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
require './view/formHelper'
require './view/metaHelper'
require './view/validationHelper'
Tower.Controller.Callbacks =
ClassMethods:
beforeAction: ->
@before "action", arguments...
afterAction: ->
@after "action", arguments...
Tower.Controller.Helpers =
ClassMethods:
helper: (object) ->
@_helpers ||= []
@_helpers.push(object)
layout: (layout) ->
@_layout = layout
layout: ->
layout = @constructor._layout
if typeof(layout) == "function" then layout.call(@) else layout
Tower.Controller.Instrumentation =
call: (request, response, next) ->
@request = request
@response = response
@params = @request.params || {}
@cookies = @request.cookies || {}
@query = @request.query || {}
@session = @request.session || {}
@format = @params.format || "html"
@action = @params.action
@headers = {}
@callback = next
@process()
process: ->
@processQuery()
# hacking in logging for now
unless Tower.env.match(/(test|production)/)
console.log " Processing by #{@constructor.name}##{@action} as #{@format.toUpperCase()}"
console.log " Parameters:"
console.log @params
@runCallbacks "action", name: @action, (callback) =>
@[@action].call @, callback
processQuery: ->
clear: ->
@request = null
@response = null
@headers = null
Tower.Controller.Params =
ClassMethods:
params: (options, callback) ->
if typeof options == 'function'
callback = options
options = {}
if options
@_paramsOptions = Tower.Support.Object.extend(@_paramsOptions || {}, options)
callback.call(@)
@_params ||= {}
param: (key, options = {}) ->
@_params ||= {}
@_params[key] = Tower.HTTP.Param.create(key, Tower.Support.Object.extend({}, @_paramsOptions || {}, options))
criteria: ->
return @_criteria if @_criteria
@_criteria = criteria = new Tower.Model.Criteria
parsers = @constructor.params()
params = @params
for name, parser of parsers
if params.hasOwnProperty(name)
criteria.where(parser.toCriteria(params[name]))
criteria
Tower.Controller.Redirecting =
redirectTo: ->
@redirect arguments...
# @todo, better url extraction
redirect: ->
try
args = Tower.Support.Array.args(arguments)
console.log "redirect"
console.log @resourceType
console.log args
options = Tower.Support.Array.extractOptions(args)
console.log options
url = args.shift()
if !url && options.hasOwnProperty("action")
url = switch options.action
when "index", "new"
Tower.urlFor(@resourceType, action: options.action)
when "edit", "show"
Tower.urlFor(@resource, action: options.action)
url ||= "/"
console.log url
@response.redirect url
catch error
console.log error
@callback() if @callback
Tower.Controller.Rendering =
ClassMethods:
addRenderer: (key, block) ->
@renderers()[key] = block
addRenderers: (renderers = {}) ->
@addRenderer(key, block) for key, block of renderers
@
renderers: ->
@_renderers ||= {}
render: ->
@renderToBody @_normalizeRender(arguments...)
renderToBody: (options) ->
@_processRenderOptions(options)
@_renderTemplate(options)
renderToString: ->
@renderToBody @_normalizeRender(arguments...)
sendFile: (path, options = {}) ->
sendData: (data, options = {}) ->
_renderTemplate: (options) ->
_callback = options.callback
callback = (error, body) =>
if error
@status ||= 404
@body = error.stack
else
@status ||= 200
@body = body
_callback.apply @, arguments if _callback
@callback() if @callback
return if @_handleRenderers(options, callback)
@headers["Content-Type"] ||= "text/html"
view = new Tower.View(@)
try
view.render.call view, options, callback
catch error
callback error
_handleRenderers: (options, callback) ->
for name, renderer of Tower.Controller.renderers()
if options.hasOwnProperty(name)
renderer.call @, options[name], options, callback
return true
false
_processRenderOptions: (options = {}) ->
@status = options.status if options.status
@headers["Content-Type"] = options.contentType if options.contentType
@headers["Location"] = @urlFor(options.location) if options.location
@
_normalizeRender: ->
@_normalizeOptions @_normalizeArgs(arguments...)
_normalizeArgs: ->
args = Tower.Support.Array.args(arguments)
if typeof args[0] == "string"
action = args.shift()
if typeof args[0] == "object"
options = args.shift()
if typeof args[0] == "function"
callback = args.shift()
options ||= {}
if action
key = if !!action.match(/\//) then "file" else "action"
options[key] = action
options.callback = callback if callback
options
_normalizeOptions: (options = {}) ->
options.partial = @action if options.partial == true
options.prefixes ||= []
options.prefixes.push @collectionName
options.template ||= (options.file || (options.action || @action))
options
Tower.Controller.Resourceful =
ClassMethods:
resource: (options) ->
@_resourceName = options.name if options.hasOwnProperty("name")
@_resourceType = options.type if options.hasOwnProperty("type")
@_collectionName = options.collectionName if options.hasOwnProperty("collectionName")
@
resourceType: ->
@_resourceType ||= Tower.Support.String.singularize(@name.replace(/(Controller)$/, ""))
resourceName: ->
return @_resourceName if @_resourceName
parts = @resourceType().split(".")
@_resourceName = Tower.Support.String.camelize(parts[parts.length - 1], true)
collectionName: ->
@_collectionName ||= Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), true)
belongsTo: (key, options = {}) ->
options.key = key
options.type ||= Tower.Support.String.camelize(options.key)
@_belongsTo = options
actions: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
actions = ["index", "new", "create", "show", "edit", "update", "destroy"]
actionsToRemove = _.difference(actions, args, options.except || [])
for action in actionsToRemove
@[action] = null
delete @[action]
@
index: ->
#@_index arguments...
@_index (format) =>
format.html => @render "index"
format.json => @render json: @collection, status: 200
new: ->
@_new (format) =>
format.html => @render "new"
format.json => @render json: @resource, status: 200
create: (callback) ->
@_create (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
show: ->
@_show (format) =>
format.html => @render "show"
format.json => @render json: @resource, status: 200
edit: ->
@_edit (format) =>
format.html => @render "edit"
format.json => @render json: @resource, status: 200
update: ->
@_update (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
destroy: ->
@_destroy (format) =>
format.html => @redirectTo action: "index"
format.json => @render json: @resource, status: 200
_index: (callback) ->
@findCollection (error, collection) =>
@respondWith collection, callback
_new: (callback) ->
@buildResource (error, resource) =>
return @failure(error) unless resource
@respondWith(resource, callback)
_create: (callback) ->
@buildResource (error, resource) =>
return @failure(error, callback) unless resource
resource.save (error) =>
@respondWithStatus Tower.Support.Object.isBlank(resource.errors), callback
_show: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_edit: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_update: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.updateAttributes @params[@resourceName], (error) =>
@respondWithStatus !!!error && Tower.Support.Object.isBlank(resource.errors), callback
_destroy: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.destroy (error) =>
@respondWithStatus !!!error, callback
respondWithScoped: (callback) ->
@scoped (error, scope) =>
return @failure(error, callback) if error
@respondWith scope.build(), callback
respondWithStatus: (success, callback) ->
options = records: (@resource || @collection)
if callback && callback.length > 1
successResponder = new Tower.Controller.Responder(@, options)
failureResponder = new Tower.Controller.Responder(@, options)
callback.call @, successResponder, failureResponder
if success
successResponder[format].call @
else
failureResponder[format].call @, error
else
Tower.Controller.Responder.respond(@, options, callback)
buildResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
@[@resourceName] = @resource = resource = scope.build(@params[@resourceName])
callback.call @, null, resource if callback
resource
findResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.find @params.id, (error, resource) =>
@[@resourceName] = @resource = resource
callback.call @, error, resource
findCollection: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.all (error, collection) =>
@[@collectionName] = @collection = collection
callback.call @, error, collection if callback
findParent: (callback) ->
association = @constructor._belongsTo
if association
param = association.param || "#{association.key}Id"
parentClass = Tower.constant(association.type)
parentClass.find @params[param], (error, parent) =>
throw error if error && !callback
unless error
@parent = @[association.key] = parent
callback.call @, error, parent if callback
else
callback.call @, null, false if callback
false
scoped: (callback) ->
callbackWithScope = (error, scope) =>
callback.call @, error, scope.where(@criteria())
if @hasParent
@findParent (error, parent) =>
callbackWithScope(error, parent[@collectionName]())
else
callbackWithScope null, Tower.constant(@resourceType)
failure: (resource, callback) ->
callback()
class Tower.Controller.Responder
@respond: (controller, options, callback) ->
responder = new @(controller, options)
responder.respond callback
constructor: (controller, options = {}) ->
@controller = controller
@options = options
@accept(format) for format in @controller.formats
accept: (format) ->
@[format] = (callback) -> @["_#{format}"] = callback
respond: (callback) ->
callback.call @controller, @ if callback
method = @["_#{@controller.format}"]
if method then method.call(@) else @toFormat()
_html: ->
@controller.render action: @controller.action
_json: ->
@controller.render json: @options.records
toFormat: ->
try
if get? || !hasErrors?
@defaultRender()
else
@displayErrors()
catch error
@_apiBehavior(error)
_navigationBehavior: (error) ->
if get?
throw error
else if hasErrors? && defaultAction
@render action: @defaultAction
else
@redirectTo @navigationLocation
_apiBehavior: (error) ->
#throw error unless resourceful?
if get?
@display resource
else if post?
@display resource, status: "created", location: @apiLocation
else
@head "noContent"
isResourceful: ->
@resource.hasOwnProperty("to#{@format.toUpperCase()}")
resourceLocation: ->
@options.location || @resources
defaultRender: ->
@defaultResponse.call(options)
display: (resource, givenOptions = {}) ->
@controller.render _.extend givenOptions, @options, format: @resource
displayErrors: ->
@controller.render format: @resourceErrors, status: "unprocessableEntity"
hasErrors: ->
@resource.respondTo?("errors") && !@resource.errors.empty?
defaultAction: ->
@action ||= ACTIONS_FOR_VERBS[request.requestMethodSymbol]
resourceErrors: ->
if @hasOwnProperty("#{format}ResourceErrors") then @["#{format}RresourceErrors"] else @resource.errors
jsonResourceErrors: ->
errors: @resource.errors
Tower.Controller.Responding =
ClassMethods:
respondTo: ->
mimes = @mimes()
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
only = Tower.Support.Object.toArray(options.only) if options.only
except = Tower.Support.Object.toArray(options.except) if options.except
for name in args
mimes[name] = {}
mimes[name].only = only if only
mimes[name].except = except if except
@
mimes: ->
@_mimes ||= {json: {}, html: {}}
respondTo: (block) ->
Tower.Controller.Responder.respond(@, {}, block)
respondWith: ->
args = Tower.Support.Array.args(arguments)
callback = null
if typeof(args[args.length - 1]) == "function"
callback = args.pop()
if typeof(args[args.length - 1]) == "object" && !(args[args.length - 1] instanceof Tower.Model)
options = args.pop()
else
options = {}
options ||= {}
options.records = args[0]
Tower.Controller.Responder.respond(@, options, callback)
_mimesForAction: ->
action = @action
result = []
mimes = @constructor.mimes()
for mime, config of mimes
success = false
if config.except
success = !_.include(config.except, action)
else if config.only
success = _.include(config.only, action)
else
success = true
result.push mime if success
result
class Tower.HTTP.Agent
constructor: (attributes = {}) ->
_.extend @, attributes
toJSON: ->
family: @family
major: @major
minor: @minor
patch: @patch
version: @version
os: @os
name: @name
class Tower.HTTP.Cookies
@parse: (string = document.cookie) ->
result = {}
pairs = string.split(/[;,] */);
for pair in pairs
eqlIndex = pair.indexOf('=')
key = pair.substring(0, eqlIndex).trim().toLowerCase()
value = pair.substring(++eqlIndex, pair.length).trim()
# quoted values
value = value.slice(1, -1) if '"' == value[0]
# only assign once
if result[key] == undefined
value = value.replace(/\+/g, ' ')
try
result[key] = decodeURIComponent(value)
catch error
if error instanceof URIError
result[key] = value
else
throw err
new @(result)
constructor: (attributes = {}) ->
@[key] = value for key, value of attributes
class Tower.HTTP.Param
@perPage: 20
@sortDirection: "ASC"
@sortKey: "sort" # or "order", etc.
@limitKey: "limit" # or "perPage", etc.
@pageKey: "page"
@separator: "_" # or "-"
@create: (key, options) ->
options.type ||= "String"
new Tower.HTTP.Param[options.type](key, options)
constructor: (key, options = {}) ->
@controller = options.controller
@key = key
@attribute = options.as || @key
@modelName = options.modelName
@namespace = Tower.Support.String.pluralize(@modelName) if modelName?
@exact = options.exact || false
@default = options.default
parse: (value) -> value
render: (value) -> value
toCriteria: (value) ->
nodes = @parse(value)
criteria = new Tower.Model.Criteria
for set in nodes
for node in set
attribute = node.attribute
operator = node.operators[0]
conditions = {}
if operator == "$eq"
conditions[attribute] = node.value
else
conditions[attribute] = {}
conditions[attribute][operator] = node.value
criteria.where(conditions)
criteria
parseValue: (value, operators) ->
namespace: @namespace, key: @key, operators: operators, value: value, attribute: @attribute
_clean: (string) ->
string.replace(/^-/, "").replace(/^\+-/, "").replace(/^'|'$/, "").replace("+", " ").replace(/^\^/, "").replace(/\$$/, "").replace(/^\s+|\s+$/, "")
require './param/array'
require './param/date'
require './param/number'
require './param/string'
class Tower.HTTP.Request
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@method = data.method || "GET"
class Tower.HTTP.Response
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@headerSent = false
@statusCode = 200
@body = ""
writeHead: (statusCode, headers) ->
@statusCode = statusCode
@headers = headers
setHeader: (key, value) ->
throw new Error("Headers already sent") if @headerSent
@headers[key] = value
write: (body = '') ->
@body += body
end: (body = '') ->
@body += body
@sent = true
@headerSent = true
redirect: (path, options = {}) ->
global.History.push options, null, path if global.History
class Tower.HTTP.Route extends Tower.Class
@store: ->
@_store ||= []
@create: (route) ->
@store().push(route)
@all: ->
@store()
@clear: ->
@_store = []
@draw: (callback) ->
callback.apply(new Tower.HTTP.Route.DSL(@))
@findController: (request, response, callback) ->
routes = Tower.Route.all()
for route in routes
controller = route.toController request
break if controller
if controller
controller.call request, response, ->
callback(controller)
else
callback(null)
controller
toController: (request) ->
match = @match(request)
return null unless match
method = request.method.toLowerCase()
keys = @keys
params = Tower.Support.Object.extend({}, @defaults, request.query || {}, request.body || {})
match = match[1..-1]
for capture, i in match
params[keys[i].name] ||= if capture then decodeURIComponent(capture) else null
controller = @controller
params.action = controller.action if controller
request.params = params
controller = new (Tower.constant(Tower.namespaced(@controller.className))) if controller
controller
constructor: (options) ->
options ||= options
@path = options.path
@name = options.name
@method = (options.method || "GET").toUpperCase()
@ip = options.ip
@defaults = options.defaults || {}
@constraints = options.constraints
@options = options
@controller = options.controller
@keys = []
@pattern = @extractPattern(@path)
@id = @path
if @controller
@id += @controller.name + @controller.action
match: (requestOrPath) ->
if typeof requestOrPath == "string" then return @pattern.exec(requestOrPath)
path = requestOrPath.location.path
return null unless requestOrPath.method.toUpperCase() == @method
match = @pattern.exec(path)
return null unless match
return null unless @matchConstraints(requestOrPath)
match
matchConstraints: (request) ->
constraints = @constraints
switch typeof(constraints)
when "object"
for key, value of constraints
switch typeof(value)
when "string", "number"
return false unless request[key] == value
when "function", "object"
# regexp?
return false unless !!request.location[key].match(value)
when "function"
return constraints.call(request, request)
else
return false
return true
urlFor: (options = {}) ->
result = @path
result = result.replace(new RegExp(":#{key}\\??", "g"), value) for key, value of options
result = result.replace(new RegExp("\\.?:\\w+\\??", "g"), "")
result
extractPattern: (path, caseSensitive, strict) ->
return path if path instanceof RegExp
self = @
return new RegExp('^' + path + '$') if path == "/"
path = path.replace(/(\(?)(\/)?(\.)?([:\*])(\w+)(\))?(\?)?/g, (_, open, slash, format, symbol, key, close, optional) ->
optional = (!!optional) || (open + close == "()")
splat = symbol == "*"
self.keys.push
name: key
optional: !!optional
splat: splat
slash ||= ""
result = ""
result += slash if !optional || !splat
result += "(?:"
# result += slash if optional
if format?
result += if splat then "\\.([^.]+?)" else "\\.([^/.]+?)"
else
result += if splat then "/?(.+)" else "([^/\\.]+)"
result += ")"
result += "?" if optional
result
)
new RegExp('^' + path + '$', if !!caseSensitive then '' else 'i')
Tower.Route = Tower.HTTP.Route
require './route/dsl'
require './route/urls'
require './route/polymorphicUrls'
Tower.HTTP.Route.include Tower.HTTP.Route.Urls
Tower.HTTP.Route.include Tower.HTTP.Route.PolymorphicUrls
Tower.HTTP.Sync =
ajax: ->
webSockets: ->
class Tower.HTTP.Url
@key: ["source", "protocol", "host", "userInfo", "user", "password", "hostname", "port", "relative", "path", "directory", "file", "query", "fragment"]
@aliases:
anchor: "fragment"
@parser:
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
@querystringParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@fragmentParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@typeParser: /(youtube|vimeo|eventbrite)/
parse: (string) ->
key = @constructor.key
string = decodeURI(string)
parsed = @constructor.parser[(if @strictMode or false then "strict" else "loose")].exec(string)
attributes = {}
@params = params = {}
@fragment = fragment = params: {}
i = 14
while i--
attributes[key[i]] = parsed[i] || ""
attributes["query"].replace @constructor.querystringParser, ($0, $1, $2) ->
params[$1] = $2 if $1
attributes["fragment"].replace @constructor.fragmentParser, ($0, $1, $2) ->
fragment.params[$1] = $2 if $1
@segments = attributes.path.replace(/^\/+|\/+$/g, "").split("/")
fragment.segments = attributes.fragment.replace(/^\/+|\/+$/g, "").split("/")
@[key] ||= value for key, value of attributes
@root = (if attributes.host then attributes.protocol + "://" + attributes.hostname + (if attributes.port then ":" + attributes.port else "") else "")
domains = @hostname.split(".")
@domain = domains[(domains.length - 1 - @depth)..(domains.length - 1)].join(".")
@subdomains = domains[0..(domains.length - 2 - @depth)]
@subdomain = @subdomains.join(".")
@port = parseInt(@port) if @port?
constructor: (url, depth = 1, strictMode) ->
@strictMode = strictMode or false
@depth = depth || 1
@url = url ||= window.location.toString() if window?
@parse(url)
class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = name
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
Tower.Model.Attributes =
ClassMethods:
field: (name, options) ->
@fields()[name] = new Tower.Model.Attribute(@, name, options)
fields: ->
@_fields ||= {}
get: (name) ->
unless @has(name)
field = @constructor.fields()[name]
@attributes[name] = field.defaultValue(@) if field
@attributes[name]
# post.set $pushAll: tags: ["ruby"]
# post.set $pushAll: tags: ["javascript"]
# post.attributes["tags"] #=> ["ruby", "javascript"]
# post.changes["tags"] #=> [[], ["ruby", "javascript"]]
# post.set $pop: tags: "ruby"
# post.attributes["tags"] #=> ["javascript"]
# post.changes["tags"] #=> [[], ["javascript"]]
# if the changes looked like this:
# post.changes["tags"] #=> [["ruby", "javascript"], ["javascript", "node.js"]]
# then the updates would be
# post.toUpdates() #=> {$popAll: {tags: ["ruby"]}, $pushAll: {tags: ["node.js"]}}
# popAll = _.difference(post.changes["tags"][0], post.changes["tags"][1])
# pushAll = _.difference(post.changes["tags"][1], post.changes["tags"][0])
set: (key, value) ->
if typeof key == "object"
updates = key
else
updates = {}
updates[key] = value
@_set(key, value) for key, value of updates
_set: (key, value) ->
@_attributeChange(key, value)
@attributes[key] = value
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
has: (key) ->
@attributes.hasOwnProperty(key)
Tower.Model.Conversion =
ClassMethods:
baseClass: ->
if @__super__ && @__super__.constructor.baseClass && @__super__.constructor != Tower.Model
@__super__.constructor.baseClass()
else
@
toParam: ->
return undefined if @ == Tower.Model
@metadata().paramNamePlural
toKey: ->
@metadata().paramName
# @url "/posts/:postId/comment"
# @url parent: "post"
# @url (model) -> return "/something"
url: (options) ->
@_url = switch typeof options
when "object"
if options.parent
url = "/#{Tower.Support.String.parameterize(Tower.Support.String.pluralize(options.parent))}/:#{Tower.Support.String.camelize(options.parent, true)}/#{@toParam()}"
else
options
collectionName: ->
Tower.Support.String.camelize(Tower.Support.String.pluralize(@name), true)
resourceName: ->
Tower.Support.String.camelize(@name, true)
# inheritance_column
metadata: ->
className = @name
metadata = @metadata[className]
return metadata if metadata
namespace = Tower.namespace()
name = Tower.Support.String.camelize(className, true)
namePlural = Tower.Support.String.pluralize(name)
classNamePlural = Tower.Support.String.pluralize(className)
paramName = Tower.Support.String.parameterize(name)
paramNamePlural = Tower.Support.String.parameterize(namePlural)
modelName = "#{namespace}.#{className}"
controllerName = "#{namespace}.#{classNamePlural}Controller"
@metadata[className] =
name: name
namePlural: namePlural
className: className
classNamePlural: classNamePlural
paramName: paramName
paramNamePlural: paramNamePlural
modelName: modelName
controllerName: controllerName
toLabel: ->
@className()
toPath: ->
result = @constructor.toParam()
return "/" if result == undefined
param = @toParam()
result += "/#{param}" if param
result
toParam: ->
id = @get("id")
if id? then String(id) else null
toKey: ->
@constructor.tokey()
toCacheKey: ->
toModel: ->
@
metadata: ->
@constructor.metadata()
class Tower.Model.Criteria
constructor: (args = {}) ->
@[key] = value for key, value of args
@_where ||= []
@_order ||= []
where: (conditions) ->
if conditions instanceof Tower.Model.Criteria
@merge(conditions)
else
@_where.push(conditions)
order: (attribute, direction = "asc") ->
@_order ||= []
@_order.push [attribute, direction]
#@mergeOptions sort: [[attribute, direction]]
asc: (attributes...) ->
@order(attribute) for attribute in attributes
desc: (attributes...) ->
@order(attribute, "desc") for attribute in attributes
allIn: (attributes) ->
@_whereOperator "$all", attributes
anyIn: (attributes) ->
@_whereOperator "$any", attributes
notIn: (attributes) ->
@_whereOperator "$nin", attributes
offset: (number) ->
@_offset = number
#@mergeOptions offset: number
limit: (number) ->
@_limit = number
@mergeOptions limit: number
select: ->
@_fields = Tower.Support.Array.args(arguments)
includes: ->
@_includes = Tower.Support.Array.args(arguments)
page: (number) ->
@offset(number)
paginate: (options) ->
limit = options.perPage || options.limit
page = options.page || 1
@limit(limit)
@offset((page - 1) * limit)
clone: ->
new @constructor(@attributes())
merge: (criteria) ->
attributes = criteria.attributes()
@_where = @_where.concat attributes._where if attributes._where.length > 0
@_order = @_order.concat attributes._order if attributes._order.length > 0
@_offset = attributes._offset if attributes._offset?
@_limit = attributes._limit if attributes._limit?
@_fields = attributes._fields if attributes._fields
@_offset = attributes._offset if attributes._offset?
@
options: ->
options = {}
options.offset = @_offset if @_offset?
options.limit = @_limit if @_limit?
options.fields = @_fields if @_fields
options.sort = @_order if @_order.length > 0
options
conditions: ->
result = {}
for conditions in @_where
Tower.Support.Object.deepMergeWithArrays(result, conditions)
result
attributes: (to = {}) ->
to._where = @_where.concat()
to._order = @_order.concat()
to._offset = @_offset if @_offset?
to._limit = @_limit if @_limit?
to._fields = @_fields if @_fields
to._includes = @_includes if @_includes
to
toQuery: ->
conditions: @conditions(), options: @options()
toUpdate: ->
@toQuery()
toCreate: ->
attributes = {}
options = {}
for conditions in @_where
# tags: $in: ["a", "b"]
# $push: tags: ["c"]
for key, value of conditions
if Tower.Store.isKeyword(key)
for _key, _value of value
attributes[_key] = _value
else if Tower.Support.Object.isHash(value) && Tower.Store.hasKeyword(value)
for _key, _value of value
attributes[key] = _value
else
attributes[key] = value
for key, value of attributes
delete attributes[key] if value == undefined
attributes: attributes, options: options
mergeOptions: (options) ->
options
_whereOperator: (operator, attributes) ->
query = {}
for key, value of attributes
query[key] = {}
query[key][operator] = value
@where query
Tower.Model.Dirty =
isDirty: ->
Tower.Support.Object.isPresent(@changes)
attributeChanged: (name) ->
change = @changes[name]
return false unless change
change[0] != change[1]
attributeChange: (name) ->
change = @changes[name]
return undefined unless change
change[1]
attributeWas: (name) ->
change = @changes[name]
return undefined unless change
change[0]
resetAttribute: (name) ->
array = @changes[name]
@set(name, array[0]) if array
@
toUpdates: ->
result = {}
attributes = @attributes
for key, array of @changes
result[key] = attributes[key]
result.updatedAt ||= new Date
result
_attributeChange: (attribute, value) ->
array = @changes[attribute] ||= []
beforeValue = array[0] ||= @attributes[attribute]
array[1] = value
array = null if array[0] == array[1]
if array then @changes[attribute] = array else delete @changes[attribute]
beforeValue
# @todo
# copied this from acts_as_nested_set, haven't messed with it yet.
Tower.Model.Hierarchical =
ClassMethods:
hierarchical: ->
@field "lft", type: "Integer"
@field "rgt", type: "Integer"
@field "parentId", type: "Integer"
root: (callback) ->
@roots.first(callback)
roots: ->
@where(parentColumnName: null).order(@quotedLeftColumnName())
leaves: ->
@where("#{@quotedRightColumnName()} - #{@quotedLeftColumnName()} = 1").order(@quotedLeftColumnName())
isRoot: ->
!!!@get("parentId")
root: (callback) ->
@selfAndAncestors.where(parentColumnName: null).first(callback)
selfAndAncestors: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} <= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} >= ?", left, right
])
ancestors: ->
@withoutSelf @selfAndAncestors
selfAndSiblings: ->
@nestedSetScope().where(parentColumnName: parentId)
siblings: ->
@withoutSelf @selfAndSiblings()
leaves: ->
@descendants().where("#{self.class.quotedTableName}.#{quotedRightColumnName} - #{self.class.quotedTableName}.#{quotedLeftColumnName} = 1")
level: (callback) ->
if get('parentId') == null then 0 else ancestors().count(callback)
selfAndDescendants: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} >= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} <= ?", left, right
])
descendants: ->
@withoutSelf @selfAndDescendants()
isDescendantOf: (other) ->
other.left < self.left && self.left < other.right && sameScope?(other)
moveLeft: ->
@moveToLeftOf @leftSibling()
moveRight: ->
@moveToRightOf @rightSibling()
moveToLeftOf: (node) ->
@moveTo node, "left"
moveToRightOf: (node) ->
@moveTo node, "right"
moveToChildOf: (node) ->
@moveTo node, "child"
moveToRoot: ->
@moveTo null, "root"
moveTo: (target, position) ->
@runCallbacks "move", ->
isOrIsDescendantOf: (other) ->
other.left <= self.left && self.left < other.right && sameScope?(other)
isAncestorOf: (other) ->
self.left < other.left && other.left < self.right && sameScope?(other)
isOrIsAncestorOf: (other) ->
self.left <= other.left && other.left < self.right && sameScope?(other)
sameScope: (other) ->
Array(actsAsNestedSetOptions.scope).all (attr) ->
self.send(attr) == other.send(attr)
leftSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} < ?", left]).
order("#{self.class.quotedTableName}.#{quotedLeftColumnName} DESC").last
rightSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} > ?", left]).first
Tower.Model.Inheritance =
_computeType: ->
Tower.Model.Persistence =
ClassMethods:
defaultStore: if Tower.client then Tower.Store.Memory else Tower.Store.MongoDB
store: (value) ->
return @_store if !value && @_store
if typeof value == "function"
@_store = new value(name: @collectionName(), type: Tower.namespaced(@name))
else if typeof value == "object"
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
Tower.Support.Object.extend @_store, value
else if value
@_store = value
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
@_store
load: (records) ->
@store().load(records)
InstanceMethods:
# Create or update the record.
#
# @example Default save
# user.save -> console.log "saved"
#
# @example Save without validating
# user.save validate: false, -> console.log "saved"
save: (options, callback) ->
throw new Error("Record is read only") if @readOnly
if typeof options == "function"
callback = options
options = {}
options ||= {}
unless options.validate == false
@validate (error) =>
if error
callback.call @, null, false if callback
else
@_save callback
else
@_save callback
@
updateAttributes: (attributes, callback) ->
@set(attributes)
@_update(attributes, callback)
destroy: (callback) ->
if @isNew()
callback.call @, null if callback
else
@_destroy callback
@
delete: (callback) ->
@destroy(callback)
isPersisted: ->
!!(@persistent)# && @attributes.hasOwnProperty("id") && @attributes.id != null && @attributes.id != undefined)
isNew: ->
!!!@isPersisted()
reload: ->
store: ->
@constructor.store()
_save: (callback) ->
@runCallbacks "save", (block) =>
complete = @_callback(block, callback)
if @isNew()
@_create(complete)
else
@_update(@toUpdates(), complete)
_create: (callback) ->
@runCallbacks "create", (block) =>
complete = @_callback(block, callback)
@constructor.create @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_update: (updates, callback) ->
@runCallbacks "update", (block) =>
complete = @_callback(block, callback)
@constructor.update @get("id"), updates, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_destroy: (callback) ->
@runCallbacks "destroy", (block) =>
complete = @_callback(block, callback)
@constructor.destroy @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@persistent = false
@changes = {}
delete @attributes.id
complete.call(@, error)
@
# @todo
# https://github.com/technoweenie/coffee-resque
Tower.Model.Queue =
ClassMethods:
enqueue: ->
class Tower.Model.Relation extends Tower.Class
# hasMany "commenters", source: "person", sourceType: "User", foreignKey: "userId", type
constructor: (owner, name, options = {}, callback) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@cache = false unless @hasOwnProperty("cache")
@readOnly = false unless @hasOwnProperty("readOnly")
@validate = false unless @hasOwnProperty("validate")
@autoSave = false unless @hasOwnProperty("autoSave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", cacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @cache
if typeof @cache == "string"
@cacheKey = @cache
@cache = true
else
@cacheKey = @singularTargetName + "Ids"
@owner.field @cacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
scoped: (record) ->
new @constructor.Scope(model: @klass(), owner: record, relation: @)
targetKlass: ->
Tower.constant(@targetType)
klass: ->
Tower.constant(@type)
inverse: ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
return relation if relation.targetType == @ownerType
null
class @Scope extends Tower.Model.Scope
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
clone: ->
new @constructor(model: @model, criteria: @criteria.clone(), owner: @owner, relation: @relation)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasOne'
Tower.Model.Relations =
ClassMethods:
# One-to-one association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasOne "address"
#
# class App.Address extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# address = user.createAddress()
#
# @example Example using all the `hasOne` options
# class App.User extends Tower.Model
# @hasOne "location", type: "Address", embed: true, as: "addressable"
#
# class App.Address extends Tower.Model
# @belongsTo "addressable", polymorphic: true
hasOne: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasOne(@, name, options)
# One-to-many association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasMany "comments"
#
# class App.Comment extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# comment = user.comments().create()
#
# @example Example using all the `hasMany` options
# class App.User extends Tower.Model
# @hasMany "comments", as: "commentable", embed: true
#
# class App.Comment extends Tower.Model
# @belongsTo "commentable", polymorphic: true
#
# @param [String] name Name of the association
# @param [Object] options Association options
# @option options [String] as Polymorphic key, if the associated object's relationship is polymorphic
# @option options [Boolean] embed If true, the data store will try to embed the data in the record (MongoDB currently)
hasMany: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasMany(@, name, options)
belongsTo: (name, options) ->
@relations()[name] = new Tower.Model.Relation.BelongsTo(@, name, options)
relations: ->
@_relations ||= {}
relation: (name) ->
relation = @relations()[name]
throw new Error("Relation '#{name}' does not exist on '#{@name}'") unless relation
relation
relation: (name) ->
@constructor.relation(name).scoped(@)
buildRelation: (name, attributes, callback) ->
@relation(name).build(attributes, callback)
createRelation: (name, attributes, callback) ->
@relation(name).create(attributes, callback)
destroyRelations: ->
class Tower.Model.Scope extends Tower.Class
constructor: (options = {}) ->
@model = options.model
@criteria = options.criteria || new Tower.Model.Criteria
@store = @model.store()
toQuery: (sortDirection) ->
@toCriteria(sortDirection).toQuery()
toCriteria: (sortDirection) ->
criteria = @criteria.clone()
if sortDirection || !criteria._order.length > 0
sort = @model.defaultSort()
criteria[sortDirection || sort.direction](sort.name) if sort
criteria
toCreate: ->
@toQuery()
toUpdate: ->
@toQuery()
toDestroy: ->
merge: (scope) ->
@criteria.merge(scope.criteria)
clone: ->
new @constructor(model: @model, criteria: @criteria.clone())
_extractArgs: (args, opts = {}) ->
args = Tower.Support.Array.args(args)
callback = Tower.Support.Array.extractBlock(args)
last = args[args.length - 1]
if opts.data && (Tower.Support.Object.isHash(last) || Tower.Support.Object.isArray(last))
data = args.pop()
if Tower.Support.Object.isHash(args[args.length - 1])
if data
options = data
data = args.pop()
else
if Tower.Support.Object.isBaseObject(args[args.length - 1])
options = args.pop()
data = {} unless opts.data
data ||= {}
criteria = @criteria.clone()
options ||= {}
options.instantiate = true unless options.hasOwnProperty("instantiate")
ids = _.flatten(args) if opts.ids && args.length > 0
if ids && ids.length > 0
ids = _.map(ids, (idOrRecord) -> if idOrRecord instanceof Tower.Model then idOrRecord.get("id") else idOrRecord)
criteria.where id: $in: ids
criteria: criteria, data: data, callback: callback, options: options
require './scope/finders'
require './scope/persistence'
require './scope/queries'
Tower.Model.Scope.include Tower.Model.Scope.Finders
Tower.Model.Scope.include Tower.Model.Scope.Persistence
Tower.Model.Scope.include Tower.Model.Scope.Queries
for key in Tower.Model.Scope.queryMethods
do (key) =>
Tower.Model.Scope::[key] = ->
clone = @clone()
clone.criteria[key](arguments...)
clone
Tower.Model.Scopes =
ClassMethods:
scope: (name, scope) ->
@[name] = if scope instanceof Tower.Model.Scope then scope else @where(scope)
scoped: ->
scope = new Tower.Model.Scope(model: @)
scope.where(type: @name) if @baseClass().name != @name
scope
defaultSort: (object) ->
@_defaultSort = object if object
@_defaultSort ||= {name: "createdAt", direction: "desc"}
for key in Tower.Model.Scope.queryMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.finderMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.persistenceMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
Tower.Model.Serialization =
ClassMethods:
fromJSON: (data) ->
records = JSON.parse(data)
records = [records] unless records instanceof Array
for record, i in records
records[i] = new @(record)
records
toJSON: (records, options = {}) ->
result = []
result.push(record.toJSON()) for record in records
result
toJSON: (options) ->
@_serializableHash(options)
clone: ->
new @constructor(Tower.Support.Object.clone(@attributes))
_serializableHash: (options = {}) ->
result = {}
attributeNames = Tower.Support.Object.keys(@attributes)
if only = options.only
attributeNames = _.union(Tower.Support.Object.toArray(only), attributeNames)
else if except = options.except
attributeNames = _.difference(Tower.Support.Object.toArray(except), attributeNames)
for name in attributeNames
result[name] = @_readAttributeForSerialization(name)
if methods = options.methods
methodNames = Tower.Support.Object.toArray(methods)
for name in methods
result[name] = @[name]()
# TODO: async!
if includes = options.include
includes = Tower.Support.Object.toArray(includes)
for include in includes
unless Tower.Support.Object.isHash(include)
tmp = {}
tmp[include] = {}
include = tmp
tmp = undefined
for name, opts of include
records = @[name]().all()
for record, i in records
records[i] = record._serializableHash(opts)
result[name] = records
result
_readAttributeForSerialization: (name, type = "json") ->
@attributes[name]
Tower.Model.Sync =
sync: ->
syncAction = @syncAction
@runCallbacks "sync", =>
@runCallbacks "#{syncAction}Sync", =>
@store["#{syncAction}Sync"](@)
updateSyncAction: (action) ->
@syncAction = switch action # create, update, delete
# if it was create, and it's never been synced, then we can just remove it from memory and be all cool
when "delete" then "delete"
when "update"
switch @syncAction
when "create" then "create"
else
"update"
else
switch @syncAction
when "update" then "delete"
else
action
Tower.Model.Timestamp =
ClassMethods:
timestamps: ->
@include Tower.Model.Timestamp.CreatedAt
@include Tower.Model.Timestamp.UpdatedAt
@field "createdAt", type: "Date"
@field "updatedAt", type: "Date"
@before "create", "setCreatedAt"
@before "save", "setUpdatedAt"
CreatedAt:
ClassMethods: {}
setCreatedAt: ->
@set "createdAt", new Date
UpdatedAt:
ClassMethods: {}
setUpdatedAt: ->
@set "updatedAt", new Date
Tower.Model.Validations =
ClassMethods:
validates: ->
attributes = Tower.Support.Array.args(arguments)
options = attributes.pop()
validators = @validators()
for key, value of options
validators.push Tower.Model.Validator.create(key, value, attributes)
validators: ->
@_validators ||= []
validate: (callback) ->
success = false
@runCallbacks "validate", (block) =>
complete = @_callback(block, callback)
validators = @constructor.validators()
errors = @errors = {}
iterator = (validator, next) =>
validator.validateEach @, errors, next
Tower.async validators, iterator, (error) =>
success = true unless error || Tower.Support.Object.isPresent(errors)
complete.call(@, !success)
success
success
class Tower.Model.Validator
@create: (name, value, attributes) ->
switch name
when "presence"
new @Presence(name, value, attributes)
when "count", "length", "min", "max"
new @Length(name, value, attributes)
when "format"
new @Format(name, value, attributes)
constructor: (name, value, attributes) ->
@name = name
@value = value
@attributes = attributes
validateEach: (record, errors, callback) ->
iterator = (attribute, next) =>
@validate record, attribute, errors, (error) =>
next()
Tower.async @attributes, iterator, (error) =>
callback.call(@, error) if callback
success: (callback) ->
callback.call @ if callback
true
failure: (record, attribute, errors, message, callback) ->
errors[attribute] ||= []
errors[attribute].push message
callback.call @, message if callback
false
require './validator/format'
require './validator/length'
require './validator/presence'
require './validator/uniqueness'
require './controller/caching'
require './controller/events'
require './controller/http'
require './controller/sockets'
Tower.Controller.include Tower.Controller.Caching
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.HTTP
Tower.Controller.include Tower.Controller.Sockets
require './controller/renderers'
class Tower.Mailer extends Tower.Class
require './mailer/configuration'
require './mailer/rendering'
Tower.Mailer.include Tower.Mailer.Configuration
Tower.Mailer.include Tower.Mailer.Rendering
Tower.Support.Array =
extractOptions: (args) ->
if typeof args[args.length - 1] == "object" then args.pop() else {}
extractBlock: (args) ->
if typeof args[args.length - 1] == "function" then args.pop() else null
args: (args, index = 0, withCallback = false, withOptions = false) ->
args = Array.prototype.slice.call(args, index, args.length)
if withCallback && !(args.length >= 2 && typeof(args[args.length - 1]) == "function")
throw new Error("You must pass a callback to the render method")
args
# Sort objects by one or more attributes.
#
# cityPrimer = (string) ->
# string.toLowerCase()
# sortObjects deals, ["city", ["price", "desc"]], city: cityPrimer
#
sortBy: (objects) ->
sortings = @args(arguments, 1)
callbacks = if sortings[sortings.length - 1] instanceof Array then {} else sortings.pop()
valueComparator = (x, y) ->
if x > y then 1 else (if x < y then -1 else 0)
arrayComparator = (a, b) ->
x = []
y = []
sortings.forEach (sorting) ->
attribute = sorting[0]
direction = sorting[1]
aValue = a[attribute]
bValue = b[attribute]
unless typeof callbacks[attribute] is "undefined"
aValue = callbacks[attribute](aValue)
bValue = callbacks[attribute](bValue)
x.push(direction * valueComparator(aValue, bValue))
y.push(direction * valueComparator(bValue, aValue))
if x < y then -1 else 1
sortings = sortings.map (sorting) ->
sorting = [sorting, "asc"] unless sorting instanceof Array
if sorting[1] == "desc"
sorting[1] = -1
else
sorting[1] = 1
sorting
objects.sort (a, b) ->
arrayComparator a, b
Tower.Support.Callbacks =
ClassMethods:
before: ->
@appendCallback "before", arguments...
# @example
# class App.User extends Tower.Model
# @before "save", "beforeSave"
#
# beforeSave: (callback) ->
# # before
# callback.call @
# # after
after: ->
@appendCallback "after", arguments...
callback: ->
args = Tower.Support.Array.args(arguments)
args = ["after"].concat args unless args[0].match(/^(?:before|around|after)$/)
@appendCallback args...
removeCallback: (action, phase, run) ->
@
appendCallback: (phase) ->
args = Tower.Support.Array.args(arguments, 1)
if typeof args[args.length - 1] != "object"
method = args.pop()
if typeof args[args.length - 1] == "object"
options = args.pop()
method ||= args.pop()
options ||= {}
callbacks = @callbacks()
for filter in args
callback = callbacks[filter] ||= new Tower.Support.Callbacks.Chain
callback.push phase, method, options
@
prependCallback: (action, phase, run, options = {}) ->
@
callbacks: ->
@_callbacks ||= {}
runCallbacks: (kind, options, block, complete) ->
if typeof options == "function"
complete = block
block = options
options = {}
options ||= {}
chain = @constructor.callbacks()[kind]
if chain
chain.run(@, options, block, complete)
else
block.call @
complete.call @ if complete
_callback: (callbacks...) ->
(error) =>
for callback in callbacks
callback.call(@, error) if callback
class Tower.Support.Callbacks.Chain
constructor: (options = {}) ->
@[key] = value for key, value of options
@before ||= []
@after ||= []
run: (binding, options, block, complete) ->
runner = (callback, next) =>
callback.run(binding, options, next)
Tower.async @before, runner, (error) =>
unless error
if block
switch block.length
when 0
block.call(binding)
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
block.call binding, (error) =>
unless error
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
push: (phase, method, filters, options) ->
@[phase].push new Tower.Support.Callback(method, filters, options)
class Tower.Support.Callback
constructor: (method, conditions = {}) ->
@method = method
@conditions = conditions
conditions.only = Tower.Support.Object.toArray(conditions.only) if conditions.hasOwnProperty("only")
conditions.except = Tower.Support.Object.toArray(conditions.except) if conditions.hasOwnProperty("except")
run: (binding, options, next) ->
conditions = @conditions
if options && options.hasOwnProperty("name")
if conditions.hasOwnProperty("only")
return next() if _.indexOf(conditions.only, options.name) == -1
else if conditions.hasOwnProperty("except")
return next() if _.indexOf(conditions.except, options.name) != -1
method = @method
method = binding[method] if typeof method == "string"
switch method.length
when 0
result = method.call binding
next(if !result then new Error("Callback did not pass") else null)
else
method.call binding, next
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
class Tower.Class
@global: (value) ->
@_global = value unless value == undefined
@_global = true if @_global == undefined
if value == true
global[@name] = @
else if value == false
delete global[@name]
@_global
@alias: (to, from) ->
Tower.Support.Object.alias(@::, to, from)
@accessor: (key, callback) ->
Tower.Support.Object.accessor(@::, key, callback)
@
@getter: (key, callback) ->
Tower.Support.Object.getter(@::, key, callback)
@
@setter: (key) ->
Tower.Support.Object.setter(@::, key)
@
@classAlias: (to, from) ->
Tower.Support.Object.alias(@, to, from)
@
@classAccessor: (key, callback) ->
Tower.Support.Object.accessor(@, key, callback)
@
@classGetter: (key, callback) ->
Tower.Support.Object.getter(@, key, callback)
@
@classSetter: (key) ->
Tower.Support.Object.setter(@, key)
@
@classEval: (block) ->
block.call(@)
@delegate: (key, options = {}) ->
Tower.Support.Object.delegate(@::, key, options)
@
@mixin: (self, object) ->
for key, value of object when key not in specialProperties
self[key] = value
object
@extend: (object) ->
@mixin(@, object)
extended = object.extended
extended.apply(object) if extended
object
@self: (object) ->
@extend object
@include: (object) ->
@extend(object.ClassMethods) if object.hasOwnProperty("ClassMethods")
@include(object.InstanceMethods) if object.hasOwnProperty("InstanceMethods")
@mixin(@::, object)
included = object.included
included.apply(object) if included
object
@className: ->
Tower.Support.Object.functionName(@)
className: ->
@constructor.className()
constructor: ->
@initialize()
initialize: ->
Tower.Support.EventEmitter =
#included: ->
# @events = {}
isEventEmitter: true
events: ->
@_events ||= {}
hasEventListener: (key) ->
Tower.Support.Object.isPresent(@events(), key)
event: (key) ->
@events()[key] ||= new Tower.Event(@, key)
# Examples:
#
# @on "click .item a", "clickItem"
# @on "click", "clickItem", target: ".item a"
#
# Use jQuery to set relavant parent/child elements using jQuery `find`, `parents`, `closest`, etc.
#
# @on "click", "clickItem", selector: ".item a", find: {meta: "span small"}, closest: {title: ".item h1"}
# #=> @titleElement = @targetElement.closest(".item h1")
on: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
if args.length == 0
eventMap = options
options = {}
else
options = {}
if typeof args[args.length - 1] == "object"
eventMap = args.pop()
else
eventMap = {}
eventMap[args.shift()] = args.shift()
# this is essentially what I'm doing above
#switch args.length
# # @on click: "clickHandler", keypress: "keypressHandler"
# when 1
# # @on "click", "clickHandler"
# # @on "click", -> alert '!'
# # @on {click: "clickHandler", keypress: "keypressHandler"}, {type: "socket"}
# when 2
# # @on "click", "clickHandler", type: "socket"
# when 3
for eventType, handler of eventMap
@addEventHandler(eventType, handler, options)
addEventHandler: (type, handler, options) ->
@event(type).addHandler(handler)
mutation: (wrappedFunction) ->
->
result = wrappedFunction.apply(this, arguments)
@event('change').fire(this, this)
result
prevent: (key) ->
@event(key).prevent()
@
allow: (key) ->
@event(key).allow()
@
isPrevented: (key) ->
@event(key).isPrevented()
fire: (key) ->
event = @event(key)
event.fire.call event, Tower.Support.Array.args(arguments, 1)
allowAndFire: (key) ->
@event(key).allowAndFire(Tower.Support.Array.args(arguments, 1))
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
Tower.Support.Object.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".#{options.tense}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
Tower.Support.Number =
isInt: (n) ->
n == +n && n == (n|0)
isFloat: (n) ->
n == +n && n != (n|0)
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
Tower.Support.Object =
extend: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
object[key] = value
object
cloneHash: (options) ->
result = {}
for key, value of options
if @isArray(value)
result[key] = @cloneArray(value)
else if @isHash(value)
result[key] = @cloneHash(value)
else
result[key] = value
result
cloneArray: (value) ->
result = value.concat()
for item, i in result
if @isArray(item)
result[i] = @cloneArray(item)
else if @isHash(item)
result[i] = @cloneHash(item)
result
deepMerge: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
if object[key] && typeof value == 'object'
object[key] = Tower.Support.Object.deepMerge(object[key], value)
else
object[key] = value
object
deepMergeWithArrays: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
oldValue = object[key]
if oldValue
if @isArray(oldValue)
object[key] = oldValue.concat value
else if typeof oldValue == "object" && typeof value == "object"
object[key] = Tower.Support.Object.deepMergeWithArrays(object[key], value)
else
object[key] = value
else
object[key] = value
object
defineProperty: (object, key, options = {}) ->
Object.defineProperty object, key, options
functionName: (fn) ->
return fn.__name__ if fn.__name__
return fn.name if fn.name
fn.toString().match(/\W*function\s+([\w\$]+)\(/)?[1]
alias: (object, to, from) ->
object[to] = object[from]
accessor: (object, key, callback) ->
object._accessors ||= []
object._accessors.push(key)
@getter(key, object, callback)
@setter(key, object)
@
setter: (object, key) ->
unless object.hasOwnProperty("_setAttribute")
@defineProperty object, "_setAttribute",
enumerable: false,
configurable: true,
value: (key, value) ->
@["_#{key}"] = value
object._setters ||= []
object._setters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
set: (value) ->
@["_setAttribute"](key, value)
@
getter: (object, key, callback) ->
unless object.hasOwnProperty("_getAttribute")
@defineProperty object, "_getAttribute",
enumerable: false,
configurable: true,
value: (key) ->
@["_#{key}"]
object._getters ||= []
object._getters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
get: ->
@["_getAttribute"](key) || (@["_#{key}"] = callback.apply(@) if callback)
@
variables: (object) ->
accessors: (object) ->
methods: (object) ->
result = []
for key, value of object
result.push(key) if @isFunction(value)
result
delegate: (object, keys..., options = {}) ->
to = options.to
isFunction = @isFunction(object)
for key in keys
if isFunction
object[key] = ->
@[to]()[key](arguments...)
else
@defineProperty object, key,
enumerable: true,
configurable: true,
get: -> @[to]()[key]
object
isFunction: (object) ->
!!(object && object.constructor && object.call && object.apply)
toArray: (object) ->
if @isArray(object) then object else [object]
keys: (object) ->
Object.keys(object)
isA: (object, isa) ->
isRegExp: (object) ->
!!(object && object.test && object.exec && (object.ignoreCase || object.ignoreCase == false))
isHash: (object) ->
@isObject(object) && !(@isFunction(object) || @isArray(object) || _.isDate(object) || _.isRegExp(object))
isBaseObject: (object) ->
object && object.constructor && object.constructor.name == "Object"
isArray: Array.isArray || (object) ->
toString.call(object) == '[object Array]'
kind: (object) ->
type = typeof(object)
switch type
when "object"
return "array" if _.isArray(object)
return "arguments" if _.isArguments(object)
return "boolean" if _.isBoolean(object)
return "date" if _.isDate(object)
return "regex" if _.isRegExp(object)
return "NaN" if _.isNaN(object)
return "null" if _.isNull(object)
return "undefined" if _.isUndefined(object)
return "object"
when "number"
return "integer" if object == +object && object == (object|0)
return "float" if object == +object && object != (object|0)
return "number"
when "function"
return "regex" if _.isRegExp(object)
return "function"
else
return type
isObject: (object) ->
return object == Object(object)
isPresent: (object) ->
!@isBlank(object)
isBlank: (object) ->
return (object == "") if typeof object == "string"
return false for key, value of object
return true
has: (object, key) ->
object.hasOwnProperty(key)
Tower.Support.RegExp =
regexpEscape: (string) ->
string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
Tower.Support.String =
camelize_rx: /(?:^|_|\-)(.)/g
capitalize_rx: /(^|\s)([a-z])/g
underscore_rx1: /([A-Z]+)([A-Z][a-z])/g
underscore_rx2: /([a-z\d])([A-Z])/g
parameterize: (string) ->
Tower.Support.String.underscore(string).replace("_", "-")
constantize: (string, scope = global) ->
scope[@camelize(string)]
camelize: (string, firstLetterLower) ->
string = string.replace @camelize_rx, (str, p1) -> p1.toUpperCase()
if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string
underscore: (string) ->
string.replace(@underscore_rx1, '$1_$2')
.replace(@underscore_rx2, '$1_$2')
.replace('-', '_').toLowerCase()
singularize: (string) ->
len = string.length
if string.substr(len - 3) is 'ies'
string.substr(0, len - 3) + 'y'
else if string.substr(len - 1) is 's'
string.substr(0, len - 1)
else
string
pluralize: (count, string) ->
if string
return string if count is 1
else
string = count
len = string.length
lastLetter = string.substr(len - 1)
if lastLetter is 'y'
"#{string.substr(0, len - 1)}ies"
else if lastLetter is 's'
string
else
"#{string}s"
capitalize: (string) -> string.replace @capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase()
trim: (string) -> if string then string.trim() else ""
interpolate: (stringOrObject, keys) ->
if typeof stringOrObject is 'object'
string = stringOrObject[keys.count]
unless string
string = stringOrObject['other']
else
string = stringOrObject
for key, value of keys
string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value)
string
# use single quotes, otherwise they're escaped
Tower.Support.String.toQueryValue = (value, negate = "") ->
if Tower.Support.Object.isArray(value)
items = []
for item in value
result = negate
result += item
items.push result
result = items.join(",")
else
result = negate
result += value.toString()
result = result.replace(" ", "+").replace /[#%\"\|<>]/g, (_) -> encodeURIComponent(_)
result
# toQuery likes: 10
# toQuery likes: ">=": 10
# toQuery likes: ">=": 10, "<=": 20
# toQuery tags: ["ruby", "javascript"]
# toQuery tags: "!=": ["java", ".net"]
# #=> tags=-java,-ruby
# toQuery tags: "!=": ["java", ".net"], "==": ["ruby", "javascript"]
# #=> tags=ruby,javascript,-java,-ruby
Tower.Support.String.toQuery = (object, schema = {}) ->
result = []
for key, value of object
param = "#{key}="
type = schema[key] || "string"
negate = if type == "string" then "-" else "^"
if Tower.Support.Object.isHash(value)
data = {}
data.min = value[">="] if value.hasOwnProperty(">=")
data.min = value[">"] if value.hasOwnProperty(">")
data.max = value["<="] if value.hasOwnProperty("<=")
data.max = value["<"] if value.hasOwnProperty("<")
data.match = value["=~"] if value.hasOwnProperty("=~")
data.notMatch = value["!~"] if value.hasOwnProperty("!~")
data.eq = value["=="] if value.hasOwnProperty("==")
data.neq = value["!="] if value.hasOwnProperty("!=")
data.range = data.hasOwnProperty("min") || data.hasOwnProperty("max")
set = []
if data.range && !(data.hasOwnProperty("eq") || data.hasOwnProperty("match"))
range = ""
if data.hasOwnProperty("min")
range += Tower.Support.String.toQueryValue(data.min)
else
range += "n"
range += ".."
if data.hasOwnProperty("max")
range += Tower.Support.String.toQueryValue(data.max)
else
range += "n"
set.push range
if data.hasOwnProperty("eq")
set.push Tower.Support.String.toQueryValue(data.eq)
if data.hasOwnProperty("match")
set.push Tower.Support.String.toQueryValue(data.match)
if data.hasOwnProperty("neq")
set.push Tower.Support.String.toQueryValue(data.neq, negate)
if data.hasOwnProperty("notMatch")
set.push Tower.Support.String.toQueryValue(data.notMatch, negate)
param += set.join(",")
else
param += Tower.Support.String.toQueryValue(value)
result.push param
result.sort().join("&")
Tower.Support.String.extractDomain = (host, tldLength = 1) ->
return null unless @namedHost(host)
parts = host.split('.')
parts[0..parts.length - 1 - 1 + tldLength].join(".")
Tower.Support.String.extractSubdomains = (host, tldLength = 1) ->
return [] unless @namedHost(host)
parts = host.split('.')
parts[0..-(tldLength+2)]
Tower.Support.String.extractSubdomain = (host, tldLength = 1) ->
@extractSubdomains(host, tldLength).join('.')
Tower.Support.String.namedHost = (host) ->
!!!(host == null || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.exec(host))
Tower.Support.String.rewriteAuthentication = (options) ->
if options.user && options.password
"#{encodeURI(options.user)}:#{encodeURI(options.password)}@"
else
""
Tower.Support.String.hostOrSubdomainAndDomain = (options) ->
return options.host if options.subdomain == null && options.domain == null
tldLength = options.tldLength || 1
host = ""
unless options.subdomain == false
subdomain = options.subdomain || @extractSubdomain(options.host, tldLength)
host += "#{subdomain}." if subdomain
host += (options.domain || @extractDomain(options.host, tldLength))
host
# urlFor controller: "posts", action: "index"
# urlFor @user
# urlFor User
# urlFor "admin", @user
# Tower._urlFor({onlyPath: true, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript /i], "!=": ["java"]}}, trailingSlash: false}, {likes: "integer"})
# "?likes=-10..20,^13,^15&tags=ruby,/javascript+/i,-java"
Tower.Support.String.urlFor = (options) ->
unless options.host || options.onlyPath
throw new Error('Missing host to link to! Please provide the :host parameter, set defaultUrlOptions[:host], or set :onlyPath to true')
result = ""
params = options.params || {}
path = (options.path || "").replace(/\/+/, "/")
schema = options.schema || {}
delete options.path
delete options.schema
unless options.onlyPath
port = options.port
delete options.port
unless options.protocol == false
result += options.protocol || "http"
result += ":" unless result.match(Tower.Support.RegExp.regexpEscape(":|//"))
result += "//" unless result.match("//")
result += @rewriteAuthentication(options)
result += @hostOrSubdomainAndDomain(options)
result += ":#{port}" if port
# params.reject! {|k,v| v.toParam.nil? }
if options.trailingSlash
result += path.replace /\/$/, "/"
else
result += path
result += "?#{Tower.Support.String.toQuery(params, schema)}" unless Tower.Support.Object.isBlank(params)
result += "##{Tower.Support.String.toQuery(options.anchor)}" if options.anchor
result
# Tower.urlFor(RW.MongoUser.first(), {onlyPath: false, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript#/i], "!=": ["java"]}}, trailingSlash: true, host: "rituwall.com", user: "lance", password: "pollard", anchor: {likes: 10}})
# "http://lance:pollard@rituwall.com/mongo-users/1?likes=-10..20,-13,-15&tags=ruby,/javascript%23/i,-java#likes=10"
Tower.urlFor = ->
args = Tower.Support.Array.args(arguments)
return null unless args[0]
if args[0] instanceof Tower.Model || (typeof(args[0])).match(/(string|function)/)
last = args[args.length - 1]
if last instanceof Tower.Model || (typeof(last)).match(/(string|function)/)
options = {}
else
options = args.pop()
options ||= args.pop()
result = ""
if options.controller && options.action
route = Tower.Route.find(name: Tower.Support.String.camelize(options.controller).replace(/(Controller)?$/, "Controller"), action: options.action)
if route
result = "/" + Tower.Support.String.parameterize(options.controller)
else
for item in args
result += "/"
if typeof(item) == "string"
result += item
else if item instanceof Tower.Model
result += item.toPath()
else if typeof(item) == "function" # need better, b/c i'm meaning constructor here
result += item.toParam()
result += switch options.action
when "new" then "/new"
when "edit" then "/edit"
else
""
options.onlyPath = true unless options.hasOwnProperty("onlyPath")
options.path = result
Tower.Support.String.urlFor(options)
Tower.Support.String.parameterize = (string) ->
Tower.Support.String.underscore(string).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '')
Tower.Support.Url = {}
class Tower.View.Component
@render: ->
args = Tower.Support.Array.args(arguments)
template = args.shift()
block = Tower.Support.Array.extractBlock(args)
unless args[args.length - 1] instanceof Tower.Model || typeof(args[args.length - 1]) != "object"
options = args.pop()
options ||= {}
options.template = template
(new @(args, options)).render(block)
constructor: (args, options) ->
@[key] = value for key, value of options
tag: (key, args...) ->
@template.tag key, args
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
class Tower.View.Form extends Tower.View.Component
constructor: (args, options) ->
super
@model = args.shift() || new Tower.Model
if typeof @model == "string"
klass = Tower.constant(Tower.Support.String.camelize(@model))
@model = if klass then new klass else null
@attributes = @_extractAttributes(options)
render: (callback) ->
@tag "form", @attributes, =>
@tag "input", type: "hidden", name: "_method", value: @attributes["data-method"]
if callback
builder = new Tower.View.Form.Builder([],
template: @template
tabindex: 1
accessKeys: {}
model: @model
)
builder.render(callback)
_extractAttributes: (options = {}) ->
attributes = options.html || {}
attributes.action = options.url || Tower.urlFor(@model)
attributes.class = options["class"] if options.hasOwnProperty("class")
#@mergeClass attributes, config.formClass
attributes.id = options.id if options.hasOwnProperty("id")
attributes.id ||= Tower.Support.String.parameterize("#{@model.constructor.name}-form")
attributes.enctype = "multipart/form-data" if (options.multipart || attributes.multipart == true)
attributes.role = "form"
attributes.novalidate = "true" # needs to be true b/c the error popups are horribly ugly!# if options.validate == false
attributes["data-validate"] = options.validate.toString() if options.hasOwnProperty("validate")
method = attributes.method || options.method
if !method || method == ""
if @model && @model.get("id")
method = "put"
else
method = "post"
attributes["data-method"] = method
attributes.method = if method == "get" then "get" else "post"
attributes
require './form/builder'
require './form/field'
require './form/fieldset'
Tower.View.Helpers =
titleTag: (title) ->
"<title>#{title}</title>"
metaTag: (name, content) ->
"""<meta name="#{name}" content="#{content}"/>"""
tag: (name, options) ->
linkTag: (title, path, options) ->
imageTag: (path, options) ->
csrfMetaTag: ->
@metaTag("csrf-token", @request.session._csrf)
contentTypeTag: (type = "UTF-8") ->
"<meta charset=\"#{type}\" />"
javascriptTag: (path) ->
"<script type=\"text/javascript\" src=\"#{path}\" ></script>"
stylesheetTag: (path) ->
"<link href=\"#{path}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\"/>"
mobileTags: ->
"""
<meta content='yes' name='apple-mobile-web-app-capable'>
<meta content='yes' name='apple-touch-fullscreen'>
<meta content='initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width' name='viewport'>
"""
Tower.View.Rendering =
render: (options, callback) ->
options.type ||= @constructor.engine
options.layout = @_context.layout() if !options.hasOwnProperty("layout") && @_context.layout
options.locals = @_renderingContext(options)
@_renderBody options, (error, body) =>
return callback(error, body) if error
@_renderLayout(body, options, callback)
partial: (path, options, callback) ->
if typeof options == "function"
callback = options
options = {}
options ||= {}
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
@_renderString(template, options, callback)
_renderBody: (options, callback) ->
if options.text
callback(null, options.text)
else if options.json
callback(null, if typeof(options.json) == "string" then options.json else JSON.stringify(options.json))
else
unless options.inline
options.template = @_readTemplate(options.template, options.prefixes, options.type)
@_renderString(options.template, options, callback)
_renderLayout: (body, options, callback) ->
if options.layout
layout = @_readTemplate("layouts/#{options.layout}", [], options.type)
options.locals.body = body
@_renderString(layout, options, callback)
else
callback(null, body)
_renderString: (string, options = {}, callback) ->
if !!options.type.match(/coffee/)
e = null
result = null
# tmp hack
coffeekup = if Tower.client then global.CoffeeKup else require("coffeekup")
try
locals = options.locals
locals.renderWithEngine = @renderWithEngine
locals._readTemplate = @_readTemplate
locals.cache = Tower.env != "development"
locals.format = true
hardcode = {}
for helper in Tower.View.helpers
hardcode = _.extend(hardcode, helper)
hardcode = _.extend(hardcode, tags: coffeekup.tags)
locals.hardcode = hardcode
locals._ = _
result = coffeekup.render string, locals
catch error
e = error
callback e, result
else if options.type
mint = require "mint"
engine = require("mint").engine(options.type)
mint[engine](string, options.locals, callback)
else
mint = require "mint"
engine = require("mint")
options.locals.string = string
engine.render(options.locals, callback)
_renderingContext: (options) ->
locals = this
_ref = @_context
for key of _ref
value = _ref[key]
locals[key] = value unless key.match(/^(constructor|head)/)
#newlocals = {}
#newlocals.locals = locals
#locals = newlocals
locals = Tower.Support.Object.extend(locals, options.locals)
locals.pretty = true if @constructor.prettyPrint
locals
_readTemplate: (template, prefixes, ext) ->
return template unless typeof template == "string"
# tmp
result = @constructor.cache["app/views/#{template}"] ||= @constructor.store().find(path: template, ext: ext, prefixes: prefixes)
throw new Error("Template '#{template}' was not found.") unless result
result
renderWithEngine: (template, engine) ->
if Tower.client
"(#{template}).call(this);"
else
mint = require("mint")
mint[mint.engine(engine || "coffee")] template, {}, (error, result) ->
console.log error if error
class Tower.View.Table extends Tower.View.Component
constructor: (args, options) ->
super
recordOrKey = args.shift()
@key = @recordKey(recordOrKey)
@rowIndex = 0
@cellIndex = 0
@scope = "table"
@headers = []
options.summary ||= "Table for #{_.titleize(@key)}"
#options.class = ["data-table", options.class].compact.uniq.join(" ")
options.role = "grid"
options.class = @addClass(options.class || "", ["table"])
data = options.data ||= {}
#data.url = options.url || @template.controller.request.path
#data.for = options.for || options.model || @key
data.total = options.total if options.hasOwnProperty("total")
data.page = options.page if options.hasOwnProperty("page")
data.count = options.count if options.hasOwnProperty("count")
aria = options.aria || {}
delete options.aria
aria["aria-multiselectable"] = false unless aria.hasOwnProperty("aria-multiselectable") || options.multiselect == true
options.id ||= "#{recordOrKey}-table"
@options =
summary: options.summary
role: options.role
data: options.data
class: options.class
render: (block) ->
@tag "table", @options, =>
block(@) if block
null
tableQueryRowClass: ->
["search-row", if queryParams.except("page", "sort").blank? then null else "search-results"].compact.join(" ")
linkToSort: (title, attribute, options = {}) ->
sortParam = sortValue(attribute, oppositeSortDirection(attribute))
linkTo title, withParams(request.path, sort: sortParam), options
nextPagePath: (collection) ->
withParams(request.path, page: collection.nextPage)
prevPagePath: (collection) ->
withParams(request.path, page: collection.prevPage)
firstPagePath: (collection) ->
withParams(request.path, page: 1)
lastPagePath: (collection) ->
withParams(request.path, page: collection.lastPage)
currentPageNum: ->
page = if params.page then params.page else 1
page = 1 if page < 1
page
caption: ->
# scope='col'
head: (attributes = {}, block) ->
@hideHeader = attributes.visible == false
delete attributes.visible
@_section "head", attributes, block
# scope='row'
# <td headers='x'/>
body: (attributes = {}, block) ->
@_section "body", attributes, block
foot: (attributes = {}, block) ->
@_section "foot", attributes, block
_section: (scope, attributes, block) ->
@rowIndex = 0
@scope = scope
@tag "t#{scope}", attributes, block
@rowIndex = 0
@scope = "table"
row: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
attributes.scope = "row"
if @scope == "body"
#attributes.class = [template.cycle("odd", "even"), attributes.class].compact.uniq.join(" ")
attributes.role = "row"
@rowIndex += 1
@cellIndex = 0
@tag "tr", attributes, block
@cellIndex = 0
column: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
@headers.push attributes.id
tag "col", attributes
@cellIndex += 1
# direction => "ascending"
# valid directions: ascending, descending, none, other
# abbr is what the header controls (for sorting)
header: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.abbr ||= value
attributes.role = "columnheader"
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.scope = "col"
attributes.abbr ||= attributes.for if attributes.hasOwnProperty("for")
attributes.abbr ||= value
delete attributes.for
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
sort = attributes.sort == true
delete attributes.sort
if sort
attributes.class = @addClass attributes.class || "", [attributes.sortClass || "sortable"]
attributes.direction ||= "asc"#@template.sortClass(value)
delete attributes.sortClass
label = attributes.label || _.titleize(value.toString())
delete attributes.label
direction = attributes.direction
delete attributes.direction
if direction
attributes["aria-sort"] = direction
attributes.class = [attributes.class, direction].join(" ")
attributes["aria-selected"] = true
else
attributes["aria-sort"] = "none"
attributes["aria-selected"] = false
@headers.push(attributes.id)
if block
@tag "th", attributes, block
else
if sort
@tag "th", attributes, =>
@linkToSort(label, value)
else
@tag "th", attributes, =>
@tag "span", label
@cellIndex += 1
linkToSort: (label, value) ->
direction = "+"
@tag "a", href: "?sort=#{direction}", =>
@tag "span", label
cell: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.role = "gridcell"
attributes.id ||= @idFor("cell", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
#attributes[:"aria-describedby"] = @headers[@cellIndex]
attributes.headers = @headers[@cellIndex]
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
if block
@tag "td", attributes, block
else
@tag "td", value, attributes
@cellIndex += 1
recordKey: (recordOrKey) ->
if typeof recordOrKey == "string"
recordOrKey
else
recordOrKey.constructor.name
idFor: (type, key, value, row_index = @row_index, column_index = @column_index) ->
[key, type, row_index, column_index].compact.map (node) ->
node.replace(/[\s_]/, "-")
end.join("-")
pixelate: (value) ->
if typeof value == "string" then value else "#{value}px"
Tower.Controller.Elements =
ClassMethods:
# @extractElements $(".item a"), find: {meta: "span small"}, closest: {title: ".item h1"}
extractElements: (target, options = {}) ->
result = {}
for method, selectors of options
for key, selector of selectors
result[key] = target[method](selector)
result
processElements: (target, options = {}) ->
@elements = @extractElements(target, options)
clickHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
try
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
catch error
console.log error
return false
invalidForm: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
Tower.Controller.Events =
ClassMethods:
DOM_EVENTS: [
"click",
"dblclick",
"blur",
"error",
"focus",
"focusIn",
"focusOut",
"hover",
"keydown",
"keypress",
"keyup",
"load",
"mousedown",
"mouseenter",
"mouseleave",
"mousemove",
"mouseout",
"mouseover",
"mouseup",
"mousewheel",
"ready",
"resize",
"scroll",
"select",
"submit",
"tap",
"taphold",
"swipe",
"swipeleft",
"swiperight"
]
dispatcher: global
addEventHandler: (name, handler, options) ->
if options.type == "socket" || !name.match(@DOM_EVENT_PATTERN)
@addSocketEventHandler(name, handler, options)
else
@addDomEventHandler(name, handler, options)
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
@io ||= Tower.Application.instance().io.connect(@socketNamespace())
@io.on name, (data) =>
@_dispatch undefined, handler, data
# http://www.ravelrumba.com/blog/event-delegation-jquery-performance/
addDomEventHandler: (name, handler, options) ->
parts = name.split(/\ +/)
name = parts.shift()
selector = parts.join(" ")
options.target = selector if selector && selector != ""
options.target ||= "body"
eventType = name.split(/[\.:]/)[0]
method = @["#{eventType}Handler"]
if method
method.call @, name, handler, options
else
$(@dispatcher).on name, options.target, (event) => @_dispatch handler, options
@
_dispatch: (handler, options = {}) ->
controller = @instance()
controller.elements ||= {}
controller.params ||= {}
_.extend controller.params, options.params if options.params
_.extend controller.elements, options.elements if options.elements
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.Events.ClassMethods.DOM_EVENT_PATTERN = new RegExp("^(#{Tower.Controller.Events.ClassMethods.DOM_EVENTS.join("|")})")
Tower.Controller.Handlers =
ClassMethods:
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
Tower.View.MetaHelper =
title: (string) ->
document.title = string
Tower.View.ValidationHelper =
success: ->
@redirectTo "/"
failure: (error) ->
if error
@flashError(error)
else
@invalidate()
invalidate: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
class Tower.HTTP.Param.Array extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
class Tower.HTTP.Param.Date extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[\s,\+]/)
for string in array
isRange = false
string.replace /([^\.]+)?(\.\.)([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
values.push [@parseValue(string, ["$eq"])] unless isRange
values
parseValue: (value, operators) ->
super(Tower.date(value), operators)
class Tower.HTTP.Param.Number extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
parseValue: (value, operators) ->
super(parseFloat(value), operators)
class Tower.HTTP.Param.String extends Tower.HTTP.Param
parse: (value) ->
arrays = value.split(/(?:[\s|\+]OR[\s|\+]|\||,)/)
for node, i in arrays
values = []
# ([\+\-\^]?[\w@\-_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')
node.replace /([\+\-\^]?[\w@_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')/g, (_, token) =>
negation = false
exact = false
token = token.replace /^(\+?-+)/, (_, $1) ->
negation = $1 && $1.length > 0
""
token = token.replace /^\'(.+)\'$/, (_, $1) ->
exact = $1 && $1.length > 0
$1
if negation
operators = [if exact then "$neq" else "$notMatch"]
else
operators = [if exact then "$eq" else "$match"]
operators.push "^" if !!token.match(/^\+?\-?\^/)
operators.push "$" if !!token.match(/\$$/)
values.push @parseValue(@_clean(token), operators)
_
arrays[i] = values
arrays
class Tower.HTTP.Route.DSL
constructor: ->
@_scope = {}
match: ->
@scope ||= {}
Tower.HTTP.Route.create(new Tower.HTTP.Route(@_extractOptions(arguments...)))
get: ->
@matchMethod("get", Tower.Support.Array.args(arguments))
post: ->
@matchMethod("post", Tower.Support.Array.args(arguments))
put: ->
@matchMethod("put", Tower.Support.Array.args(arguments))
delete: ->
@matchMethod("delete", Tower.Support.Array.args(arguments))
matchMethod: (method, args) ->
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
name = args.shift()
options.method = method
options.action = name
options.name = name
if @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
path = "/#{name}"
path = @_scope.path + path if @_scope.path
@match(path, options)
@
scope: (options = {}, block) ->
originalScope = @_scope ||= {}
@_scope = Tower.Support.Object.extend {}, originalScope, options
block.call(@)
@_scope = originalScope
@
controller: (controller, options, block) ->
options.controller = controller
@scope(options, block)
namespace: (path, options, block) ->
if typeof options == 'function'
block = options
options = {}
else
options = {}
options = Tower.Support.Object.extend(name: path, path: path, as: path, module: path, shallowPath: path, shallowPrefix: path, options)
if options.name && @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
@scope(options, block)
constraints: (options, block) ->
@scope(constraints: options, block)
defaults: (options, block) ->
@scope(defaults: options, block)
resource: (name, options = {}) ->
options.controller = name
@match "#{name}/new", Tower.Support.Object.extend({action: "new"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{name}/", Tower.Support.Object.extend({action: "show"}, options)
@match "#{name}/edit", Tower.Support.Object.extend({action: "edit"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
resources: (name, options, callback) ->
if typeof options == 'function'
callback = options
options = {}
else
options = {}
options.controller ||= name
path = "/#{name}"
path = @_scope.path + path if @_scope.path
if @_scope.name
many = @_scope.name + Tower.Support.String.camelize(name)
else
many = name
one = Tower.Support.String.singularize(many)
@match "#{path}", Tower.Support.Object.extend({name: "#{many}", action: "index"}, options)
@match "#{path}/new", Tower.Support.Object.extend({name: "new#{Tower.Support.String.camelize(one)}", action: "new"}, options)
@match "#{path}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({name: "#{one}", action: "show"}, options)
@match "#{path}/:id/edit", Tower.Support.Object.extend({name: "edit#{Tower.Support.String.camelize(one)}", action: "edit"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
if callback
@scope Tower.Support.Object.extend({path: "#{path}/:#{Tower.Support.String.singularize(name)}Id", name: one}, options), callback
@
collection: ->
member: ->
root: (options) ->
@match '/', Tower.Support.Object.extend(as: "root", options)
_extractOptions: ->
args = Tower.Support.Array.args(arguments)
path = "/" + args.shift().replace(/^\/|\/$/, "")
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
options.to ||= args.shift() if args.length > 0
options.path = path
format = @_extractFormat(options)
options.path = @_extractPath(options)
method = @_extractRequestMethod(options)
constraints = @_extractConstraints(options)
defaults = @_extractDefaults(options)
controller = @_extractController(options)
anchor = @_extractAnchor(options)
name = @_extractName(options)
options = Tower.Support.Object.extend options,
method: method
constraints: constraints
defaults: defaults
name: name
format: format
controller: controller
anchor: anchor
ip: options.ip
options
_extractFormat: (options) ->
_extractName: (options) ->
options.as || options.name
_extractConstraints: (options) ->
Tower.Support.Object.extend(@_scope.constraints || {}, options.constraints || {})
_extractDefaults: (options) ->
options.defaults || {}
_extractPath: (options) ->
"#{options.path}.:format?"
_extractRequestMethod: (options) ->
(options.method || options.via || "GET").toUpperCase()
_extractAnchor: (options) ->
options.anchor
_extractController: (options = {}) ->
to = options.to
if to
to = to.split('#')
if to.length == 1
action = to[0]
else
controller = to[0]
action = to[1]
controller ||= options.controller || @_scope.controller
action ||= options.action
throw new Error("No controller was specified for the route #{options.path}") unless controller
controller = controller.toLowerCase().replace(/(?:[cC]ontroller)?$/, "Controller")
#action = action.toLowerCase()
name: controller, action: action, className: Tower.Support.String.camelize("#{controller}")
Tower.HTTP.Route.PolymorphicUrls =
ClassMethods:
polymorphicUrl: ->
Tower.HTTP.Route.Urls =
ClassMethods:
urlFor: (options) ->
switch typeof(options)
when "string"
options
else
# https://github.com/kieran/barista/blob/master/lib/route.js#L157
{controller, action, host, port, anchor} = options
Tower.Support.I18n.load model:
errors:
presence: "%{attribute} can't be blank"
minimum: "%{attribute} must be a minimum of %{value}"
maximum: "%{attribute} must be a maximum of %{value}"
length: "%{attribute} must be equal to %{value}"
format: "%{attribute} must be match the format %{value}"
inclusion: "%{attribute} is not included in the list"
exclusion: "%{attribute} is reserved"
invalid: "%{attribute} is invalid"
confirmation: "%{attribute} doesn't match confirmation"
accepted: "%{attribute} must be accepted"
empty: "%{attribute} can't be empty"
blank: "%{attribute} can't be blank"
tooLong: "%{attribute} is too long (maximum is %{count} characters)"
tooShort: "%{attribute} is too short (minimum is %{count} characters)"
wrongLength: "%{attribute} is the wrong length (should be %{count} characters)"
taken: "%{attribute} has already been taken"
notANumber: "%{attribute} is not a number"
greaterThan: "%{attribute} must be greater than %{count}"
greaterThanOrEqualTo: "%{attribute} must be greater than or equal to %{count}"
equalTo: "%{attribute} must be equal to %{count}"
lessThan: "%{attribute} must be less than %{count}"
lessThanOrEqualTo: "%{attribute} must be less than or equal to %{count}"
odd: "%{attribute} must be odd"
even: "%{attribute} must be even"
recordInvalid: "Validation failed: %{errors}"
# Append your own errors here or at the model/attributes scope.
fullMessages:
format: "%{message}"
#format: "%{attribute} %{message}"
class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = "#{name}Id"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = (callback) ->
@relation(name).first(callback)
self = @
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Scope extends @Scope
# need to do something here about Reflection
class Tower.Model.Relation.HasMany extends Tower.Model.Relation
class @Scope extends @Scope
create: ->
unless @owner.isPersisted()
throw new Error("You cannot call create unless the parent is saved")
relation = @relation
inverseRelation = relation.inverse()
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
id = @owner.get("id")
if inverseRelation && inverseRelation.cache
array = data[inverseRelation.cacheKey] || []
array.push(id) if array.indexOf(id) == -1
data[inverseRelation.cacheKey] = array
else if relation.foreignKey
data[relation.foreignKey] = id if id != undefined
# must check here if owner is instance of foreignType
data[relation.foreignType] ||= @owner.constructor.name if @relation.foreignType
criteria.where(data)
criteria.mergeOptions(options)
if inverseRelation && inverseRelation.counterCacheKey
defaults = {}
defaults[inverseRelation.counterCacheKey] = 1
criteria.where(defaults)
instantiate = options.instantiate != false
{attributes, options} = criteria.toCreate()
options.instantiate = true
@_create criteria, attributes, options, (error, record) =>
unless error
# add the id to the array on the owner record after it's created
if relation && (relation.cache || relation.counterCache)
if relation.cache
push = {}
push[relation.cacheKey] = record.get("id")
if relation.counterCacheKey
inc = {}
inc[relation.counterCacheKey] = 1
updates = {}
updates["$push"] = push if push
updates["$inc"] = inc if inc
@owner.updateAttributes updates, callback
else
callback.call @, error, record if callback
else
callback.call @, error, record if callback
update: ->
destroy: ->
concat: ->
_serializeAttributes: (attributes = {}) ->
target = Tower.constant(@relation.targetClassName)
for name, relation of target.relations()
if attributes.hasOwnProperty(name)
value = attributes[name]
delete attributes[name]
if relation instanceof Tower.Model.Relation.BelongsTo
attributes[relation.foreignKey] = value.id
attributes[relation.foreignType] = value.type if relation.polymorphic
attributes
toCriteria: ->
criteria = super
relation = @relation
if relation.cache
defaults = {}
defaults[relation.foreignKey + "s"] = $in: [@owner.get("id")]
criteria.where(defaults)
criteria
class Tower.Model.Relation.HasOne extends Tower.Model.Relation
Tower.Model.Scope.Finders =
ClassMethods:
finderMethods: [
"find",
"all",
"first",
"last",
"count",
"exists"
]
find: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
{conditions, options} = criteria.toQuery()
@_find conditions, options, callback
first: (callback) ->
{conditions, options} = @toQuery("asc")
@store.findOne conditions, options, callback
last: (callback) ->
{conditions, options} = @toQuery("desc")
@store.findOne conditions, options, callback
all: (callback) ->
{conditions, options} = @toQuery()
@store.find conditions, options, callback
count: (callback) ->
{conditions, options} = @toQuery()
@store.count conditions, options, callback
exists: (callback) ->
{conditions, options} = @toQuery()
@store.exists conditions, options, callback
batch: ->
fetch: ->
_find: (conditions, options, callback) ->
if conditions.id && conditions.id.hasOwnProperty("$in") && conditions.id.$in.length == 1
@store.findOne conditions, options, callback
else if conditions.id && !conditions.id.hasOwnProperty("$in")
conditions.id = {$in: Tower.Support.Object.toArray(conditions.id)}
@store.findOne conditions, options, callback
else
@store.find conditions, options, callback
# @todo
Tower.Model.Scope.Modifiers =
ClassMethods:
atomicModifiers:
"$set": "$set"
"$unset": "$unset"
"$push": "$push"
"$pushAll": "$pushAll"
"$pull": "$pull"
"$pullAll": "$pullAll"
"$inc": "$inc"
"$pop": "$pop"
# { $push : { field : value } }
push: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= []
# @todo check if valid type from schema!
if all && _.isArray(value)
attributes[key] = attributes[key].concat(value)
else
attributes[key].push(value)
@changeAttribute(changes, key, oldValue, attributes[key])
changes
changeAttribute: (changes, key, oldValue, newValue) ->
unless !!changes[key]
changes[key] = [oldValue, newValue]
else
changes[key][1] = newValue
delete changes[key] if changes[key][0] == changes[key][1]
changes
# { $pushAll : { field : array } }
pushAll: (record, updates) ->
@push record, updates, true
pull: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
attributeValue = attributes[key]
oldValue = undefined
if attributeValue && _.isArray(attributeValue)
oldValue = attributeValue.concat()
if all && _.isArray(value)
for item in value
attributeValue.splice _attributeValue.indexOf(item), 1
else
attributeValue.splice _attributeValue.indexOf(value), 1
@changeAttribute(changes, key, oldValue, attributeValue)
changes
pullAll: (record, updates) ->
@pull record, updates, true
inc: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= 0
attributes[key] += value
@changeAttribute changes, key, oldValue, attributes[key]
attributes
set: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
field = schema[key]
oldValue = attributes[key]
if field && field.type == "Array" && !Tower.Support.Object.isArray(value)
attributes[key] ||= []
attributes[key].push value
else
attributes[key] = value
@changeAttribute changes, key, oldValue, attributes[key]
changes
unset: (record, updates) ->
attributes = record.attributes
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] = undefined
@changeAttribute changes, key, oldValue, attributes[key]
changes
update: (record, updates) ->
set = null
for key, value of updates
if @isAtomicModifier(key)
@["#{key.replace("$", "")}"](record, value)
else
set ||= {}
set[key] = value
@set(record, set) if set
record
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
resetAttributes: (keys) ->
@resetAttributes(key) for key in keys
@
resetAttribute: (key) ->
array = @changes[key]
if array
delete @changes[key]
@attributes[key] = array[0]
@
toUpdates: (record) ->
result = {}
changes = record.changes
schema = record.constructor.schema()
for key, value of changes
field = field[key]
if field
if field.type == "Array"
pop = _.difference(value[0], value[1])
if pop.length > 0
result.$pop ||= {}
result.$pop[key] = pop
push = _.difference(value[1], value[0])
if push.length > 0
result.$push ||= {}
result.$push[key] = push
else if field.type == "Integer"
result.$inc ||= {}
result.$inc[key] = (value[1] || 0) - (value[0] || 0)
else
result[key]
result
Tower.Model.Scope.Persistence =
ClassMethods:
persistenceMethods: [
"create",
"update",
"destroy"
]
build: (attributes, options) ->
{conditions, options} = @toCreate()
@_build attributes, conditions, options
# User.create(firstName: "Lance")
# User.where(firstName: "Lance").create()
# User.where(firstName: "Lance").create([{lastName: "Pollard"}, {lastName: "Smith"}])
# User.where(firstName: "Lance").create(new User(lastName: "Pollard"))
# create(attributes)
# create([attributes, attributes])
# create(attributes, options)
create: ->
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
criteria.mergeOptions(options)
@_create criteria, data, options, callback
# User.where(firstName: "Lance").update(1, 2, 3)
# User.update(User.first(), User.last(), firstName: "Lance")
# User.update([User.first(), User.last()], firstName: "Lance")
# User.update([1, 2], firstName: "Lance")
update: ->
{criteria, data, options, callback} = @_extractArgs(arguments, ids: true, data: true)
criteria.mergeOptions(options)
@_update criteria, data, options, callback
destroy: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
criteria.mergeOptions(options)
@_destroy criteria, options, callback
sync: ->
transaction: ->
_build: (attributes, conditions, options) ->
if Tower.Support.Object.isArray(attributes)
result = []
for object in attributes
result.push @store.serializeModel(Tower.Support.Object.extend({}, conditions, object))
result
else
@store.serializeModel(Tower.Support.Object.extend({}, conditions, attributes))
_create: (criteria, data, opts, callback) ->
if opts.instantiate
isArray = Tower.Support.Object.isArray(data)
records = Tower.Support.Object.toArray(@build(data))
iterator = (record, next) ->
if record
record.save(next)
else
next()
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
return callback(error) if error
if isArray
callback(error, records)
else
callback(error, records[0])
else
@store.create data, opts, callback
_update: (criteria, data, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.updateAttributes(data, next)
@_each conditions, options, iterator, callback
else
@store.update data, conditions, options, callback
_destroy: (criteria, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.destroy(next)
@_each conditions, options, iterator, callback
else
@store.destroy conditions, options, callback
_each: (conditions, options, iterator, callback) ->
@store.find conditions, options, (error, records) =>
if error
callback.call @, error, records
else
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
callback.call @, error, records if callback
Tower.Model.Scope.Queries =
ClassMethods:
queryMethods: [
"where",
"order",
"asc",
"desc",
"limit",
"offset",
"select",
"joins",
"includes",
"excludes",
"paginate",
"within",
"allIn",
"allOf",
"alsoIn",
"anyIn",
"anyOf",
"near",
"notIn"
]
queryOperators:
">=": "$gte"
"$gte": "$gte"
">": "$gt"
"$gt": "$gt"
"<=": "$lte"
"$lte": "$lte"
"<": "$lt"
"$lt": "$lt"
"$in": "$in"
"$nin": "$nin"
"$any": "$any"
"$all": "$all"
"=~": "$regex"
"$m": "$regex"
"$regex": "$regex"
"$match": "$match"
"$notMatch": "$notMatch"
"!~": "$nm"
"$nm": "$nm"
"=": "$eq"
"$eq": "$eq"
"!=": "$neq"
"$neq": "$neq"
"$null": "$null"
"$notNull": "$notNull"
class Tower.Model.Validator.Format
constructor: (value, attributes) ->
super(value, attributes)
@value = if typeof(value) == 'string' then new RegExp(value) else value
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless !!@value.exec(value)
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.format", attribute: attribute, value: @value.toString())
callback
)
else
@success(callback)
class Tower.Model.Validator.Length extends Tower.Model.Validator
constructor: (name, value, attributes) ->
super
@validate = switch name
when "min" then @validateMinimum
when "max" then @validateMaximum
else
@validateLength
validateMinimum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value >= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.minimum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateMaximum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value <= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.maximum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateLength: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value == @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.length", attribute: attribute, value: @value)
callback
)
@success(callback)
class Tower.Model.Validator.Presence extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
unless Tower.Support.Object.isPresent(record.get(attribute))
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.presence", attribute: attribute),
callback
)
@success(callback)
class Tower.Model.Validator.Uniqueness extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
conditions = {}
conditions[attribute] = value
record.constructor.where(conditions).exists (error, result) =>
if result
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.uniqueness", attribute: attribute, value: value),
callback
)
else
@success(callback)
Tower.Controller.Caching =
freshWhen: ->
stale: ->
expiresIn: ->
Tower.Controller.Events =
ClassMethods:
addEventHandler: (name, handler, options) ->
@_addSocketEventHandler name, handler, options
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
unless @io
@_socketHandlers = {}
@io = Tower.Application.instance().socket.of(@socketNamespace()).on "connection", (socket) =>
for eventType, handler of @_socketHandlers
do (eventType, handler) ->
if eventType isnt 'connection' and eventType isnt 'disconnect'
socket.on eventType, (data) =>
@_dispatch undefined, handler, data
@_socketHandlers[name] = handler
_dispatch: (event, handler, locals = {}) ->
controller = new @
for key, value of locals
controller.params[key] = value
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.HTTP =
head: (status, options = {}) ->
if typeof status == "object"
options = status
status = null
status ||= options.status || "ok"
location = options.location
delete options.status
delete options.location
#for key, value of options
# @headers[key.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
@status = status
@location = Tower.urlFor(location) if location
@headers["Content-Type"] = Mime[formats.first] if formats
@body = " "
Tower.Controller.addRenderers
json: (json, options, callback) ->
json = JSON.stringify(json) unless typeof(json) == "string"
json = "#{options.callback}(#{json})" if options.callback
@headers["Content-Type"] ||= require("mime").lookup("json")
callback null, json if callback
json
# https://github.com/wdavidw/node-csv-parser
# csv: (csv, options, callback) ->
# https://github.com/devongovett/pdfkit
# pdf: (data, options, callback) ->
Tower.Controller.Sockets =
broadcast: ->
emit: ->
connect: ->
Tower.Mailer.Configuration =
ClassMethods:
lib: -> require('mailer')
Tower.Mailer.Rendering =
ClassMethods:
mail: (options = {}, callback) ->
@host = options.host
@port = options.port
@domain = options.domain
@to = options.to
@from = options.from
@subject = options.subject
@locals = options.locals || {}
@template = options.template
deliver: ->
email = @constructor.lib()
self = @
Shift.render path: @template, @locals, (error, body) ->
options =
host: self.host
port: self.port
domain: self.domain
to: self.to
from: self.from
subject: self.subject
body: body
authentication: self.login
username: self.username
password: self.password
email.send options, (error, result) ->
console.log error if error
console.log result
Tower.Support.I18n.load date:
formats:
# Use the strftime parameters for formats.
# When no format has been given", it uses default.
# You can provide other formats here if you like!
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
abbrDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
# Don't forget the nil at the beginning; there's no such thing as a 0th month
monthNames: [null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
abbrMonthNames: [null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Used in dateSelect and datetimeSelect.
order: ["year", "month", "day"]
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
# Used in array.toSentence.
support:
array:
wordsConnector: ", "
twoWordsConnector: " and "
lastWordConnector: ", and "
class Tower.View.Form.Builder extends Tower.View.Component
constructor: (args, options = {}) ->
@template = options.template
@model = options.model
@attribute = options.attribute
@parentIndex = options.parentIndex
@index = options.index
@tabindex = options.tabindex
@accessKeys = options.accessKeys
#@attributes = @cloneAttributes(options.except(:template, :model, :attribute, :accessKeys, :index, :tabindex))
defaultOptions: (options = {}) ->
options.model ||= @model
options.index ||= @index
options.attribute ||= @attribute
options.template ||= @template
options
fieldset: (args...) ->
block = args.pop()
options = @defaultOptions(Tower.Support.Array.extractOptions(args))
options.label ||= args.shift()
new Tower.View.Form.Fieldset([], options).render(block)
fields: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as = "fields"
options.label ||= false
attribute = args.shift() || @attribute
@field attribute, options, (_field) =>
@fieldset(block)
fieldsFor: ->
options = args.extractOptions
attribute = args.shift
macro = model.macroFor(attribute)
attrName = nil
if options.as == "object"
attrName = attribute.toS
else
attrName = if Tower.View.renameNestedAttributes then "#{attribute}_attributes" else attribute.toS
# -> something here for counts
subParent = model.object
subObject = args.shift
index = options.delete("index")
unless index.present? && typeof index == "string"
if subObject.blank? && index.present?
subObject = subParent.send(attribute)[index]
else if index.blank? && subObject.present? && macro == "hasMany"
index = subParent.send(attribute).index(subObject)
subObject ||= model.default(attribute) || model.toS.camelize.constantize.new
keys = [model.keys, attrName]
options.merge(
template: template
model: model
parentIndex: index
accessKeys: accessKeys
tabindex: tabindex
)
new Tower.View.Form.Builder(options).render(block)
field: ->
args = Tower.Support.Array.args(arguments)
last = args[args.length - 1]
args.pop() if last == null || last == undefined
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
attributeName = args.shift() || "attribute.name"
#attribute = Storefront:"Attribute".new(
# name: attributeName,
# model: @model,
# required: options.required == true,
# disabled: options.disabled == true,
# topLevel: options.attribute == false
#)
defaults =
template: @template
model: @model
attribute: attributeName,
parentIndex: @parentIndex
index: @index
fieldHTML: options.fieldHTML || {}
inputHTML: options.inputHTML || {}
labelHTML: options.labelHTML || {}
errorHTML: options.errorHTML || {}
hintHtml: options.hintHtml || {}
new Tower.View.Form.Field([], _.extend(defaults, options)).render(block)
button: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as ||= "submit"
options.value = args.shift() || "Submit"
options.class = Tower.View.submitFieldsetClass if options.as == "submit"
@field options.value, options, block
submit: @::button
partial: (path, options = {}) ->
@template.render partial: path, locals: options.merge(fields: self)
tag: (key, args...) ->
@template.tag key, args
render: (block) ->
block(@)
class Tower.View.Form.Field extends Tower.View.Component
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
toId: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "-#{options.parentIndex}" if options.parentIndex
result += "-#{Tower.Support.String.parameterize(@attribute)}"
result += "-#{options.type || "field"}"
result += "-#{@index}" if @index?
result
toParam: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "[#{options.parentIndex}]" if options.parentIndex
result += "[#{@attribute}]"
result += "[#{@index}]" if @index?
result
constructor: (args, options) ->
@labelValue = options.label
delete options.label
super(args, options)
@required ||= false
# input type
field = @model.constructor.fields()[@attribute]
options.as ||= if field then Tower.Support.String.camelize(field.type, true) else "string"
@inputType = inputType = options.as
@required = !!(field && field.required == true)
# class
classes = [Tower.View.fieldClass, inputType]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
if options.validate != false && field.validations
classes.push Tower.View.validateClass
@fieldHTML.class = @addClass @fieldHTML.class, classes
# id
if !@fieldHTML.id && Tower.View.idEnabledOn.indexOf("field") > -1
@fieldHTML.id = @toId(type: "field", index: @index, parentIndex: @parentIndex)
@inputHTML.id = @toId(type: "input", index: @index, parentIndex: @parentIndex)
unless ["hidden", "submit"].indexOf(inputType) > -1
@labelHTML.for ||= @inputHTML.id
@labelHTML.class = @addClass @labelHTML.class, [Tower.View.labelClass]
unless @labelValue == false
@labelValue ||= Tower.Support.String.camelize(@attribute.toString())
unless options.hint == false
@errorHTML.class = @addClass @errorHTML.class, [Tower.View.errorClass]
if Tower.View.includeAria && Tower.View.hintIsPopup
@errorHTML.role ||= "tooltip"
@attributes = @fieldHTML
@inputHTML.name ||= @toParam() unless inputType == "submit"
@value = options.value
@dynamic = options.dynamic == true
@richInput = if options.hasOwnProperty("rich_input") then !!options.rich_input else Tower.View.richInput
@validate = options.validate != false
classes = [inputType, Tower.Support.String.parameterize(@attribute), @inputHTML.class]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
classes.push "input"
if options.validate != false && field.validations
classes.push Tower.View.validateClass
# class
@inputHTML.class = @addClass @inputHTML.class, classes
@inputHTML.placeholder = options.placeholder if options.placeholder
# value
unless @inputHTML.value?
if options.hasOwnProperty("value")
@inputHTML.value = options.value
unless @inputHTML.value?
value = @model.get(@attribute)
@inputHTML.value = value if value
# @inputHTML[:tabindex] = @tabindex
@inputHTML.maxlength ||= options.max if options.hasOwnProperty("max")
# expressions
pattern = options.match
pattern = pattern.toString() if _.isRegExp(pattern)
@inputHTML["data-match"] = pattern if pattern?
@inputHTML["aria-required"] = @required.toString()
@inputHTML.required = "true" if @required == true
@inputHTML.disabled = "true" if @disabled
@inputHTML.autofocus = "true" if @autofocus == true
@inputHTML["data-dynamic"] = "true" if @dynamic
@inputHTML.title ||= @inputHTML.placeholder if @inputHTML.placeholder
@autocomplete = @inputHTML.autocomplete == true
if @autocomplete && Tower.View.includeAria
@inputHTML["aria-autocomplete"] = switch @autocomplete
when "inline", "list", "both"
@autocomplete
else
"both"
input: (args...) ->
options = _.extend @inputHTML, Tower.Support.Array.extractOptions(args)
key = args.shift() || @attribute
@["#{@inputType}Input"](key, options)
checkboxInput: (key, options) ->
@tag "input", _.extend(type: "checkbox", options)
stringInput: (key, options) ->
@tag "input", _.extend(type: "text", options)
submitInput: (key, options) ->
@tag "input", _.extend(type: "submit", options)
fileInput: (key, options) ->
@tag "input", _.extend(type: "file", options)
textInput: (key, options) ->
@tag "textarea", options
password_input: (key, options) ->
@tag "input", _.extend(type: "password", options)
emailInput: (key, options) ->
@tag "input", _.extend(type: "email", options)
urlInput: (key, options) ->
@tag "input", _.extend(type: "url", options)
numberInput: (key, options) ->
@tag "input", _.extend(type: "string", "data-type": "numeric", options)
searchInput: (key, options) ->
@tag "input", _.extend(type: "search", "data-type": "search", options)
phoneInput: (key, options) ->
@tag "input", _.extend(type: "tel", "data-type": "phone", options)
label: ->
return unless @labelValue
@tag "label", @labelHTML, =>
@tag "span", @labelValue
if @required
@tag "abbr", title: Tower.View.requiredTitle, class: Tower.View.requiredClass, -> Tower.View.requiredAbbr
else
@tag "abbr", title: Tower.View.optionalTitle, class: Tower.View.optionalClass, -> Tower.View.optionalAbbr
render: (block) ->
@tag Tower.View.fieldTag, @attributes, =>
if block
block.call @
else
@label()
@input()
#elements = extractElements!(attributes)
#
#result = elements.map do |element|
# Array(send(element)).map(&"render")
#template.hamlConcat result.flatten.join.gsub(/\n$/, "") if result.present?
#
#yield(self) if blockGiven? # template.captureHaml(self, block)
extractElements: (options = {}) ->
elements = []
if ["hidden", "submit"].include?(inputType)
elements.push "inputs"
else
if @label.present? && @label.value?
elements.push "label"
elements = elements.concat ["inputs", "hints", "errors"]
elements
class Tower.View.Form.Fieldset extends Tower.View.Component
constructor: (args, options) ->
super
#@label = @localize("titles", options[:label], nil, (attributes[:locale_options] || {}).merge(:allow_blank => true)) if options[:label].present?
#merge_class! attributes, *[
# config.fieldset_class
#]
@attributes = attributes = {}
#attributes.id ||= label.underscore.strip.gsub(/[_\s]+/, config.separator) if label.present?
delete attributes.index
delete attributes.parentIndex
delete attributes.label
@builder = new Tower.View.Form.Builder([],
template: @template
model: @model
attribute: @attribute
index: @index
parentIndex: @parentIndex
)
# form.inputs :basic_info, :locale_options => {:count => 1, :past => true}
render: (block) ->
@tag "fieldset", @attributes, =>
if @label
@tag "legend", class: Tower.View.legendClass, =>
@tag "span", @label
@tag Tower.View.fieldListTag, class: Tower.View.fieldListClass, =>
@builder.render(block)
Tower.View.ComponentHelper =
formFor: ->
Tower.View.Form.render(__ck, arguments...)
tableFor: ->
Tower.View.Table.render(__ck, arguments...)
widget: ->
linkTo: (title, path, options = {}) ->
a _.extend(options, href: path, title: title), title.toString()
Tower.View.ElementHelper =
title: (value) ->
document.title = value
addClass: (string, parts...) ->
classes = string.split(/\ +/)
for part in parts
classes.push(part) if classes.indexOf(part) > -1
classes.join(" ")
# @elementId @user, "form"
# #=> "#user-form"
#
# @elementId @user, "firstName", "field"
# #=> "#user-first-name-field"
elementId: ->
"##{@elementKey(arguments...)}"
elementClass: ->
".#{@elementKey(arguments...)}"
elementKey: ->
Tower.Support.String.parameterize(@elementNameComponents(arguments...).join("-"))
# @elementName @user, "firstName"
# #=> "user[firstName]"
#
# @elementName @user, "address", "city"
# #=> "user[address][city]"
elementName: ->
result = @elementNameComponents(arguments...)
i = 1
for item, i in result
result[i] = "[#{item}]"
Tower.Support.String.parameterize(result.join(""))
elementNameComponents: ->
args = Tower.Support.Array.args(arguments)
result = []
for item in args
switch typeof item
when "function"
result.push item.constructor.name
when "string"
result.push item
else
result.push item.toString()
result
for filter in ["stylus", "less", "markdown"]
@[filter] = (text) ->
Tower.View.render(text, filter: filter)
Tower.View.HeadHelper =
metaTag: (name, content) ->
meta name: name, content: content
snapshotLinkTag: (href) ->
linkTag rel: "imageSrc", href: href
html4ContentTypeTag: (charset = "UTF-8", type = "text/html") ->
httpMetaTag "Content-Type", "#{type}; charset=#{charset}"
chromeFrameTag: ->
html4ContentTypeTag()
meta "http-equiv": "X-UA-Compatible", content: "IE=Edge,chrome=1"
html5ContentTypeTag: (charset = "UTF-8") ->
meta charset: charset
contentTypeTag: (charset) ->
html5ContentTypeTag charset
csrfMetaTag: ->
metaTag "csrf-token", @request.session._csrf
searchLinkTag: (href, title) ->
linkTag rel: "search", type: "application/opensearchdescription+xml", href: href, title: title
faviconLinkTag: (favicon = "/favicon.ico") ->
linkTag rel: "shortcut icon", href: favicon, type: "image/x-icon"
linkTag: (options = {}) ->
link options
ieApplicationMetaTags: (title, options = {}) ->
result = []
result.push metaTag("application-name", title)
result.push metaTag("msapplication-tooltip", options.tooltip) if options.hasOwnProperty("tooltip")
result.push metaTag("msapplication-starturl", options.url) if options.hasOwnProperty("url")
if options.hasOwnProperty("width") && options.hasOwnProperty("height")
result.push metaTag("msapplication-window", "width=#{options.width};height=#{options.height}")
result.push metaTag("msapplication-navbutton-color", options.color) if options.hasOwnProperty("color")
result.join("\n")
ieTaskMetaTag: (name, path, icon = null) ->
content = []
content.push "name=#{name}"
content.push "uri=#{path}"
content.push "icon-uri=#{icon}" if icon
@metaTag "msapplication-task", content.join(";")
appleMetaTags: (options = {}) ->
result = []
result.push appleViewportMetaTag(options)
result.push appleFullScreenMetaTag(options.fullScreen) if options.hasOwnProperty("fullScreen")
result.push appleMobileCompatibleMetaTag(options.mobile) if options.hasOwnProperty("mobile")
result.join()
# http://www.html5rocks.com/en/mobile/mobifying.html
appleViewportMetaTag: (options = {}) ->
viewport = []
viewport.push "width=#{options.width}" if options.hasOwnProperty("width")
viewport.push "height=#{options.height}" if options.hasOwnProperty("height")
viewport.push "initial-scale=#{options.scale || 1.0}"
viewport.push "minimum-scale=#{options.min}" if options.hasOwnProperty("min")
viewport.push "maximum-scale=#{options.max}" if options.hasOwnProperty("max")
viewport.push "user-scalable=#{boolean(options.scalable)}" if options.hasOwnProperty("scalable")
metaTag "viewport", viewport.join(", ")
appleFullScreenMetaTag: (value) ->
metaTag "apple-touch-fullscreen", boolean(value)
appleMobileCompatibleMetaTag: (value) ->
metaTag "apple-mobile-web-app-capable", boolean(value)
appleTouchIconLinkTag: (path, options = {}) ->
rel = ["apple-touch-icon"]
rel.push "#{options.size}x#{options.size}" if options.hasOwnProperty("size")
rel.push "precomposed" if options.precomposed
linkTag rel: rel.join("-"), href: path
appleTouchIconLinkTags: (path, sizes...) ->
if typeof sizes[sizes.length - 1] == "object"
options = sizes.pop()
else
options = {}
result = []
for size in sizes
result.push appleTouchIconLinkTag(path, _.extend(size: size, options))
result.join()
openGraphMetaTags: (options = {}) ->
openGraphMetaTag("og:title", options.title) if options.title
openGraphMetaTag("og:type", options.type) if options.type
openGraphMetaTag("og:image", options.image) if options.image
openGraphMetaTag("og:siteName", options.site) if options.site
openGraphMetaTag("og:description", options.description) if options.description
openGraphMetaTag("og:email", options.email) if options.email
openGraphMetaTag("og:phoneNumber", options.phone) if options.phone
openGraphMetaTag("og:faxNumber", options.fax) if options.fax
openGraphMetaTag("og:latitude", options.lat) if options.lat
openGraphMetaTag("og:longitude", options.lng) if options.lng
openGraphMetaTag("og:street-address", options.street) if options.street
openGraphMetaTag("og:locality", options.city) if options.city
openGraphMetaTag("og:region", options.state) if options.state
openGraphMetaTag("og:postal-code", options.zip) if options.zip
openGraphMetaTag("og:country-name", options.country) if options.country
null
openGraphMetaTag: (property, content) ->
meta property: property, content: content
Tower.View.RenderingHelper =
partial: (path, options, callback) ->
try
if typeof options == "function"
callback = options
options = {}
options ||= {}
options.locals ||= {}
locals = options.locals
path = path.split("/")
path[path.length - 1] = "_#{path[path.length - 1]}"
path = path.join("/")
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
template = @renderWithEngine(String(template))
if options.collection
name = options.as || Tower.Support.String.camelize(options.collection[0].constructor.name, true)
tmpl = eval "(function(data) { with(data) { this.#{name} = #{name}; #{String(template)} } })"
for item in options.collection
locals[name] = item
tmpl.call(@, locals)
delete @[name]
else
tmpl = "(function(data) { with(data) { #{String(template)} } })"
eval(tmpl).call(@, locals)
catch error
console.log error.stack || error
null
page: ->
args = Tower.Support.Array.args(arguments)
options = Tower.Support.Array.extractOptions(args)
browserTitle = args.shift() || options.title
@contentFor "title", ->
title browserTitle
urlFor: ->
Tower.urlFor(arguments...)
yields: (key) ->
value = @[key]
if typeof value == "function"
eval("(#{String(value)})()")
else
#__ck.indent()
ending = if value.match(/\n$/) then "\n" else ""
text(value.replace(/\n$/, "").replace(/^(?!\s+$)/mg, __ck.repeat(' ', __ck.tabs)) + ending)
null
hasContentFor: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
has: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
contentFor: (key, block) ->
@[key] = block
null
Tower.View.StringHelper =
# Characters that need to be escaped to HTML entities from user input
HTML_ESCAPE:
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
preserve: (text) ->
text.replace(/\n/g, '
').replace(/\r/g, '')
htmlEscape: (text) ->
text.replace /[\"><&]/g, (_) => @HTML_ESCAPE[_]
t: (string) ->
Tower.Support.I18n.translate(string)
l: (object) ->
Tower.Support.I18n.localize(string)
boolean: (boolean) ->
if boolean then "yes" else "no"
| 42996 |
window.global ||= window
module = global.module || {}
global.Tower = Tower = {}
Tower.version = "0.3.0"
Tower.logger = console
require './support'
require './application'
require './client/application'
require './store'
require './client/store'
require './model'
require './view'
require './client/view'
require './controller'
require './client/controller'
require './http'
require './middleware'
class Tower.Controller extends Tower.Class
@include Tower.Support.Callbacks
@extend Tower.Support.EventEmitter
@include Tower.Support.EventEmitter
@instance: ->
@_instance ||= new @
@metadata: ->
@_metadata ||= {}
constructor: ->
@constructor._instance = @
@headers = {}
@status = 200
@request = null
@response = null
@params = {}
@query = {}
@resourceName = @constructor.resourceName()
@resourceType = @constructor.resourceType()
@collectionName = @constructor.collectionName()
@formats = _.keys(@constructor.mimes())
if @constructor._belongsTo
@hasParent = true
else
@hasParent = false
require './controller/callbacks'
require './controller/helpers'
require './controller/instrumentation'
require './controller/params'
require './controller/redirecting'
require './controller/rendering'
require './controller/resourceful'
require './controller/responder'
require './controller/responding'
Tower.Controller.include Tower.Controller.Callbacks
Tower.Controller.include Tower.Controller.Helpers
Tower.Controller.include Tower.Controller.Instrumentation
Tower.Controller.include Tower.Controller.Params
Tower.Controller.include Tower.Controller.Redirecting
Tower.Controller.include Tower.Controller.Rendering
Tower.Controller.include Tower.Controller.Resourceful
Tower.Controller.include Tower.Controller.Responding
Tower.HTTP = {}
require './http/agent'
require './http/cookies'
require './http/param'
require './http/route'
require './http/request'
require './http/response'
require './http/url'
class Tower.Model extends Tower.Class
# @example All configuration options
# class App.User extends Tower.Model
# @configure
#
# @example Configure using a function
# class App.User extends Tower.Model
# @configure ->
# defaultStore: Tower.Store.Memory
@configure: (object) ->
@config ||= {}
object = object.call @ if typeof object == "function"
_.extend @config, object
@
# @example All default options
# class App.User extends Tower.Model
# @defaults store: Tower.Store.Memory, scope: @desc("createdAt")
@defaults: (object) ->
@default(key, value) for key, value of object
@_defaults
# @example All default options
# class App.User extends Tower.Model
# @default "store", Tower.Store.Memory
# @default "scope", @desc("createdAt")
@default: (key, value) ->
@_defaults ||= {}
@_defaults[key] = value
constructor: (attrs, options) ->
@initialize attrs, options
initialize: (attrs = {}, options = {}) ->
definitions = @constructor.fields()
attributes = {}
for name, definition of definitions
attributes[name] = definition.defaultValue(@) unless attrs.hasOwnProperty(name)
@attributes = attributes
@changes = {}
@errors = {}
@readOnly = if options.hasOwnProperty("readOnly") then options.readOnly else false
@persistent = if options.hasOwnProperty("persistent") then options.persisted else false
@attributes[key] = value for key, value of attrs
require './model/scope'
require './model/criteria'
require './model/dirty'
require './model/conversion'
require './model/inheritance'
require './model/relation'
require './model/relations'
require './model/attribute'
require './model/attributes'
require './model/persistence'
require './model/scopes'
require './model/serialization'
require './model/validator'
require './model/validations'
require './model/timestamp'
require './model/locale/en'
Tower.Model.include Tower.Support.Callbacks
Tower.Model.include Tower.Model.Conversion
Tower.Model.include Tower.Model.Dirty
Tower.Model.include Tower.Model.Criteria
Tower.Model.include Tower.Model.Scopes
Tower.Model.include Tower.Model.Persistence
Tower.Model.include Tower.Model.Inheritance
Tower.Model.include Tower.Model.Serialization
Tower.Model.include Tower.Model.Relations
Tower.Model.include Tower.Model.Validations
Tower.Model.include Tower.Model.Attributes
Tower.Model.include Tower.Model.Timestamp
require 'underscore.logger'
global._ = require 'underscore'
_.mixin(require('underscore.string'))
Tower.version = JSON.parse(require("fs").readFileSync(require("path").normalize("#{__dirname}/../../package.json"))).version
Tower.logger = _console
require './support'
require './application'
require './server/application'
require './store'
require './server/store'
require './model'
require './view'
require './controller'
require './server/controller'
require './http'
require './middleware'
require './server/middleware'
require './server/command'
require './server/generator'
Tower.Model.defaultStore = Tower.Store.MongoDB
Tower.View.store(new Tower.Store.FileSystem(["app/views"]))
Tower.root = process.cwd()
Tower.publicPath = process.cwd() + "/public"
Tower.publicCacheDuration = 60 * 1000
Tower.sessionSecret = "tower-session-secret"
Tower.cookieSecret = "tower-cookie-secret"
Tower.render = (string, options = {}) ->
require("mint").render(options.type, string, options)
Tower.domain = "localhost"
Tower.date = ->
require('moment')(arguments...)._d
Tower.run = (argv) ->
(new Tower.Command.Server(argv)).run()
Tower.Support = {}
require './support/array'
require './support/callbacks'
require './support/class'
require './support/eventEmitter'
require './support/i18n'
require './support/number'
require './support/object'
require './support/regexp'
require './support/string'
require './support/url'
require './support/locale/en'
class Tower.View extends Tower.Class
@extend
cache: {}
engine: "coffee"
prettyPrint: false
loadPaths: ["app/views"]
componentSuffix: "widget"
hintClass: "hint"
hintTag: "figure"
labelClass: "label"
requiredClass: "required"
requiredAbbr: "*"
requiredTitle: "Required"
errorClass: "error"
errorTag: "output"
validClass: null
optionalClass: "optional"
optionalAbbr: ""
optionalTitle: "Optional"
labelMethod: "humanize"
labelAttribute: "toLabel"
validationMaxLimit: 255
defaultTextFieldSize: null
defaultTextAreaWidth: 300
allFieldsRequiredByDefault: true
fieldListTag: "ol"
fieldListClass: "fields"
fieldTag: "li"
separator: "-"
breadcrumb: " - "
includeBlankForSelectByDefault: true
collectionLabelMethods: ["toLabel", "displayName", "fullName", "name", "title", "toString"]
i18nLookupsByDefault: true
escapeHtmlEntitiesInHintsAndLabels: false
renameNestedAttributes: true
inlineValidations: true
autoIdForm: true
fieldsetClass: "fieldset"
fieldClass: "field"
validateClass: "validate"
legendClass: "legend"
formClass: "form"
idEnabledOn: ["input", "field"] # %w(field label error hint)
widgetsPath: "shared/widgets"
navClass: "list-item"
includeAria: true
activeClass: "active"
navTag: "li"
termsTag: "dl"
termClass: "term"
termKeyClass: "key"
termValueClass: "value"
hintIsPopup: false
listTag: "ul"
pageHeaderId: "header"
pageTitleId: "title"
autoIdNav: false
pageSubtitleId: "subtitle"
widgetClass: "widget"
headerClass: "header"
titleClass: "title"
subtitleClass: "subtitle"
contentClass: "content"
defaultHeaderLevel: 3
termSeparator: ":"
richInput: false
submitFieldsetClass: "submit-fieldset"
addLabel: "+"
removeLabel: "-"
cycleFields: false
alwaysIncludeHintTag: false
alwaysIncludeErrorTag: true
requireIfValidatesPresence: true
localizeWithNamespace: false
localizeWithNestedModel: false
localizeWithInheritance: true
defaultComponentHeaderLevel: 3
helpers: []
metaTags: [
"description",
"keywords",
"author",
"copyright",
"category",
"robots"
]
store: (store) ->
@_store = store if store
@_store ||= new Tower.Store.Memory(name: "view")
renderers: {}
constructor: (context = {}) ->
@_context = context
require './view/helpers'
require './view/rendering'
require './view/component'
require './view/table'
require './view/form'
require './view/helpers/assetHelper'
require './view/helpers/componentHelper'
require './view/helpers/elementHelper'
require './view/helpers/headHelper'
require './view/helpers/renderingHelper'
require './view/helpers/stringHelper'
Tower.View.include Tower.View.Rendering
Tower.View.include Tower.View.Helpers
Tower.View.include Tower.View.AssetHelper
Tower.View.include Tower.View.ComponentHelper
Tower.View.include Tower.View.HeadHelper
Tower.View.include Tower.View.RenderingHelper
Tower.View.include Tower.View.StringHelper
Tower.View.helpers.push Tower.View.AssetHelper
Tower.View.helpers.push Tower.View.ComponentHelper
Tower.View.helpers.push Tower.View.HeadHelper
Tower.View.helpers.push Tower.View.RenderingHelper
Tower.View.helpers.push Tower.View.StringHelper
require './controller/elements'
require './controller/events'
require './controller/handlers'
Tower.Controller.include Tower.Controller.Elements
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.Handlers
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
require './view/formHelper'
require './view/metaHelper'
require './view/validationHelper'
Tower.Controller.Callbacks =
ClassMethods:
beforeAction: ->
@before "action", arguments...
afterAction: ->
@after "action", arguments...
Tower.Controller.Helpers =
ClassMethods:
helper: (object) ->
@_helpers ||= []
@_helpers.push(object)
layout: (layout) ->
@_layout = layout
layout: ->
layout = @constructor._layout
if typeof(layout) == "function" then layout.call(@) else layout
Tower.Controller.Instrumentation =
call: (request, response, next) ->
@request = request
@response = response
@params = @request.params || {}
@cookies = @request.cookies || {}
@query = @request.query || {}
@session = @request.session || {}
@format = @params.format || "html"
@action = @params.action
@headers = {}
@callback = next
@process()
process: ->
@processQuery()
# hacking in logging for now
unless Tower.env.match(/(test|production)/)
console.log " Processing by #{@constructor.name}##{@action} as #{@format.toUpperCase()}"
console.log " Parameters:"
console.log @params
@runCallbacks "action", name: @action, (callback) =>
@[@action].call @, callback
processQuery: ->
clear: ->
@request = null
@response = null
@headers = null
Tower.Controller.Params =
ClassMethods:
params: (options, callback) ->
if typeof options == 'function'
callback = options
options = {}
if options
@_paramsOptions = Tower.Support.Object.extend(@_paramsOptions || {}, options)
callback.call(@)
@_params ||= {}
param: (key, options = {}) ->
@_params ||= {}
@_params[key] = Tower.HTTP.Param.create(key, Tower.Support.Object.extend({}, @_paramsOptions || {}, options))
criteria: ->
return @_criteria if @_criteria
@_criteria = criteria = new Tower.Model.Criteria
parsers = @constructor.params()
params = @params
for name, parser of parsers
if params.hasOwnProperty(name)
criteria.where(parser.toCriteria(params[name]))
criteria
Tower.Controller.Redirecting =
redirectTo: ->
@redirect arguments...
# @todo, better url extraction
redirect: ->
try
args = Tower.Support.Array.args(arguments)
console.log "redirect"
console.log @resourceType
console.log args
options = Tower.Support.Array.extractOptions(args)
console.log options
url = args.shift()
if !url && options.hasOwnProperty("action")
url = switch options.action
when "index", "new"
Tower.urlFor(@resourceType, action: options.action)
when "edit", "show"
Tower.urlFor(@resource, action: options.action)
url ||= "/"
console.log url
@response.redirect url
catch error
console.log error
@callback() if @callback
Tower.Controller.Rendering =
ClassMethods:
addRenderer: (key, block) ->
@renderers()[key] = block
addRenderers: (renderers = {}) ->
@addRenderer(key, block) for key, block of renderers
@
renderers: ->
@_renderers ||= {}
render: ->
@renderToBody @_normalizeRender(arguments...)
renderToBody: (options) ->
@_processRenderOptions(options)
@_renderTemplate(options)
renderToString: ->
@renderToBody @_normalizeRender(arguments...)
sendFile: (path, options = {}) ->
sendData: (data, options = {}) ->
_renderTemplate: (options) ->
_callback = options.callback
callback = (error, body) =>
if error
@status ||= 404
@body = error.stack
else
@status ||= 200
@body = body
_callback.apply @, arguments if _callback
@callback() if @callback
return if @_handleRenderers(options, callback)
@headers["Content-Type"] ||= "text/html"
view = new Tower.View(@)
try
view.render.call view, options, callback
catch error
callback error
_handleRenderers: (options, callback) ->
for name, renderer of Tower.Controller.renderers()
if options.hasOwnProperty(name)
renderer.call @, options[name], options, callback
return true
false
_processRenderOptions: (options = {}) ->
@status = options.status if options.status
@headers["Content-Type"] = options.contentType if options.contentType
@headers["Location"] = @urlFor(options.location) if options.location
@
_normalizeRender: ->
@_normalizeOptions @_normalizeArgs(arguments...)
_normalizeArgs: ->
args = Tower.Support.Array.args(arguments)
if typeof args[0] == "string"
action = args.shift()
if typeof args[0] == "object"
options = args.shift()
if typeof args[0] == "function"
callback = args.shift()
options ||= {}
if action
key = if !!action.match(/\//) then "file" else "action"
options[key] = action
options.callback = callback if callback
options
_normalizeOptions: (options = {}) ->
options.partial = @action if options.partial == true
options.prefixes ||= []
options.prefixes.push @collectionName
options.template ||= (options.file || (options.action || @action))
options
Tower.Controller.Resourceful =
ClassMethods:
resource: (options) ->
@_resourceName = options.name if options.hasOwnProperty("name")
@_resourceType = options.type if options.hasOwnProperty("type")
@_collectionName = options.collectionName if options.hasOwnProperty("collectionName")
@
resourceType: ->
@_resourceType ||= Tower.Support.String.singularize(@name.replace(/(Controller)$/, ""))
resourceName: ->
return @_resourceName if @_resourceName
parts = @resourceType().split(".")
@_resourceName = Tower.Support.String.camelize(parts[parts.length - 1], true)
collectionName: ->
@_collectionName ||= Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), true)
belongsTo: (key, options = {}) ->
options.key = key
options.type ||= Tower.Support.String.camelize(options.key)
@_belongsTo = options
actions: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
actions = ["index", "new", "create", "show", "edit", "update", "destroy"]
actionsToRemove = _.difference(actions, args, options.except || [])
for action in actionsToRemove
@[action] = null
delete @[action]
@
index: ->
#@_index arguments...
@_index (format) =>
format.html => @render "index"
format.json => @render json: @collection, status: 200
new: ->
@_new (format) =>
format.html => @render "new"
format.json => @render json: @resource, status: 200
create: (callback) ->
@_create (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
show: ->
@_show (format) =>
format.html => @render "show"
format.json => @render json: @resource, status: 200
edit: ->
@_edit (format) =>
format.html => @render "edit"
format.json => @render json: @resource, status: 200
update: ->
@_update (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
destroy: ->
@_destroy (format) =>
format.html => @redirectTo action: "index"
format.json => @render json: @resource, status: 200
_index: (callback) ->
@findCollection (error, collection) =>
@respondWith collection, callback
_new: (callback) ->
@buildResource (error, resource) =>
return @failure(error) unless resource
@respondWith(resource, callback)
_create: (callback) ->
@buildResource (error, resource) =>
return @failure(error, callback) unless resource
resource.save (error) =>
@respondWithStatus Tower.Support.Object.isBlank(resource.errors), callback
_show: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_edit: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_update: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.updateAttributes @params[@resourceName], (error) =>
@respondWithStatus !!!error && Tower.Support.Object.isBlank(resource.errors), callback
_destroy: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.destroy (error) =>
@respondWithStatus !!!error, callback
respondWithScoped: (callback) ->
@scoped (error, scope) =>
return @failure(error, callback) if error
@respondWith scope.build(), callback
respondWithStatus: (success, callback) ->
options = records: (@resource || @collection)
if callback && callback.length > 1
successResponder = new Tower.Controller.Responder(@, options)
failureResponder = new Tower.Controller.Responder(@, options)
callback.call @, successResponder, failureResponder
if success
successResponder[format].call @
else
failureResponder[format].call @, error
else
Tower.Controller.Responder.respond(@, options, callback)
buildResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
@[@resourceName] = @resource = resource = scope.build(@params[@resourceName])
callback.call @, null, resource if callback
resource
findResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.find @params.id, (error, resource) =>
@[@resourceName] = @resource = resource
callback.call @, error, resource
findCollection: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.all (error, collection) =>
@[@collectionName] = @collection = collection
callback.call @, error, collection if callback
findParent: (callback) ->
association = @constructor._belongsTo
if association
param = association.param || "#{association.key}Id"
parentClass = Tower.constant(association.type)
parentClass.find @params[param], (error, parent) =>
throw error if error && !callback
unless error
@parent = @[association.key] = parent
callback.call @, error, parent if callback
else
callback.call @, null, false if callback
false
scoped: (callback) ->
callbackWithScope = (error, scope) =>
callback.call @, error, scope.where(@criteria())
if @hasParent
@findParent (error, parent) =>
callbackWithScope(error, parent[@collectionName]())
else
callbackWithScope null, Tower.constant(@resourceType)
failure: (resource, callback) ->
callback()
class Tower.Controller.Responder
@respond: (controller, options, callback) ->
responder = new @(controller, options)
responder.respond callback
constructor: (controller, options = {}) ->
@controller = controller
@options = options
@accept(format) for format in @controller.formats
accept: (format) ->
@[format] = (callback) -> @["_#{format}"] = callback
respond: (callback) ->
callback.call @controller, @ if callback
method = @["_#{@controller.format}"]
if method then method.call(@) else @toFormat()
_html: ->
@controller.render action: @controller.action
_json: ->
@controller.render json: @options.records
toFormat: ->
try
if get? || !hasErrors?
@defaultRender()
else
@displayErrors()
catch error
@_apiBehavior(error)
_navigationBehavior: (error) ->
if get?
throw error
else if hasErrors? && defaultAction
@render action: @defaultAction
else
@redirectTo @navigationLocation
_apiBehavior: (error) ->
#throw error unless resourceful?
if get?
@display resource
else if post?
@display resource, status: "created", location: @apiLocation
else
@head "noContent"
isResourceful: ->
@resource.hasOwnProperty("to#{@format.toUpperCase()}")
resourceLocation: ->
@options.location || @resources
defaultRender: ->
@defaultResponse.call(options)
display: (resource, givenOptions = {}) ->
@controller.render _.extend givenOptions, @options, format: @resource
displayErrors: ->
@controller.render format: @resourceErrors, status: "unprocessableEntity"
hasErrors: ->
@resource.respondTo?("errors") && !@resource.errors.empty?
defaultAction: ->
@action ||= ACTIONS_FOR_VERBS[request.requestMethodSymbol]
resourceErrors: ->
if @hasOwnProperty("#{format}ResourceErrors") then @["#{format}RresourceErrors"] else @resource.errors
jsonResourceErrors: ->
errors: @resource.errors
Tower.Controller.Responding =
ClassMethods:
respondTo: ->
mimes = @mimes()
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
only = Tower.Support.Object.toArray(options.only) if options.only
except = Tower.Support.Object.toArray(options.except) if options.except
for name in args
mimes[name] = {}
mimes[name].only = only if only
mimes[name].except = except if except
@
mimes: ->
@_mimes ||= {json: {}, html: {}}
respondTo: (block) ->
Tower.Controller.Responder.respond(@, {}, block)
respondWith: ->
args = Tower.Support.Array.args(arguments)
callback = null
if typeof(args[args.length - 1]) == "function"
callback = args.pop()
if typeof(args[args.length - 1]) == "object" && !(args[args.length - 1] instanceof Tower.Model)
options = args.pop()
else
options = {}
options ||= {}
options.records = args[0]
Tower.Controller.Responder.respond(@, options, callback)
_mimesForAction: ->
action = @action
result = []
mimes = @constructor.mimes()
for mime, config of mimes
success = false
if config.except
success = !_.include(config.except, action)
else if config.only
success = _.include(config.only, action)
else
success = true
result.push mime if success
result
class Tower.HTTP.Agent
constructor: (attributes = {}) ->
_.extend @, attributes
toJSON: ->
family: @family
major: @major
minor: @minor
patch: @patch
version: @version
os: @os
name: @name
class Tower.HTTP.Cookies
@parse: (string = document.cookie) ->
result = {}
pairs = string.split(/[;,] */);
for pair in pairs
eqlIndex = pair.indexOf('=')
key = pair.substring(0, eqlIndex).trim().toLowerCase()
value = pair.substring(++eqlIndex, pair.length).trim()
# quoted values
value = value.slice(1, -1) if '"' == value[0]
# only assign once
if result[key] == undefined
value = value.replace(/\+/g, ' ')
try
result[key] = decodeURIComponent(value)
catch error
if error instanceof URIError
result[key] = value
else
throw err
new @(result)
constructor: (attributes = {}) ->
@[key] = value for key, value of attributes
class Tower.HTTP.Param
@perPage: 20
@sortDirection: "ASC"
@sortKey: "sort" # or "order", etc.
@limitKey: "limit" # or "perPage", etc.
@pageKey: "page"
@separator: "_" # or "-"
@create: (key, options) ->
options.type ||= "String"
new Tower.HTTP.Param[options.type](key, options)
constructor: (key, options = {}) ->
@controller = options.controller
@key = key
@attribute = options.as || @key
@modelName = options.modelName
@namespace = Tower.Support.String.pluralize(@modelName) if modelName?
@exact = options.exact || false
@default = options.default
parse: (value) -> value
render: (value) -> value
toCriteria: (value) ->
nodes = @parse(value)
criteria = new Tower.Model.Criteria
for set in nodes
for node in set
attribute = node.attribute
operator = node.operators[0]
conditions = {}
if operator == "$eq"
conditions[attribute] = node.value
else
conditions[attribute] = {}
conditions[attribute][operator] = node.value
criteria.where(conditions)
criteria
parseValue: (value, operators) ->
namespace: @namespace, key: @key, operators: operators, value: value, attribute: @attribute
_clean: (string) ->
string.replace(/^-/, "").replace(/^\+-/, "").replace(/^'|'$/, "").replace("+", " ").replace(/^\^/, "").replace(/\$$/, "").replace(/^\s+|\s+$/, "")
require './param/array'
require './param/date'
require './param/number'
require './param/string'
class Tower.HTTP.Request
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@method = data.method || "GET"
class Tower.HTTP.Response
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@headerSent = false
@statusCode = 200
@body = ""
writeHead: (statusCode, headers) ->
@statusCode = statusCode
@headers = headers
setHeader: (key, value) ->
throw new Error("Headers already sent") if @headerSent
@headers[key] = value
write: (body = '') ->
@body += body
end: (body = '') ->
@body += body
@sent = true
@headerSent = true
redirect: (path, options = {}) ->
global.History.push options, null, path if global.History
class Tower.HTTP.Route extends Tower.Class
@store: ->
@_store ||= []
@create: (route) ->
@store().push(route)
@all: ->
@store()
@clear: ->
@_store = []
@draw: (callback) ->
callback.apply(new Tower.HTTP.Route.DSL(@))
@findController: (request, response, callback) ->
routes = Tower.Route.all()
for route in routes
controller = route.toController request
break if controller
if controller
controller.call request, response, ->
callback(controller)
else
callback(null)
controller
toController: (request) ->
match = @match(request)
return null unless match
method = request.method.toLowerCase()
keys = @keys
params = Tower.Support.Object.extend({}, @defaults, request.query || {}, request.body || {})
match = match[1..-1]
for capture, i in match
params[keys[i].name] ||= if capture then decodeURIComponent(capture) else null
controller = @controller
params.action = controller.action if controller
request.params = params
controller = new (Tower.constant(Tower.namespaced(@controller.className))) if controller
controller
constructor: (options) ->
options ||= options
@path = options.path
@name = options.name
@method = (options.method || "GET").toUpperCase()
@ip = options.ip
@defaults = options.defaults || {}
@constraints = options.constraints
@options = options
@controller = options.controller
@keys = []
@pattern = @extractPattern(@path)
@id = @path
if @controller
@id += @controller.name + @controller.action
match: (requestOrPath) ->
if typeof requestOrPath == "string" then return @pattern.exec(requestOrPath)
path = requestOrPath.location.path
return null unless requestOrPath.method.toUpperCase() == @method
match = @pattern.exec(path)
return null unless match
return null unless @matchConstraints(requestOrPath)
match
matchConstraints: (request) ->
constraints = @constraints
switch typeof(constraints)
when "object"
for key, value of constraints
switch typeof(value)
when "string", "number"
return false unless request[key] == value
when "function", "object"
# regexp?
return false unless !!request.location[key].match(value)
when "function"
return constraints.call(request, request)
else
return false
return true
urlFor: (options = {}) ->
result = @path
result = result.replace(new RegExp(":#{key}\\??", "g"), value) for key, value of options
result = result.replace(new RegExp("\\.?:\\w+\\??", "g"), "")
result
extractPattern: (path, caseSensitive, strict) ->
return path if path instanceof RegExp
self = @
return new RegExp('^' + path + '$') if path == "/"
path = path.replace(/(\(?)(\/)?(\.)?([:\*])(\w+)(\))?(\?)?/g, (_, open, slash, format, symbol, key, close, optional) ->
optional = (!!optional) || (open + close == "()")
splat = symbol == "*"
self.keys.push
name: key
optional: !!optional
splat: splat
slash ||= ""
result = ""
result += slash if !optional || !splat
result += "(?:"
# result += slash if optional
if format?
result += if splat then "\\.([^.]+?)" else "\\.([^/.]+?)"
else
result += if splat then "/?(.+)" else "([^/\\.]+)"
result += ")"
result += "?" if optional
result
)
new RegExp('^' + path + '$', if !!caseSensitive then '' else 'i')
Tower.Route = Tower.HTTP.Route
require './route/dsl'
require './route/urls'
require './route/polymorphicUrls'
Tower.HTTP.Route.include Tower.HTTP.Route.Urls
Tower.HTTP.Route.include Tower.HTTP.Route.PolymorphicUrls
Tower.HTTP.Sync =
ajax: ->
webSockets: ->
class Tower.HTTP.Url
@key: ["source", "protocol", "host", "userInfo", "user", "password", "hostname", "port", "relative", "path", "directory", "file", "query", "fragment"]
@aliases:
anchor: "fragment"
@parser:
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
@querystringParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@fragmentParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@typeParser: /(youtube|vimeo|eventbrite)/
parse: (string) ->
key = @constructor.key
string = decodeURI(string)
parsed = @constructor.parser[(if @strictMode or false then "strict" else "loose")].exec(string)
attributes = {}
@params = params = {}
@fragment = fragment = params: {}
i = 14
while i--
attributes[key[i]] = parsed[i] || ""
attributes["query"].replace @constructor.querystringParser, ($0, $1, $2) ->
params[$1] = $2 if $1
attributes["fragment"].replace @constructor.fragmentParser, ($0, $1, $2) ->
fragment.params[$1] = $2 if $1
@segments = attributes.path.replace(/^\/+|\/+$/g, "").split("/")
fragment.segments = attributes.fragment.replace(/^\/+|\/+$/g, "").split("/")
@[key] ||= value for key, value of attributes
@root = (if attributes.host then attributes.protocol + "://" + attributes.hostname + (if attributes.port then ":" + attributes.port else "") else "")
domains = @hostname.split(".")
@domain = domains[(domains.length - 1 - @depth)..(domains.length - 1)].join(".")
@subdomains = domains[0..(domains.length - 2 - @depth)]
@subdomain = @subdomains.join(".")
@port = parseInt(@port) if @port?
constructor: (url, depth = 1, strictMode) ->
@strictMode = strictMode or false
@depth = depth || 1
@url = url ||= window.location.toString() if window?
@parse(url)
class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = name
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
Tower.Model.Attributes =
ClassMethods:
field: (name, options) ->
@fields()[name] = new Tower.Model.Attribute(@, name, options)
fields: ->
@_fields ||= {}
get: (name) ->
unless @has(name)
field = @constructor.fields()[name]
@attributes[name] = field.defaultValue(@) if field
@attributes[name]
# post.set $pushAll: tags: ["ruby"]
# post.set $pushAll: tags: ["javascript"]
# post.attributes["tags"] #=> ["ruby", "javascript"]
# post.changes["tags"] #=> [[], ["ruby", "javascript"]]
# post.set $pop: tags: "ruby"
# post.attributes["tags"] #=> ["javascript"]
# post.changes["tags"] #=> [[], ["javascript"]]
# if the changes looked like this:
# post.changes["tags"] #=> [["ruby", "javascript"], ["javascript", "node.js"]]
# then the updates would be
# post.toUpdates() #=> {$popAll: {tags: ["ruby"]}, $pushAll: {tags: ["node.js"]}}
# popAll = _.difference(post.changes["tags"][0], post.changes["tags"][1])
# pushAll = _.difference(post.changes["tags"][1], post.changes["tags"][0])
set: (key, value) ->
if typeof key == "object"
updates = key
else
updates = {}
updates[key] = value
@_set(key, value) for key, value of updates
_set: (key, value) ->
@_attributeChange(key, value)
@attributes[key] = value
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
has: (key) ->
@attributes.hasOwnProperty(key)
Tower.Model.Conversion =
ClassMethods:
baseClass: ->
if @__super__ && @__super__.constructor.baseClass && @__super__.constructor != Tower.Model
@__super__.constructor.baseClass()
else
@
toParam: ->
return undefined if @ == Tower.Model
@metadata().paramNamePlural
toKey: ->
@metadata().paramName
# @url "/posts/:postId/comment"
# @url parent: "post"
# @url (model) -> return "/something"
url: (options) ->
@_url = switch typeof options
when "object"
if options.parent
url = "/#{Tower.Support.String.parameterize(Tower.Support.String.pluralize(options.parent))}/:#{Tower.Support.String.camelize(options.parent, true)}/#{@toParam()}"
else
options
collectionName: ->
Tower.Support.String.camelize(Tower.Support.String.pluralize(@name), true)
resourceName: ->
Tower.Support.String.camelize(@name, true)
# inheritance_column
metadata: ->
className = @name
metadata = @metadata[className]
return metadata if metadata
namespace = Tower.namespace()
name = Tower.Support.String.camelize(className, true)
namePlural = Tower.Support.String.pluralize(name)
classNamePlural = Tower.Support.String.pluralize(className)
paramName = Tower.Support.String.parameterize(name)
paramNamePlural = Tower.Support.String.parameterize(namePlural)
modelName = "#{namespace}.#{className}"
controllerName = "#{namespace}.#{classNamePlural}Controller"
@metadata[className] =
name: name
namePlural: namePlural
className: className
classNamePlural: classNamePlural
paramName: paramName
paramNamePlural: paramNamePlural
modelName: modelName
controllerName: controllerName
toLabel: ->
@className()
toPath: ->
result = @constructor.toParam()
return "/" if result == undefined
param = @toParam()
result += "/#{param}" if param
result
toParam: ->
id = @get("id")
if id? then String(id) else null
toKey: ->
@constructor.tokey()
toCacheKey: ->
toModel: ->
@
metadata: ->
@constructor.metadata()
class Tower.Model.Criteria
constructor: (args = {}) ->
@[key] = value for key, value of args
@_where ||= []
@_order ||= []
where: (conditions) ->
if conditions instanceof Tower.Model.Criteria
@merge(conditions)
else
@_where.push(conditions)
order: (attribute, direction = "asc") ->
@_order ||= []
@_order.push [attribute, direction]
#@mergeOptions sort: [[attribute, direction]]
asc: (attributes...) ->
@order(attribute) for attribute in attributes
desc: (attributes...) ->
@order(attribute, "desc") for attribute in attributes
allIn: (attributes) ->
@_whereOperator "$all", attributes
anyIn: (attributes) ->
@_whereOperator "$any", attributes
notIn: (attributes) ->
@_whereOperator "$nin", attributes
offset: (number) ->
@_offset = number
#@mergeOptions offset: number
limit: (number) ->
@_limit = number
@mergeOptions limit: number
select: ->
@_fields = Tower.Support.Array.args(arguments)
includes: ->
@_includes = Tower.Support.Array.args(arguments)
page: (number) ->
@offset(number)
paginate: (options) ->
limit = options.perPage || options.limit
page = options.page || 1
@limit(limit)
@offset((page - 1) * limit)
clone: ->
new @constructor(@attributes())
merge: (criteria) ->
attributes = criteria.attributes()
@_where = @_where.concat attributes._where if attributes._where.length > 0
@_order = @_order.concat attributes._order if attributes._order.length > 0
@_offset = attributes._offset if attributes._offset?
@_limit = attributes._limit if attributes._limit?
@_fields = attributes._fields if attributes._fields
@_offset = attributes._offset if attributes._offset?
@
options: ->
options = {}
options.offset = @_offset if @_offset?
options.limit = @_limit if @_limit?
options.fields = @_fields if @_fields
options.sort = @_order if @_order.length > 0
options
conditions: ->
result = {}
for conditions in @_where
Tower.Support.Object.deepMergeWithArrays(result, conditions)
result
attributes: (to = {}) ->
to._where = @_where.concat()
to._order = @_order.concat()
to._offset = @_offset if @_offset?
to._limit = @_limit if @_limit?
to._fields = @_fields if @_fields
to._includes = @_includes if @_includes
to
toQuery: ->
conditions: @conditions(), options: @options()
toUpdate: ->
@toQuery()
toCreate: ->
attributes = {}
options = {}
for conditions in @_where
# tags: $in: ["a", "b"]
# $push: tags: ["c"]
for key, value of conditions
if Tower.Store.isKeyword(key)
for _key, _value of value
attributes[_key] = _value
else if Tower.Support.Object.isHash(value) && Tower.Store.hasKeyword(value)
for _key, _value of value
attributes[key] = _value
else
attributes[key] = value
for key, value of attributes
delete attributes[key] if value == undefined
attributes: attributes, options: options
mergeOptions: (options) ->
options
_whereOperator: (operator, attributes) ->
query = {}
for key, value of attributes
query[key] = {}
query[key][operator] = value
@where query
Tower.Model.Dirty =
isDirty: ->
Tower.Support.Object.isPresent(@changes)
attributeChanged: (name) ->
change = @changes[name]
return false unless change
change[0] != change[1]
attributeChange: (name) ->
change = @changes[name]
return undefined unless change
change[1]
attributeWas: (name) ->
change = @changes[name]
return undefined unless change
change[0]
resetAttribute: (name) ->
array = @changes[name]
@set(name, array[0]) if array
@
toUpdates: ->
result = {}
attributes = @attributes
for key, array of @changes
result[key] = attributes[key]
result.updatedAt ||= new Date
result
_attributeChange: (attribute, value) ->
array = @changes[attribute] ||= []
beforeValue = array[0] ||= @attributes[attribute]
array[1] = value
array = null if array[0] == array[1]
if array then @changes[attribute] = array else delete @changes[attribute]
beforeValue
# @todo
# copied this from acts_as_nested_set, haven't messed with it yet.
Tower.Model.Hierarchical =
ClassMethods:
hierarchical: ->
@field "lft", type: "Integer"
@field "rgt", type: "Integer"
@field "parentId", type: "Integer"
root: (callback) ->
@roots.first(callback)
roots: ->
@where(parentColumnName: null).order(@quotedLeftColumnName())
leaves: ->
@where("#{@quotedRightColumnName()} - #{@quotedLeftColumnName()} = 1").order(@quotedLeftColumnName())
isRoot: ->
!!!@get("parentId")
root: (callback) ->
@selfAndAncestors.where(parentColumnName: null).first(callback)
selfAndAncestors: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} <= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} >= ?", left, right
])
ancestors: ->
@withoutSelf @selfAndAncestors
selfAndSiblings: ->
@nestedSetScope().where(parentColumnName: parentId)
siblings: ->
@withoutSelf @selfAndSiblings()
leaves: ->
@descendants().where("#{self.class.quotedTableName}.#{quotedRightColumnName} - #{self.class.quotedTableName}.#{quotedLeftColumnName} = 1")
level: (callback) ->
if get('parentId') == null then 0 else ancestors().count(callback)
selfAndDescendants: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} >= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} <= ?", left, right
])
descendants: ->
@withoutSelf @selfAndDescendants()
isDescendantOf: (other) ->
other.left < self.left && self.left < other.right && sameScope?(other)
moveLeft: ->
@moveToLeftOf @leftSibling()
moveRight: ->
@moveToRightOf @rightSibling()
moveToLeftOf: (node) ->
@moveTo node, "left"
moveToRightOf: (node) ->
@moveTo node, "right"
moveToChildOf: (node) ->
@moveTo node, "child"
moveToRoot: ->
@moveTo null, "root"
moveTo: (target, position) ->
@runCallbacks "move", ->
isOrIsDescendantOf: (other) ->
other.left <= self.left && self.left < other.right && sameScope?(other)
isAncestorOf: (other) ->
self.left < other.left && other.left < self.right && sameScope?(other)
isOrIsAncestorOf: (other) ->
self.left <= other.left && other.left < self.right && sameScope?(other)
sameScope: (other) ->
Array(actsAsNestedSetOptions.scope).all (attr) ->
self.send(attr) == other.send(attr)
leftSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} < ?", left]).
order("#{self.class.quotedTableName}.#{quotedLeftColumnName} DESC").last
rightSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} > ?", left]).first
Tower.Model.Inheritance =
_computeType: ->
Tower.Model.Persistence =
ClassMethods:
defaultStore: if Tower.client then Tower.Store.Memory else Tower.Store.MongoDB
store: (value) ->
return @_store if !value && @_store
if typeof value == "function"
@_store = new value(name: @collectionName(), type: Tower.namespaced(@name))
else if typeof value == "object"
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
Tower.Support.Object.extend @_store, value
else if value
@_store = value
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
@_store
load: (records) ->
@store().load(records)
InstanceMethods:
# Create or update the record.
#
# @example Default save
# user.save -> console.log "saved"
#
# @example Save without validating
# user.save validate: false, -> console.log "saved"
save: (options, callback) ->
throw new Error("Record is read only") if @readOnly
if typeof options == "function"
callback = options
options = {}
options ||= {}
unless options.validate == false
@validate (error) =>
if error
callback.call @, null, false if callback
else
@_save callback
else
@_save callback
@
updateAttributes: (attributes, callback) ->
@set(attributes)
@_update(attributes, callback)
destroy: (callback) ->
if @isNew()
callback.call @, null if callback
else
@_destroy callback
@
delete: (callback) ->
@destroy(callback)
isPersisted: ->
!!(@persistent)# && @attributes.hasOwnProperty("id") && @attributes.id != null && @attributes.id != undefined)
isNew: ->
!!!@isPersisted()
reload: ->
store: ->
@constructor.store()
_save: (callback) ->
@runCallbacks "save", (block) =>
complete = @_callback(block, callback)
if @isNew()
@_create(complete)
else
@_update(@toUpdates(), complete)
_create: (callback) ->
@runCallbacks "create", (block) =>
complete = @_callback(block, callback)
@constructor.create @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_update: (updates, callback) ->
@runCallbacks "update", (block) =>
complete = @_callback(block, callback)
@constructor.update @get("id"), updates, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_destroy: (callback) ->
@runCallbacks "destroy", (block) =>
complete = @_callback(block, callback)
@constructor.destroy @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@persistent = false
@changes = {}
delete @attributes.id
complete.call(@, error)
@
# @todo
# https://github.com/technoweenie/coffee-resque
Tower.Model.Queue =
ClassMethods:
enqueue: ->
class Tower.Model.Relation extends Tower.Class
# hasMany "commenters", source: "person", sourceType: "User", foreignKey: "userId", type
constructor: (owner, name, options = {}, callback) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@cache = false unless @hasOwnProperty("cache")
@readOnly = false unless @hasOwnProperty("readOnly")
@validate = false unless @hasOwnProperty("validate")
@autoSave = false unless @hasOwnProperty("autoSave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", cacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @cache
if typeof @cache == "string"
@cacheKey = @cache
@cache = true
else
@cacheKey = @singularTargetName + "Ids"
@owner.field @cacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
scoped: (record) ->
new @constructor.Scope(model: @klass(), owner: record, relation: @)
targetKlass: ->
Tower.constant(@targetType)
klass: ->
Tower.constant(@type)
inverse: ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
return relation if relation.targetType == @ownerType
null
class @Scope extends Tower.Model.Scope
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
clone: ->
new @constructor(model: @model, criteria: @criteria.clone(), owner: @owner, relation: @relation)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasOne'
Tower.Model.Relations =
ClassMethods:
# One-to-one association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasOne "address"
#
# class App.Address extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# address = user.createAddress()
#
# @example Example using all the `hasOne` options
# class App.User extends Tower.Model
# @hasOne "location", type: "Address", embed: true, as: "addressable"
#
# class App.Address extends Tower.Model
# @belongsTo "addressable", polymorphic: true
hasOne: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasOne(@, name, options)
# One-to-many association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasMany "comments"
#
# class App.Comment extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# comment = user.comments().create()
#
# @example Example using all the `hasMany` options
# class App.User extends Tower.Model
# @hasMany "comments", as: "commentable", embed: true
#
# class App.Comment extends Tower.Model
# @belongsTo "commentable", polymorphic: true
#
# @param [String] name Name of the association
# @param [Object] options Association options
# @option options [String] as Polymorphic key, if the associated object's relationship is polymorphic
# @option options [Boolean] embed If true, the data store will try to embed the data in the record (MongoDB currently)
hasMany: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasMany(@, name, options)
belongsTo: (name, options) ->
@relations()[name] = new Tower.Model.Relation.BelongsTo(@, name, options)
relations: ->
@_relations ||= {}
relation: (name) ->
relation = @relations()[name]
throw new Error("Relation '#{name}' does not exist on '#{@name}'") unless relation
relation
relation: (name) ->
@constructor.relation(name).scoped(@)
buildRelation: (name, attributes, callback) ->
@relation(name).build(attributes, callback)
createRelation: (name, attributes, callback) ->
@relation(name).create(attributes, callback)
destroyRelations: ->
class Tower.Model.Scope extends Tower.Class
constructor: (options = {}) ->
@model = options.model
@criteria = options.criteria || new Tower.Model.Criteria
@store = @model.store()
toQuery: (sortDirection) ->
@toCriteria(sortDirection).toQuery()
toCriteria: (sortDirection) ->
criteria = @criteria.clone()
if sortDirection || !criteria._order.length > 0
sort = @model.defaultSort()
criteria[sortDirection || sort.direction](sort.name) if sort
criteria
toCreate: ->
@toQuery()
toUpdate: ->
@toQuery()
toDestroy: ->
merge: (scope) ->
@criteria.merge(scope.criteria)
clone: ->
new @constructor(model: @model, criteria: @criteria.clone())
_extractArgs: (args, opts = {}) ->
args = Tower.Support.Array.args(args)
callback = Tower.Support.Array.extractBlock(args)
last = args[args.length - 1]
if opts.data && (Tower.Support.Object.isHash(last) || Tower.Support.Object.isArray(last))
data = args.pop()
if Tower.Support.Object.isHash(args[args.length - 1])
if data
options = data
data = args.pop()
else
if Tower.Support.Object.isBaseObject(args[args.length - 1])
options = args.pop()
data = {} unless opts.data
data ||= {}
criteria = @criteria.clone()
options ||= {}
options.instantiate = true unless options.hasOwnProperty("instantiate")
ids = _.flatten(args) if opts.ids && args.length > 0
if ids && ids.length > 0
ids = _.map(ids, (idOrRecord) -> if idOrRecord instanceof Tower.Model then idOrRecord.get("id") else idOrRecord)
criteria.where id: $in: ids
criteria: criteria, data: data, callback: callback, options: options
require './scope/finders'
require './scope/persistence'
require './scope/queries'
Tower.Model.Scope.include Tower.Model.Scope.Finders
Tower.Model.Scope.include Tower.Model.Scope.Persistence
Tower.Model.Scope.include Tower.Model.Scope.Queries
for key in Tower.Model.Scope.queryMethods
do (key) =>
Tower.Model.Scope::[key] = ->
clone = @clone()
clone.criteria[key](arguments...)
clone
Tower.Model.Scopes =
ClassMethods:
scope: (name, scope) ->
@[name] = if scope instanceof Tower.Model.Scope then scope else @where(scope)
scoped: ->
scope = new Tower.Model.Scope(model: @)
scope.where(type: @name) if @baseClass().name != @name
scope
defaultSort: (object) ->
@_defaultSort = object if object
@_defaultSort ||= {name: "createdAt", direction: "desc"}
for key in Tower.Model.Scope.queryMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.finderMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.persistenceMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
Tower.Model.Serialization =
ClassMethods:
fromJSON: (data) ->
records = JSON.parse(data)
records = [records] unless records instanceof Array
for record, i in records
records[i] = new @(record)
records
toJSON: (records, options = {}) ->
result = []
result.push(record.toJSON()) for record in records
result
toJSON: (options) ->
@_serializableHash(options)
clone: ->
new @constructor(Tower.Support.Object.clone(@attributes))
_serializableHash: (options = {}) ->
result = {}
attributeNames = Tower.Support.Object.keys(@attributes)
if only = options.only
attributeNames = _.union(Tower.Support.Object.toArray(only), attributeNames)
else if except = options.except
attributeNames = _.difference(Tower.Support.Object.toArray(except), attributeNames)
for name in attributeNames
result[name] = @_readAttributeForSerialization(name)
if methods = options.methods
methodNames = Tower.Support.Object.toArray(methods)
for name in methods
result[name] = @[name]()
# TODO: async!
if includes = options.include
includes = Tower.Support.Object.toArray(includes)
for include in includes
unless Tower.Support.Object.isHash(include)
tmp = {}
tmp[include] = {}
include = tmp
tmp = undefined
for name, opts of include
records = @[name]().all()
for record, i in records
records[i] = record._serializableHash(opts)
result[name] = records
result
_readAttributeForSerialization: (name, type = "json") ->
@attributes[name]
Tower.Model.Sync =
sync: ->
syncAction = @syncAction
@runCallbacks "sync", =>
@runCallbacks "#{syncAction}Sync", =>
@store["#{syncAction}Sync"](@)
updateSyncAction: (action) ->
@syncAction = switch action # create, update, delete
# if it was create, and it's never been synced, then we can just remove it from memory and be all cool
when "delete" then "delete"
when "update"
switch @syncAction
when "create" then "create"
else
"update"
else
switch @syncAction
when "update" then "delete"
else
action
Tower.Model.Timestamp =
ClassMethods:
timestamps: ->
@include Tower.Model.Timestamp.CreatedAt
@include Tower.Model.Timestamp.UpdatedAt
@field "createdAt", type: "Date"
@field "updatedAt", type: "Date"
@before "create", "setCreatedAt"
@before "save", "setUpdatedAt"
CreatedAt:
ClassMethods: {}
setCreatedAt: ->
@set "createdAt", new Date
UpdatedAt:
ClassMethods: {}
setUpdatedAt: ->
@set "updatedAt", new Date
Tower.Model.Validations =
ClassMethods:
validates: ->
attributes = Tower.Support.Array.args(arguments)
options = attributes.pop()
validators = @validators()
for key, value of options
validators.push Tower.Model.Validator.create(key, value, attributes)
validators: ->
@_validators ||= []
validate: (callback) ->
success = false
@runCallbacks "validate", (block) =>
complete = @_callback(block, callback)
validators = @constructor.validators()
errors = @errors = {}
iterator = (validator, next) =>
validator.validateEach @, errors, next
Tower.async validators, iterator, (error) =>
success = true unless error || Tower.Support.Object.isPresent(errors)
complete.call(@, !success)
success
success
class Tower.Model.Validator
@create: (name, value, attributes) ->
switch name
when "presence"
new @Presence(name, value, attributes)
when "count", "length", "min", "max"
new @Length(name, value, attributes)
when "format"
new @Format(name, value, attributes)
constructor: (name, value, attributes) ->
@name = name
@value = value
@attributes = attributes
validateEach: (record, errors, callback) ->
iterator = (attribute, next) =>
@validate record, attribute, errors, (error) =>
next()
Tower.async @attributes, iterator, (error) =>
callback.call(@, error) if callback
success: (callback) ->
callback.call @ if callback
true
failure: (record, attribute, errors, message, callback) ->
errors[attribute] ||= []
errors[attribute].push message
callback.call @, message if callback
false
require './validator/format'
require './validator/length'
require './validator/presence'
require './validator/uniqueness'
require './controller/caching'
require './controller/events'
require './controller/http'
require './controller/sockets'
Tower.Controller.include Tower.Controller.Caching
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.HTTP
Tower.Controller.include Tower.Controller.Sockets
require './controller/renderers'
class Tower.Mailer extends Tower.Class
require './mailer/configuration'
require './mailer/rendering'
Tower.Mailer.include Tower.Mailer.Configuration
Tower.Mailer.include Tower.Mailer.Rendering
Tower.Support.Array =
extractOptions: (args) ->
if typeof args[args.length - 1] == "object" then args.pop() else {}
extractBlock: (args) ->
if typeof args[args.length - 1] == "function" then args.pop() else null
args: (args, index = 0, withCallback = false, withOptions = false) ->
args = Array.prototype.slice.call(args, index, args.length)
if withCallback && !(args.length >= 2 && typeof(args[args.length - 1]) == "function")
throw new Error("You must pass a callback to the render method")
args
# Sort objects by one or more attributes.
#
# cityPrimer = (string) ->
# string.toLowerCase()
# sortObjects deals, ["city", ["price", "desc"]], city: cityPrimer
#
sortBy: (objects) ->
sortings = @args(arguments, 1)
callbacks = if sortings[sortings.length - 1] instanceof Array then {} else sortings.pop()
valueComparator = (x, y) ->
if x > y then 1 else (if x < y then -1 else 0)
arrayComparator = (a, b) ->
x = []
y = []
sortings.forEach (sorting) ->
attribute = sorting[0]
direction = sorting[1]
aValue = a[attribute]
bValue = b[attribute]
unless typeof callbacks[attribute] is "undefined"
aValue = callbacks[attribute](aValue)
bValue = callbacks[attribute](bValue)
x.push(direction * valueComparator(aValue, bValue))
y.push(direction * valueComparator(bValue, aValue))
if x < y then -1 else 1
sortings = sortings.map (sorting) ->
sorting = [sorting, "asc"] unless sorting instanceof Array
if sorting[1] == "desc"
sorting[1] = -1
else
sorting[1] = 1
sorting
objects.sort (a, b) ->
arrayComparator a, b
Tower.Support.Callbacks =
ClassMethods:
before: ->
@appendCallback "before", arguments...
# @example
# class App.User extends Tower.Model
# @before "save", "beforeSave"
#
# beforeSave: (callback) ->
# # before
# callback.call @
# # after
after: ->
@appendCallback "after", arguments...
callback: ->
args = Tower.Support.Array.args(arguments)
args = ["after"].concat args unless args[0].match(/^(?:before|around|after)$/)
@appendCallback args...
removeCallback: (action, phase, run) ->
@
appendCallback: (phase) ->
args = Tower.Support.Array.args(arguments, 1)
if typeof args[args.length - 1] != "object"
method = args.pop()
if typeof args[args.length - 1] == "object"
options = args.pop()
method ||= args.pop()
options ||= {}
callbacks = @callbacks()
for filter in args
callback = callbacks[filter] ||= new Tower.Support.Callbacks.Chain
callback.push phase, method, options
@
prependCallback: (action, phase, run, options = {}) ->
@
callbacks: ->
@_callbacks ||= {}
runCallbacks: (kind, options, block, complete) ->
if typeof options == "function"
complete = block
block = options
options = {}
options ||= {}
chain = @constructor.callbacks()[kind]
if chain
chain.run(@, options, block, complete)
else
block.call @
complete.call @ if complete
_callback: (callbacks...) ->
(error) =>
for callback in callbacks
callback.call(@, error) if callback
class Tower.Support.Callbacks.Chain
constructor: (options = {}) ->
@[key] = value for key, value of options
@before ||= []
@after ||= []
run: (binding, options, block, complete) ->
runner = (callback, next) =>
callback.run(binding, options, next)
Tower.async @before, runner, (error) =>
unless error
if block
switch block.length
when 0
block.call(binding)
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
block.call binding, (error) =>
unless error
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
push: (phase, method, filters, options) ->
@[phase].push new Tower.Support.Callback(method, filters, options)
class Tower.Support.Callback
constructor: (method, conditions = {}) ->
@method = method
@conditions = conditions
conditions.only = Tower.Support.Object.toArray(conditions.only) if conditions.hasOwnProperty("only")
conditions.except = Tower.Support.Object.toArray(conditions.except) if conditions.hasOwnProperty("except")
run: (binding, options, next) ->
conditions = @conditions
if options && options.hasOwnProperty("name")
if conditions.hasOwnProperty("only")
return next() if _.indexOf(conditions.only, options.name) == -1
else if conditions.hasOwnProperty("except")
return next() if _.indexOf(conditions.except, options.name) != -1
method = @method
method = binding[method] if typeof method == "string"
switch method.length
when 0
result = method.call binding
next(if !result then new Error("Callback did not pass") else null)
else
method.call binding, next
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
class Tower.Class
@global: (value) ->
@_global = value unless value == undefined
@_global = true if @_global == undefined
if value == true
global[@name] = @
else if value == false
delete global[@name]
@_global
@alias: (to, from) ->
Tower.Support.Object.alias(@::, to, from)
@accessor: (key, callback) ->
Tower.Support.Object.accessor(@::, key, callback)
@
@getter: (key, callback) ->
Tower.Support.Object.getter(@::, key, callback)
@
@setter: (key) ->
Tower.Support.Object.setter(@::, key)
@
@classAlias: (to, from) ->
Tower.Support.Object.alias(@, to, from)
@
@classAccessor: (key, callback) ->
Tower.Support.Object.accessor(@, key, callback)
@
@classGetter: (key, callback) ->
Tower.Support.Object.getter(@, key, callback)
@
@classSetter: (key) ->
Tower.Support.Object.setter(@, key)
@
@classEval: (block) ->
block.call(@)
@delegate: (key, options = {}) ->
Tower.Support.Object.delegate(@::, key, options)
@
@mixin: (self, object) ->
for key, value of object when key not in specialProperties
self[key] = value
object
@extend: (object) ->
@mixin(@, object)
extended = object.extended
extended.apply(object) if extended
object
@self: (object) ->
@extend object
@include: (object) ->
@extend(object.ClassMethods) if object.hasOwnProperty("ClassMethods")
@include(object.InstanceMethods) if object.hasOwnProperty("InstanceMethods")
@mixin(@::, object)
included = object.included
included.apply(object) if included
object
@className: ->
Tower.Support.Object.functionName(@)
className: ->
@constructor.className()
constructor: ->
@initialize()
initialize: ->
Tower.Support.EventEmitter =
#included: ->
# @events = {}
isEventEmitter: true
events: ->
@_events ||= {}
hasEventListener: (key) ->
Tower.Support.Object.isPresent(@events(), key)
event: (key) ->
@events()[key] ||= new Tower.Event(@, key)
# Examples:
#
# @on "click .item a", "clickItem"
# @on "click", "clickItem", target: ".item a"
#
# Use jQuery to set relavant parent/child elements using jQuery `find`, `parents`, `closest`, etc.
#
# @on "click", "clickItem", selector: ".item a", find: {meta: "span small"}, closest: {title: ".item h1"}
# #=> @titleElement = @targetElement.closest(".item h1")
on: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
if args.length == 0
eventMap = options
options = {}
else
options = {}
if typeof args[args.length - 1] == "object"
eventMap = args.pop()
else
eventMap = {}
eventMap[args.shift()] = args.shift()
# this is essentially what I'm doing above
#switch args.length
# # @on click: "clickHandler", keypress: "keypressHandler"
# when 1
# # @on "click", "clickHandler"
# # @on "click", -> alert '!'
# # @on {click: "clickHandler", keypress: "keypressHandler"}, {type: "socket"}
# when 2
# # @on "click", "clickHandler", type: "socket"
# when 3
for eventType, handler of eventMap
@addEventHandler(eventType, handler, options)
addEventHandler: (type, handler, options) ->
@event(type).addHandler(handler)
mutation: (wrappedFunction) ->
->
result = wrappedFunction.apply(this, arguments)
@event('change').fire(this, this)
result
prevent: (key) ->
@event(key).prevent()
@
allow: (key) ->
@event(key).allow()
@
isPrevented: (key) ->
@event(key).isPrevented()
fire: (key) ->
event = @event(key)
event.fire.call event, Tower.Support.Array.args(arguments, 1)
allowAndFire: (key) ->
@event(key).allowAndFire(Tower.Support.Array.args(arguments, 1))
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
Tower.Support.Object.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".<KEY>options.tense}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
Tower.Support.Number =
isInt: (n) ->
n == +n && n == (n|0)
isFloat: (n) ->
n == +n && n != (n|0)
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
Tower.Support.Object =
extend: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
object[key] = value
object
cloneHash: (options) ->
result = {}
for key, value of options
if @isArray(value)
result[key] = @cloneArray(value)
else if @isHash(value)
result[key] = @cloneHash(value)
else
result[key] = value
result
cloneArray: (value) ->
result = value.concat()
for item, i in result
if @isArray(item)
result[i] = @cloneArray(item)
else if @isHash(item)
result[i] = @cloneHash(item)
result
deepMerge: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
if object[key] && typeof value == 'object'
object[key] = Tower.Support.Object.deepMerge(object[key], value)
else
object[key] = value
object
deepMergeWithArrays: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
oldValue = object[key]
if oldValue
if @isArray(oldValue)
object[key] = oldValue.concat value
else if typeof oldValue == "object" && typeof value == "object"
object[key] = Tower.Support.Object.deepMergeWithArrays(object[key], value)
else
object[key] = value
else
object[key] = value
object
defineProperty: (object, key, options = {}) ->
Object.defineProperty object, key, options
functionName: (fn) ->
return fn.__name__ if fn.__name__
return fn.name if fn.name
fn.toString().match(/\W*function\s+([\w\$]+)\(/)?[1]
alias: (object, to, from) ->
object[to] = object[from]
accessor: (object, key, callback) ->
object._accessors ||= []
object._accessors.push(key)
@getter(key, object, callback)
@setter(key, object)
@
setter: (object, key) ->
unless object.hasOwnProperty("_setAttribute")
@defineProperty object, "_setAttribute",
enumerable: false,
configurable: true,
value: (key, value) ->
@["_#{key}"] = value
object._setters ||= []
object._setters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
set: (value) ->
@["_setAttribute"](key, value)
@
getter: (object, key, callback) ->
unless object.hasOwnProperty("_getAttribute")
@defineProperty object, "_getAttribute",
enumerable: false,
configurable: true,
value: (key) ->
@["_#{key}"]
object._getters ||= []
object._getters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
get: ->
@["_getAttribute"](key) || (@["_#{key}"] = callback.apply(@) if callback)
@
variables: (object) ->
accessors: (object) ->
methods: (object) ->
result = []
for key, value of object
result.push(key) if @isFunction(value)
result
delegate: (object, keys..., options = {}) ->
to = options.to
isFunction = @isFunction(object)
for key in keys
if isFunction
object[key] = ->
@[to]()[key](arguments...)
else
@defineProperty object, key,
enumerable: true,
configurable: true,
get: -> @[to]()[key]
object
isFunction: (object) ->
!!(object && object.constructor && object.call && object.apply)
toArray: (object) ->
if @isArray(object) then object else [object]
keys: (object) ->
Object.keys(object)
isA: (object, isa) ->
isRegExp: (object) ->
!!(object && object.test && object.exec && (object.ignoreCase || object.ignoreCase == false))
isHash: (object) ->
@isObject(object) && !(@isFunction(object) || @isArray(object) || _.isDate(object) || _.isRegExp(object))
isBaseObject: (object) ->
object && object.constructor && object.constructor.name == "Object"
isArray: Array.isArray || (object) ->
toString.call(object) == '[object Array]'
kind: (object) ->
type = typeof(object)
switch type
when "object"
return "array" if _.isArray(object)
return "arguments" if _.isArguments(object)
return "boolean" if _.isBoolean(object)
return "date" if _.isDate(object)
return "regex" if _.isRegExp(object)
return "NaN" if _.isNaN(object)
return "null" if _.isNull(object)
return "undefined" if _.isUndefined(object)
return "object"
when "number"
return "integer" if object == +object && object == (object|0)
return "float" if object == +object && object != (object|0)
return "number"
when "function"
return "regex" if _.isRegExp(object)
return "function"
else
return type
isObject: (object) ->
return object == Object(object)
isPresent: (object) ->
!@isBlank(object)
isBlank: (object) ->
return (object == "") if typeof object == "string"
return false for key, value of object
return true
has: (object, key) ->
object.hasOwnProperty(key)
Tower.Support.RegExp =
regexpEscape: (string) ->
string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
Tower.Support.String =
camelize_rx: /(?:^|_|\-)(.)/g
capitalize_rx: /(^|\s)([a-z])/g
underscore_rx1: /([A-Z]+)([A-Z][a-z])/g
underscore_rx2: /([a-z\d])([A-Z])/g
parameterize: (string) ->
Tower.Support.String.underscore(string).replace("_", "-")
constantize: (string, scope = global) ->
scope[@camelize(string)]
camelize: (string, firstLetterLower) ->
string = string.replace @camelize_rx, (str, p1) -> p1.toUpperCase()
if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string
underscore: (string) ->
string.replace(@underscore_rx1, '$1_$2')
.replace(@underscore_rx2, '$1_$2')
.replace('-', '_').toLowerCase()
singularize: (string) ->
len = string.length
if string.substr(len - 3) is 'ies'
string.substr(0, len - 3) + 'y'
else if string.substr(len - 1) is 's'
string.substr(0, len - 1)
else
string
pluralize: (count, string) ->
if string
return string if count is 1
else
string = count
len = string.length
lastLetter = string.substr(len - 1)
if lastLetter is 'y'
"#{string.substr(0, len - 1)}ies"
else if lastLetter is 's'
string
else
"#{string}s"
capitalize: (string) -> string.replace @capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase()
trim: (string) -> if string then string.trim() else ""
interpolate: (stringOrObject, keys) ->
if typeof stringOrObject is 'object'
string = stringOrObject[keys.count]
unless string
string = stringOrObject['other']
else
string = stringOrObject
for key, value of keys
string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value)
string
# use single quotes, otherwise they're escaped
Tower.Support.String.toQueryValue = (value, negate = "") ->
if Tower.Support.Object.isArray(value)
items = []
for item in value
result = negate
result += item
items.push result
result = items.join(",")
else
result = negate
result += value.toString()
result = result.replace(" ", "+").replace /[#%\"\|<>]/g, (_) -> encodeURIComponent(_)
result
# toQuery likes: 10
# toQuery likes: ">=": 10
# toQuery likes: ">=": 10, "<=": 20
# toQuery tags: ["ruby", "javascript"]
# toQuery tags: "!=": ["java", ".net"]
# #=> tags=-java,-ruby
# toQuery tags: "!=": ["java", ".net"], "==": ["ruby", "javascript"]
# #=> tags=ruby,javascript,-java,-ruby
Tower.Support.String.toQuery = (object, schema = {}) ->
result = []
for key, value of object
param = "#{key}="
type = schema[key] || "string"
negate = if type == "string" then "-" else "^"
if Tower.Support.Object.isHash(value)
data = {}
data.min = value[">="] if value.hasOwnProperty(">=")
data.min = value[">"] if value.hasOwnProperty(">")
data.max = value["<="] if value.hasOwnProperty("<=")
data.max = value["<"] if value.hasOwnProperty("<")
data.match = value["=~"] if value.hasOwnProperty("=~")
data.notMatch = value["!~"] if value.hasOwnProperty("!~")
data.eq = value["=="] if value.hasOwnProperty("==")
data.neq = value["!="] if value.hasOwnProperty("!=")
data.range = data.hasOwnProperty("min") || data.hasOwnProperty("max")
set = []
if data.range && !(data.hasOwnProperty("eq") || data.hasOwnProperty("match"))
range = ""
if data.hasOwnProperty("min")
range += Tower.Support.String.toQueryValue(data.min)
else
range += "n"
range += ".."
if data.hasOwnProperty("max")
range += Tower.Support.String.toQueryValue(data.max)
else
range += "n"
set.push range
if data.hasOwnProperty("eq")
set.push Tower.Support.String.toQueryValue(data.eq)
if data.hasOwnProperty("match")
set.push Tower.Support.String.toQueryValue(data.match)
if data.hasOwnProperty("neq")
set.push Tower.Support.String.toQueryValue(data.neq, negate)
if data.hasOwnProperty("notMatch")
set.push Tower.Support.String.toQueryValue(data.notMatch, negate)
param += set.join(",")
else
param += Tower.Support.String.toQueryValue(value)
result.push param
result.sort().join("&")
Tower.Support.String.extractDomain = (host, tldLength = 1) ->
return null unless @namedHost(host)
parts = host.split('.')
parts[0..parts.length - 1 - 1 + tldLength].join(".")
Tower.Support.String.extractSubdomains = (host, tldLength = 1) ->
return [] unless @namedHost(host)
parts = host.split('.')
parts[0..-(tldLength+2)]
Tower.Support.String.extractSubdomain = (host, tldLength = 1) ->
@extractSubdomains(host, tldLength).join('.')
Tower.Support.String.namedHost = (host) ->
!!!(host == null || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.exec(host))
Tower.Support.String.rewriteAuthentication = (options) ->
if options.user && options.password
"#{encodeURI(options.user)}:#{encodeURI(options.password)}@"
else
""
Tower.Support.String.hostOrSubdomainAndDomain = (options) ->
return options.host if options.subdomain == null && options.domain == null
tldLength = options.tldLength || 1
host = ""
unless options.subdomain == false
subdomain = options.subdomain || @extractSubdomain(options.host, tldLength)
host += "#{subdomain}." if subdomain
host += (options.domain || @extractDomain(options.host, tldLength))
host
# urlFor controller: "posts", action: "index"
# urlFor @user
# urlFor User
# urlFor "admin", @user
# Tower._urlFor({onlyPath: true, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript /i], "!=": ["java"]}}, trailingSlash: false}, {likes: "integer"})
# "?likes=-10..20,^13,^15&tags=ruby,/javascript+/i,-java"
Tower.Support.String.urlFor = (options) ->
unless options.host || options.onlyPath
throw new Error('Missing host to link to! Please provide the :host parameter, set defaultUrlOptions[:host], or set :onlyPath to true')
result = ""
params = options.params || {}
path = (options.path || "").replace(/\/+/, "/")
schema = options.schema || {}
delete options.path
delete options.schema
unless options.onlyPath
port = options.port
delete options.port
unless options.protocol == false
result += options.protocol || "http"
result += ":" unless result.match(Tower.Support.RegExp.regexpEscape(":|//"))
result += "//" unless result.match("//")
result += @rewriteAuthentication(options)
result += @hostOrSubdomainAndDomain(options)
result += ":#{port}" if port
# params.reject! {|k,v| v.toParam.nil? }
if options.trailingSlash
result += path.replace /\/$/, "/"
else
result += path
result += "?#{Tower.Support.String.toQuery(params, schema)}" unless Tower.Support.Object.isBlank(params)
result += "##{Tower.Support.String.toQuery(options.anchor)}" if options.anchor
result
# Tower.urlFor(RW.MongoUser.first(), {onlyPath: false, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript#/i], "!=": ["java"]}}, trailingSlash: true, host: "rituwall.com", user: "lance", password: "<PASSWORD>", anchor: {likes: 10}})
# "http://lance:pollard@rituwall.com/mongo-users/1?likes=-10..20,-13,-15&tags=ruby,/javascript%23/i,-java#likes=10"
Tower.urlFor = ->
args = Tower.Support.Array.args(arguments)
return null unless args[0]
if args[0] instanceof Tower.Model || (typeof(args[0])).match(/(string|function)/)
last = args[args.length - 1]
if last instanceof Tower.Model || (typeof(last)).match(/(string|function)/)
options = {}
else
options = args.pop()
options ||= args.pop()
result = ""
if options.controller && options.action
route = Tower.Route.find(name: Tower.Support.String.camelize(options.controller).replace(/(Controller)?$/, "Controller"), action: options.action)
if route
result = "/" + Tower.Support.String.parameterize(options.controller)
else
for item in args
result += "/"
if typeof(item) == "string"
result += item
else if item instanceof Tower.Model
result += item.toPath()
else if typeof(item) == "function" # need better, b/c i'm meaning constructor here
result += item.toParam()
result += switch options.action
when "new" then "/new"
when "edit" then "/edit"
else
""
options.onlyPath = true unless options.hasOwnProperty("onlyPath")
options.path = result
Tower.Support.String.urlFor(options)
Tower.Support.String.parameterize = (string) ->
Tower.Support.String.underscore(string).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '')
Tower.Support.Url = {}
class Tower.View.Component
@render: ->
args = Tower.Support.Array.args(arguments)
template = args.shift()
block = Tower.Support.Array.extractBlock(args)
unless args[args.length - 1] instanceof Tower.Model || typeof(args[args.length - 1]) != "object"
options = args.pop()
options ||= {}
options.template = template
(new @(args, options)).render(block)
constructor: (args, options) ->
@[key] = value for key, value of options
tag: (key, args...) ->
@template.tag key, args
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
class Tower.View.Form extends Tower.View.Component
constructor: (args, options) ->
super
@model = args.shift() || new Tower.Model
if typeof @model == "string"
klass = Tower.constant(Tower.Support.String.camelize(@model))
@model = if klass then new klass else null
@attributes = @_extractAttributes(options)
render: (callback) ->
@tag "form", @attributes, =>
@tag "input", type: "hidden", name: "_method", value: @attributes["data-method"]
if callback
builder = new Tower.View.Form.Builder([],
template: @template
tabindex: 1
accessKeys: {}
model: @model
)
builder.render(callback)
_extractAttributes: (options = {}) ->
attributes = options.html || {}
attributes.action = options.url || Tower.urlFor(@model)
attributes.class = options["class"] if options.hasOwnProperty("class")
#@mergeClass attributes, config.formClass
attributes.id = options.id if options.hasOwnProperty("id")
attributes.id ||= Tower.Support.String.parameterize("#{@model.constructor.name}-form")
attributes.enctype = "multipart/form-data" if (options.multipart || attributes.multipart == true)
attributes.role = "form"
attributes.novalidate = "true" # needs to be true b/c the error popups are horribly ugly!# if options.validate == false
attributes["data-validate"] = options.validate.toString() if options.hasOwnProperty("validate")
method = attributes.method || options.method
if !method || method == ""
if @model && @model.get("id")
method = "put"
else
method = "post"
attributes["data-method"] = method
attributes.method = if method == "get" then "get" else "post"
attributes
require './form/builder'
require './form/field'
require './form/fieldset'
Tower.View.Helpers =
titleTag: (title) ->
"<title>#{title}</title>"
metaTag: (name, content) ->
"""<meta name="#{name}" content="#{content}"/>"""
tag: (name, options) ->
linkTag: (title, path, options) ->
imageTag: (path, options) ->
csrfMetaTag: ->
@metaTag("csrf-token", @request.session._csrf)
contentTypeTag: (type = "UTF-8") ->
"<meta charset=\"#{type}\" />"
javascriptTag: (path) ->
"<script type=\"text/javascript\" src=\"#{path}\" ></script>"
stylesheetTag: (path) ->
"<link href=\"#{path}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\"/>"
mobileTags: ->
"""
<meta content='yes' name='apple-mobile-web-app-capable'>
<meta content='yes' name='apple-touch-fullscreen'>
<meta content='initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width' name='viewport'>
"""
Tower.View.Rendering =
render: (options, callback) ->
options.type ||= @constructor.engine
options.layout = @_context.layout() if !options.hasOwnProperty("layout") && @_context.layout
options.locals = @_renderingContext(options)
@_renderBody options, (error, body) =>
return callback(error, body) if error
@_renderLayout(body, options, callback)
partial: (path, options, callback) ->
if typeof options == "function"
callback = options
options = {}
options ||= {}
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
@_renderString(template, options, callback)
_renderBody: (options, callback) ->
if options.text
callback(null, options.text)
else if options.json
callback(null, if typeof(options.json) == "string" then options.json else JSON.stringify(options.json))
else
unless options.inline
options.template = @_readTemplate(options.template, options.prefixes, options.type)
@_renderString(options.template, options, callback)
_renderLayout: (body, options, callback) ->
if options.layout
layout = @_readTemplate("layouts/#{options.layout}", [], options.type)
options.locals.body = body
@_renderString(layout, options, callback)
else
callback(null, body)
_renderString: (string, options = {}, callback) ->
if !!options.type.match(/coffee/)
e = null
result = null
# tmp hack
coffeekup = if Tower.client then global.CoffeeKup else require("coffeekup")
try
locals = options.locals
locals.renderWithEngine = @renderWithEngine
locals._readTemplate = @_readTemplate
locals.cache = Tower.env != "development"
locals.format = true
hardcode = {}
for helper in Tower.View.helpers
hardcode = _.extend(hardcode, helper)
hardcode = _.extend(hardcode, tags: coffeekup.tags)
locals.hardcode = hardcode
locals._ = _
result = coffeekup.render string, locals
catch error
e = error
callback e, result
else if options.type
mint = require "mint"
engine = require("mint").engine(options.type)
mint[engine](string, options.locals, callback)
else
mint = require "mint"
engine = require("mint")
options.locals.string = string
engine.render(options.locals, callback)
_renderingContext: (options) ->
locals = this
_ref = @_context
for key of _ref
value = _ref[key]
locals[key] = value unless key.match(/^(constructor|head)/)
#newlocals = {}
#newlocals.locals = locals
#locals = newlocals
locals = Tower.Support.Object.extend(locals, options.locals)
locals.pretty = true if @constructor.prettyPrint
locals
_readTemplate: (template, prefixes, ext) ->
return template unless typeof template == "string"
# tmp
result = @constructor.cache["app/views/#{template}"] ||= @constructor.store().find(path: template, ext: ext, prefixes: prefixes)
throw new Error("Template '#{template}' was not found.") unless result
result
renderWithEngine: (template, engine) ->
if Tower.client
"(#{template}).call(this);"
else
mint = require("mint")
mint[mint.engine(engine || "coffee")] template, {}, (error, result) ->
console.log error if error
class Tower.View.Table extends Tower.View.Component
constructor: (args, options) ->
super
recordOrKey = args.shift()
@key = @recordKey(recordOrKey)
@rowIndex = 0
@cellIndex = 0
@scope = "table"
@headers = []
options.summary ||= "Table for #{_.titleize(@key)}"
#options.class = ["data-table", options.class].compact.uniq.join(" ")
options.role = "grid"
options.class = @addClass(options.class || "", ["table"])
data = options.data ||= {}
#data.url = options.url || @template.controller.request.path
#data.for = options.for || options.model || @key
data.total = options.total if options.hasOwnProperty("total")
data.page = options.page if options.hasOwnProperty("page")
data.count = options.count if options.hasOwnProperty("count")
aria = options.aria || {}
delete options.aria
aria["aria-multiselectable"] = false unless aria.hasOwnProperty("aria-multiselectable") || options.multiselect == true
options.id ||= "#{recordOrKey}-table"
@options =
summary: options.summary
role: options.role
data: options.data
class: options.class
render: (block) ->
@tag "table", @options, =>
block(@) if block
null
tableQueryRowClass: ->
["search-row", if queryParams.except("page", "sort").blank? then null else "search-results"].compact.join(" ")
linkToSort: (title, attribute, options = {}) ->
sortParam = sortValue(attribute, oppositeSortDirection(attribute))
linkTo title, withParams(request.path, sort: sortParam), options
nextPagePath: (collection) ->
withParams(request.path, page: collection.nextPage)
prevPagePath: (collection) ->
withParams(request.path, page: collection.prevPage)
firstPagePath: (collection) ->
withParams(request.path, page: 1)
lastPagePath: (collection) ->
withParams(request.path, page: collection.lastPage)
currentPageNum: ->
page = if params.page then params.page else 1
page = 1 if page < 1
page
caption: ->
# scope='col'
head: (attributes = {}, block) ->
@hideHeader = attributes.visible == false
delete attributes.visible
@_section "head", attributes, block
# scope='row'
# <td headers='x'/>
body: (attributes = {}, block) ->
@_section "body", attributes, block
foot: (attributes = {}, block) ->
@_section "foot", attributes, block
_section: (scope, attributes, block) ->
@rowIndex = 0
@scope = scope
@tag "t#{scope}", attributes, block
@rowIndex = 0
@scope = "table"
row: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
attributes.scope = "row"
if @scope == "body"
#attributes.class = [template.cycle("odd", "even"), attributes.class].compact.uniq.join(" ")
attributes.role = "row"
@rowIndex += 1
@cellIndex = 0
@tag "tr", attributes, block
@cellIndex = 0
column: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
@headers.push attributes.id
tag "col", attributes
@cellIndex += 1
# direction => "ascending"
# valid directions: ascending, descending, none, other
# abbr is what the header controls (for sorting)
header: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.abbr ||= value
attributes.role = "columnheader"
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.scope = "col"
attributes.abbr ||= attributes.for if attributes.hasOwnProperty("for")
attributes.abbr ||= value
delete attributes.for
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
sort = attributes.sort == true
delete attributes.sort
if sort
attributes.class = @addClass attributes.class || "", [attributes.sortClass || "sortable"]
attributes.direction ||= "asc"#@template.sortClass(value)
delete attributes.sortClass
label = attributes.label || _.titleize(value.toString())
delete attributes.label
direction = attributes.direction
delete attributes.direction
if direction
attributes["aria-sort"] = direction
attributes.class = [attributes.class, direction].join(" ")
attributes["aria-selected"] = true
else
attributes["aria-sort"] = "none"
attributes["aria-selected"] = false
@headers.push(attributes.id)
if block
@tag "th", attributes, block
else
if sort
@tag "th", attributes, =>
@linkToSort(label, value)
else
@tag "th", attributes, =>
@tag "span", label
@cellIndex += 1
linkToSort: (label, value) ->
direction = "+"
@tag "a", href: "?sort=#{direction}", =>
@tag "span", label
cell: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.role = "gridcell"
attributes.id ||= @idFor("cell", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
#attributes[:"aria-describedby"] = @headers[@cellIndex]
attributes.headers = @headers[@cellIndex]
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
if block
@tag "td", attributes, block
else
@tag "td", value, attributes
@cellIndex += 1
recordKey: (recordOrKey) ->
if typeof recordOrKey == "string"
recordOrKey
else
recordOrKey.constructor.name
idFor: (type, key, value, row_index = @row_index, column_index = @column_index) ->
[key, type, row_index, column_index].compact.map (node) ->
node.replace(/[\s_]/, "-")
end.join("-")
pixelate: (value) ->
if typeof value == "string" then value else "#{value}px"
Tower.Controller.Elements =
ClassMethods:
# @extractElements $(".item a"), find: {meta: "span small"}, closest: {title: ".item h1"}
extractElements: (target, options = {}) ->
result = {}
for method, selectors of options
for key, selector of selectors
result[key] = target[method](selector)
result
processElements: (target, options = {}) ->
@elements = @extractElements(target, options)
clickHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
try
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
catch error
console.log error
return false
invalidForm: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
Tower.Controller.Events =
ClassMethods:
DOM_EVENTS: [
"click",
"dblclick",
"blur",
"error",
"focus",
"focusIn",
"focusOut",
"hover",
"keydown",
"keypress",
"keyup",
"load",
"mousedown",
"mouseenter",
"mouseleave",
"mousemove",
"mouseout",
"mouseover",
"mouseup",
"mousewheel",
"ready",
"resize",
"scroll",
"select",
"submit",
"tap",
"taphold",
"swipe",
"swipeleft",
"swiperight"
]
dispatcher: global
addEventHandler: (name, handler, options) ->
if options.type == "socket" || !name.match(@DOM_EVENT_PATTERN)
@addSocketEventHandler(name, handler, options)
else
@addDomEventHandler(name, handler, options)
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
@io ||= Tower.Application.instance().io.connect(@socketNamespace())
@io.on name, (data) =>
@_dispatch undefined, handler, data
# http://www.ravelrumba.com/blog/event-delegation-jquery-performance/
addDomEventHandler: (name, handler, options) ->
parts = name.split(/\ +/)
name = parts.shift()
selector = parts.join(" ")
options.target = selector if selector && selector != ""
options.target ||= "body"
eventType = name.split(/[\.:]/)[0]
method = @["#{eventType}Handler"]
if method
method.call @, name, handler, options
else
$(@dispatcher).on name, options.target, (event) => @_dispatch handler, options
@
_dispatch: (handler, options = {}) ->
controller = @instance()
controller.elements ||= {}
controller.params ||= {}
_.extend controller.params, options.params if options.params
_.extend controller.elements, options.elements if options.elements
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.Events.ClassMethods.DOM_EVENT_PATTERN = new RegExp("^(#{Tower.Controller.Events.ClassMethods.DOM_EVENTS.join("|")})")
Tower.Controller.Handlers =
ClassMethods:
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
Tower.View.MetaHelper =
title: (string) ->
document.title = string
Tower.View.ValidationHelper =
success: ->
@redirectTo "/"
failure: (error) ->
if error
@flashError(error)
else
@invalidate()
invalidate: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
class Tower.HTTP.Param.Array extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
class Tower.HTTP.Param.Date extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[\s,\+]/)
for string in array
isRange = false
string.replace /([^\.]+)?(\.\.)([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
values.push [@parseValue(string, ["$eq"])] unless isRange
values
parseValue: (value, operators) ->
super(Tower.date(value), operators)
class Tower.HTTP.Param.Number extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
parseValue: (value, operators) ->
super(parseFloat(value), operators)
class Tower.HTTP.Param.String extends Tower.HTTP.Param
parse: (value) ->
arrays = value.split(/(?:[\s|\+]OR[\s|\+]|\||,)/)
for node, i in arrays
values = []
# ([\+\-\^]?[\w@\-_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')
node.replace /([\+\-\^]?[\w@_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')/g, (_, token) =>
negation = false
exact = false
token = token.replace /^(\+?-+)/, (_, $1) ->
negation = $1 && $1.length > 0
""
token = token.replace /^\'(.+)\'$/, (_, $1) ->
exact = $1 && $1.length > 0
$1
if negation
operators = [if exact then "$neq" else "$notMatch"]
else
operators = [if exact then "$eq" else "$match"]
operators.push "^" if !!token.match(/^\+?\-?\^/)
operators.push "$" if !!token.match(/\$$/)
values.push @parseValue(@_clean(token), operators)
_
arrays[i] = values
arrays
class Tower.HTTP.Route.DSL
constructor: ->
@_scope = {}
match: ->
@scope ||= {}
Tower.HTTP.Route.create(new Tower.HTTP.Route(@_extractOptions(arguments...)))
get: ->
@matchMethod("get", Tower.Support.Array.args(arguments))
post: ->
@matchMethod("post", Tower.Support.Array.args(arguments))
put: ->
@matchMethod("put", Tower.Support.Array.args(arguments))
delete: ->
@matchMethod("delete", Tower.Support.Array.args(arguments))
matchMethod: (method, args) ->
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
name = args.shift()
options.method = method
options.action = name
options.name = name
if @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
path = "/#{name}"
path = @_scope.path + path if @_scope.path
@match(path, options)
@
scope: (options = {}, block) ->
originalScope = @_scope ||= {}
@_scope = Tower.Support.Object.extend {}, originalScope, options
block.call(@)
@_scope = originalScope
@
controller: (controller, options, block) ->
options.controller = controller
@scope(options, block)
namespace: (path, options, block) ->
if typeof options == 'function'
block = options
options = {}
else
options = {}
options = Tower.Support.Object.extend(name: path, path: path, as: path, module: path, shallowPath: path, shallowPrefix: path, options)
if options.name && @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
@scope(options, block)
constraints: (options, block) ->
@scope(constraints: options, block)
defaults: (options, block) ->
@scope(defaults: options, block)
resource: (name, options = {}) ->
options.controller = name
@match "#{name}/new", Tower.Support.Object.extend({action: "new"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{name}/", Tower.Support.Object.extend({action: "show"}, options)
@match "#{name}/edit", Tower.Support.Object.extend({action: "edit"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
resources: (name, options, callback) ->
if typeof options == 'function'
callback = options
options = {}
else
options = {}
options.controller ||= name
path = "/#{name}"
path = @_scope.path + path if @_scope.path
if @_scope.name
many = @_scope.name + Tower.Support.String.camelize(name)
else
many = name
one = Tower.Support.String.singularize(many)
@match "#{path}", Tower.Support.Object.extend({name: "#{many}", action: "index"}, options)
@match "#{path}/new", Tower.Support.Object.extend({name: "new#{Tower.Support.String.camelize(one)}", action: "new"}, options)
@match "#{path}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({name: "#{one}", action: "show"}, options)
@match "#{path}/:id/edit", Tower.Support.Object.extend({name: "edit#{Tower.Support.String.camelize(one)}", action: "edit"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
if callback
@scope Tower.Support.Object.extend({path: "#{path}/:#{Tower.Support.String.singularize(name)}Id", name: one}, options), callback
@
collection: ->
member: ->
root: (options) ->
@match '/', Tower.Support.Object.extend(as: "root", options)
_extractOptions: ->
args = Tower.Support.Array.args(arguments)
path = "/" + args.shift().replace(/^\/|\/$/, "")
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
options.to ||= args.shift() if args.length > 0
options.path = path
format = @_extractFormat(options)
options.path = @_extractPath(options)
method = @_extractRequestMethod(options)
constraints = @_extractConstraints(options)
defaults = @_extractDefaults(options)
controller = @_extractController(options)
anchor = @_extractAnchor(options)
name = @_extractName(options)
options = Tower.Support.Object.extend options,
method: method
constraints: constraints
defaults: defaults
name: name
format: format
controller: controller
anchor: anchor
ip: options.ip
options
_extractFormat: (options) ->
_extractName: (options) ->
options.as || options.name
_extractConstraints: (options) ->
Tower.Support.Object.extend(@_scope.constraints || {}, options.constraints || {})
_extractDefaults: (options) ->
options.defaults || {}
_extractPath: (options) ->
"#{options.path}.:format?"
_extractRequestMethod: (options) ->
(options.method || options.via || "GET").toUpperCase()
_extractAnchor: (options) ->
options.anchor
_extractController: (options = {}) ->
to = options.to
if to
to = to.split('#')
if to.length == 1
action = to[0]
else
controller = to[0]
action = to[1]
controller ||= options.controller || @_scope.controller
action ||= options.action
throw new Error("No controller was specified for the route #{options.path}") unless controller
controller = controller.toLowerCase().replace(/(?:[cC]ontroller)?$/, "Controller")
#action = action.toLowerCase()
name: controller, action: action, className: Tower.Support.String.camelize("#{controller}")
Tower.HTTP.Route.PolymorphicUrls =
ClassMethods:
polymorphicUrl: ->
Tower.HTTP.Route.Urls =
ClassMethods:
urlFor: (options) ->
switch typeof(options)
when "string"
options
else
# https://github.com/kieran/barista/blob/master/lib/route.js#L157
{controller, action, host, port, anchor} = options
Tower.Support.I18n.load model:
errors:
presence: "%{attribute} can't be blank"
minimum: "%{attribute} must be a minimum of %{value}"
maximum: "%{attribute} must be a maximum of %{value}"
length: "%{attribute} must be equal to %{value}"
format: "%{attribute} must be match the format %{value}"
inclusion: "%{attribute} is not included in the list"
exclusion: "%{attribute} is reserved"
invalid: "%{attribute} is invalid"
confirmation: "%{attribute} doesn't match confirmation"
accepted: "%{attribute} must be accepted"
empty: "%{attribute} can't be empty"
blank: "%{attribute} can't be blank"
tooLong: "%{attribute} is too long (maximum is %{count} characters)"
tooShort: "%{attribute} is too short (minimum is %{count} characters)"
wrongLength: "%{attribute} is the wrong length (should be %{count} characters)"
taken: "%{attribute} has already been taken"
notANumber: "%{attribute} is not a number"
greaterThan: "%{attribute} must be greater than %{count}"
greaterThanOrEqualTo: "%{attribute} must be greater than or equal to %{count}"
equalTo: "%{attribute} must be equal to %{count}"
lessThan: "%{attribute} must be less than %{count}"
lessThanOrEqualTo: "%{attribute} must be less than or equal to %{count}"
odd: "%{attribute} must be odd"
even: "%{attribute} must be even"
recordInvalid: "Validation failed: %{errors}"
# Append your own errors here or at the model/attributes scope.
fullMessages:
format: "%{message}"
#format: "%{attribute} %{message}"
class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = <KEY>"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = (callback) ->
@relation(name).first(callback)
self = @
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Scope extends @Scope
# need to do something here about Reflection
class Tower.Model.Relation.HasMany extends Tower.Model.Relation
class @Scope extends @Scope
create: ->
unless @owner.isPersisted()
throw new Error("You cannot call create unless the parent is saved")
relation = @relation
inverseRelation = relation.inverse()
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
id = @owner.get("id")
if inverseRelation && inverseRelation.cache
array = data[inverseRelation.cacheKey] || []
array.push(id) if array.indexOf(id) == -1
data[inverseRelation.cacheKey] = array
else if relation.foreignKey
data[relation.foreignKey] = id if id != undefined
# must check here if owner is instance of foreignType
data[relation.foreignType] ||= @owner.constructor.name if @relation.foreignType
criteria.where(data)
criteria.mergeOptions(options)
if inverseRelation && inverseRelation.counterCacheKey
defaults = {}
defaults[inverseRelation.counterCacheKey] = 1
criteria.where(defaults)
instantiate = options.instantiate != false
{attributes, options} = criteria.toCreate()
options.instantiate = true
@_create criteria, attributes, options, (error, record) =>
unless error
# add the id to the array on the owner record after it's created
if relation && (relation.cache || relation.counterCache)
if relation.cache
push = {}
push[relation.cacheKey] = record.get("id")
if relation.counterCacheKey
inc = {}
inc[relation.counterCacheKey] = 1
updates = {}
updates["$push"] = push if push
updates["$inc"] = inc if inc
@owner.updateAttributes updates, callback
else
callback.call @, error, record if callback
else
callback.call @, error, record if callback
update: ->
destroy: ->
concat: ->
_serializeAttributes: (attributes = {}) ->
target = Tower.constant(@relation.targetClassName)
for name, relation of target.relations()
if attributes.hasOwnProperty(name)
value = attributes[name]
delete attributes[name]
if relation instanceof Tower.Model.Relation.BelongsTo
attributes[relation.foreignKey] = value.id
attributes[relation.foreignType] = value.type if relation.polymorphic
attributes
toCriteria: ->
criteria = super
relation = @relation
if relation.cache
defaults = {}
defaults[relation.foreignKey + "s"] = $in: [@owner.get("id")]
criteria.where(defaults)
criteria
class Tower.Model.Relation.HasOne extends Tower.Model.Relation
Tower.Model.Scope.Finders =
ClassMethods:
finderMethods: [
"find",
"all",
"first",
"last",
"count",
"exists"
]
find: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
{conditions, options} = criteria.toQuery()
@_find conditions, options, callback
first: (callback) ->
{conditions, options} = @toQuery("asc")
@store.findOne conditions, options, callback
last: (callback) ->
{conditions, options} = @toQuery("desc")
@store.findOne conditions, options, callback
all: (callback) ->
{conditions, options} = @toQuery()
@store.find conditions, options, callback
count: (callback) ->
{conditions, options} = @toQuery()
@store.count conditions, options, callback
exists: (callback) ->
{conditions, options} = @toQuery()
@store.exists conditions, options, callback
batch: ->
fetch: ->
_find: (conditions, options, callback) ->
if conditions.id && conditions.id.hasOwnProperty("$in") && conditions.id.$in.length == 1
@store.findOne conditions, options, callback
else if conditions.id && !conditions.id.hasOwnProperty("$in")
conditions.id = {$in: Tower.Support.Object.toArray(conditions.id)}
@store.findOne conditions, options, callback
else
@store.find conditions, options, callback
# @todo
Tower.Model.Scope.Modifiers =
ClassMethods:
atomicModifiers:
"$set": "$set"
"$unset": "$unset"
"$push": "$push"
"$pushAll": "$pushAll"
"$pull": "$pull"
"$pullAll": "$pullAll"
"$inc": "$inc"
"$pop": "$pop"
# { $push : { field : value } }
push: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= []
# @todo check if valid type from schema!
if all && _.isArray(value)
attributes[key] = attributes[key].concat(value)
else
attributes[key].push(value)
@changeAttribute(changes, key, oldValue, attributes[key])
changes
changeAttribute: (changes, key, oldValue, newValue) ->
unless !!changes[key]
changes[key] = [oldValue, newValue]
else
changes[key][1] = newValue
delete changes[key] if changes[key][0] == changes[key][1]
changes
# { $pushAll : { field : array } }
pushAll: (record, updates) ->
@push record, updates, true
pull: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
attributeValue = attributes[key]
oldValue = undefined
if attributeValue && _.isArray(attributeValue)
oldValue = attributeValue.concat()
if all && _.isArray(value)
for item in value
attributeValue.splice _attributeValue.indexOf(item), 1
else
attributeValue.splice _attributeValue.indexOf(value), 1
@changeAttribute(changes, key, oldValue, attributeValue)
changes
pullAll: (record, updates) ->
@pull record, updates, true
inc: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= 0
attributes[key] += value
@changeAttribute changes, key, oldValue, attributes[key]
attributes
set: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
field = schema[key]
oldValue = attributes[key]
if field && field.type == "Array" && !Tower.Support.Object.isArray(value)
attributes[key] ||= []
attributes[key].push value
else
attributes[key] = value
@changeAttribute changes, key, oldValue, attributes[key]
changes
unset: (record, updates) ->
attributes = record.attributes
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] = undefined
@changeAttribute changes, key, oldValue, attributes[key]
changes
update: (record, updates) ->
set = null
for key, value of updates
if @isAtomicModifier(key)
@["#{key.replace("$", "")}"](record, value)
else
set ||= {}
set[key] = value
@set(record, set) if set
record
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
resetAttributes: (keys) ->
@resetAttributes(key) for key in keys
@
resetAttribute: (key) ->
array = @changes[key]
if array
delete @changes[key]
@attributes[key] = array[0]
@
toUpdates: (record) ->
result = {}
changes = record.changes
schema = record.constructor.schema()
for key, value of changes
field = field[key]
if field
if field.type == "Array"
pop = _.difference(value[0], value[1])
if pop.length > 0
result.$pop ||= {}
result.$pop[key] = pop
push = _.difference(value[1], value[0])
if push.length > 0
result.$push ||= {}
result.$push[key] = push
else if field.type == "Integer"
result.$inc ||= {}
result.$inc[key] = (value[1] || 0) - (value[0] || 0)
else
result[key]
result
Tower.Model.Scope.Persistence =
ClassMethods:
persistenceMethods: [
"create",
"update",
"destroy"
]
build: (attributes, options) ->
{conditions, options} = @toCreate()
@_build attributes, conditions, options
# User.create(firstName: "<NAME>")
# User.where(firstName: "<NAME>").create()
# User.where(firstName: "<NAME>").create([{lastName: "<NAME>"}, {lastName: "<NAME>"}])
# User.where(firstName: "<NAME>").create(new User(lastName: "<NAME>"))
# create(attributes)
# create([attributes, attributes])
# create(attributes, options)
create: ->
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
criteria.mergeOptions(options)
@_create criteria, data, options, callback
# User.where(firstName: "<NAME>").update(1, 2, 3)
# User.update(User.first(), User.last(), firstName: "<NAME>")
# User.update([User.first(), User.last()], firstName: "<NAME>")
# User.update([1, 2], firstName: "<NAME>")
update: ->
{criteria, data, options, callback} = @_extractArgs(arguments, ids: true, data: true)
criteria.mergeOptions(options)
@_update criteria, data, options, callback
destroy: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
criteria.mergeOptions(options)
@_destroy criteria, options, callback
sync: ->
transaction: ->
_build: (attributes, conditions, options) ->
if Tower.Support.Object.isArray(attributes)
result = []
for object in attributes
result.push @store.serializeModel(Tower.Support.Object.extend({}, conditions, object))
result
else
@store.serializeModel(Tower.Support.Object.extend({}, conditions, attributes))
_create: (criteria, data, opts, callback) ->
if opts.instantiate
isArray = Tower.Support.Object.isArray(data)
records = Tower.Support.Object.toArray(@build(data))
iterator = (record, next) ->
if record
record.save(next)
else
next()
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
return callback(error) if error
if isArray
callback(error, records)
else
callback(error, records[0])
else
@store.create data, opts, callback
_update: (criteria, data, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.updateAttributes(data, next)
@_each conditions, options, iterator, callback
else
@store.update data, conditions, options, callback
_destroy: (criteria, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.destroy(next)
@_each conditions, options, iterator, callback
else
@store.destroy conditions, options, callback
_each: (conditions, options, iterator, callback) ->
@store.find conditions, options, (error, records) =>
if error
callback.call @, error, records
else
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
callback.call @, error, records if callback
Tower.Model.Scope.Queries =
ClassMethods:
queryMethods: [
"where",
"order",
"asc",
"desc",
"limit",
"offset",
"select",
"joins",
"includes",
"excludes",
"paginate",
"within",
"allIn",
"allOf",
"alsoIn",
"anyIn",
"anyOf",
"near",
"notIn"
]
queryOperators:
">=": "$gte"
"$gte": "$gte"
">": "$gt"
"$gt": "$gt"
"<=": "$lte"
"$lte": "$lte"
"<": "$lt"
"$lt": "$lt"
"$in": "$in"
"$nin": "$nin"
"$any": "$any"
"$all": "$all"
"=~": "$regex"
"$m": "$regex"
"$regex": "$regex"
"$match": "$match"
"$notMatch": "$notMatch"
"!~": "$nm"
"$nm": "$nm"
"=": "$eq"
"$eq": "$eq"
"!=": "$neq"
"$neq": "$neq"
"$null": "$null"
"$notNull": "$notNull"
class Tower.Model.Validator.Format
constructor: (value, attributes) ->
super(value, attributes)
@value = if typeof(value) == 'string' then new RegExp(value) else value
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless !!@value.exec(value)
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.format", attribute: attribute, value: @value.toString())
callback
)
else
@success(callback)
class Tower.Model.Validator.Length extends Tower.Model.Validator
constructor: (name, value, attributes) ->
super
@validate = switch name
when "min" then @validateMinimum
when "max" then @validateMaximum
else
@validateLength
validateMinimum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value >= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.minimum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateMaximum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value <= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.maximum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateLength: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value == @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.length", attribute: attribute, value: @value)
callback
)
@success(callback)
class Tower.Model.Validator.Presence extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
unless Tower.Support.Object.isPresent(record.get(attribute))
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.presence", attribute: attribute),
callback
)
@success(callback)
class Tower.Model.Validator.Uniqueness extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
conditions = {}
conditions[attribute] = value
record.constructor.where(conditions).exists (error, result) =>
if result
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.uniqueness", attribute: attribute, value: value),
callback
)
else
@success(callback)
Tower.Controller.Caching =
freshWhen: ->
stale: ->
expiresIn: ->
Tower.Controller.Events =
ClassMethods:
addEventHandler: (name, handler, options) ->
@_addSocketEventHandler name, handler, options
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
unless @io
@_socketHandlers = {}
@io = Tower.Application.instance().socket.of(@socketNamespace()).on "connection", (socket) =>
for eventType, handler of @_socketHandlers
do (eventType, handler) ->
if eventType isnt 'connection' and eventType isnt 'disconnect'
socket.on eventType, (data) =>
@_dispatch undefined, handler, data
@_socketHandlers[name] = handler
_dispatch: (event, handler, locals = {}) ->
controller = new @
for key, value of locals
controller.params[key] = value
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.HTTP =
head: (status, options = {}) ->
if typeof status == "object"
options = status
status = null
status ||= options.status || "ok"
location = options.location
delete options.status
delete options.location
#for key, value of options
# @headers[key.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
@status = status
@location = Tower.urlFor(location) if location
@headers["Content-Type"] = Mime[formats.first] if formats
@body = " "
Tower.Controller.addRenderers
json: (json, options, callback) ->
json = JSON.stringify(json) unless typeof(json) == "string"
json = "#{options.callback}(#{json})" if options.callback
@headers["Content-Type"] ||= require("mime").lookup("json")
callback null, json if callback
json
# https://github.com/wdavidw/node-csv-parser
# csv: (csv, options, callback) ->
# https://github.com/devongovett/pdfkit
# pdf: (data, options, callback) ->
Tower.Controller.Sockets =
broadcast: ->
emit: ->
connect: ->
Tower.Mailer.Configuration =
ClassMethods:
lib: -> require('mailer')
Tower.Mailer.Rendering =
ClassMethods:
mail: (options = {}, callback) ->
@host = options.host
@port = options.port
@domain = options.domain
@to = options.to
@from = options.from
@subject = options.subject
@locals = options.locals || {}
@template = options.template
deliver: ->
email = @constructor.lib()
self = @
Shift.render path: @template, @locals, (error, body) ->
options =
host: self.host
port: self.port
domain: self.domain
to: self.to
from: self.from
subject: self.subject
body: body
authentication: self.login
username: self.username
password: <PASSWORD>
email.send options, (error, result) ->
console.log error if error
console.log result
Tower.Support.I18n.load date:
formats:
# Use the strftime parameters for formats.
# When no format has been given", it uses default.
# You can provide other formats here if you like!
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
abbrDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
# Don't forget the nil at the beginning; there's no such thing as a 0th month
monthNames: [null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
abbrMonthNames: [null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Used in dateSelect and datetimeSelect.
order: ["year", "month", "day"]
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
# Used in array.toSentence.
support:
array:
wordsConnector: ", "
twoWordsConnector: " and "
lastWordConnector: ", and "
class Tower.View.Form.Builder extends Tower.View.Component
constructor: (args, options = {}) ->
@template = options.template
@model = options.model
@attribute = options.attribute
@parentIndex = options.parentIndex
@index = options.index
@tabindex = options.tabindex
@accessKeys = options.accessKeys
#@attributes = @cloneAttributes(options.except(:template, :model, :attribute, :accessKeys, :index, :tabindex))
defaultOptions: (options = {}) ->
options.model ||= @model
options.index ||= @index
options.attribute ||= @attribute
options.template ||= @template
options
fieldset: (args...) ->
block = args.pop()
options = @defaultOptions(Tower.Support.Array.extractOptions(args))
options.label ||= args.shift()
new Tower.View.Form.Fieldset([], options).render(block)
fields: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as = "fields"
options.label ||= false
attribute = args.shift() || @attribute
@field attribute, options, (_field) =>
@fieldset(block)
fieldsFor: ->
options = args.extractOptions
attribute = args.shift
macro = model.macroFor(attribute)
attrName = nil
if options.as == "object"
attrName = attribute.toS
else
attrName = if Tower.View.renameNestedAttributes then "#{attribute}_attributes" else attribute.toS
# -> something here for counts
subParent = model.object
subObject = args.shift
index = options.delete("index")
unless index.present? && typeof index == "string"
if subObject.blank? && index.present?
subObject = subParent.send(attribute)[index]
else if index.blank? && subObject.present? && macro == "hasMany"
index = subParent.send(attribute).index(subObject)
subObject ||= model.default(attribute) || model.toS.camelize.constantize.new
keys = [model.keys, attrName]
options.merge(
template: template
model: model
parentIndex: index
accessKeys: accessKeys
tabindex: tabindex
)
new Tower.View.Form.Builder(options).render(block)
field: ->
args = Tower.Support.Array.args(arguments)
last = args[args.length - 1]
args.pop() if last == null || last == undefined
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
attributeName = args.shift() || "attribute.name"
#attribute = Storefront:"Attribute".new(
# name: attributeName,
# model: @model,
# required: options.required == true,
# disabled: options.disabled == true,
# topLevel: options.attribute == false
#)
defaults =
template: @template
model: @model
attribute: attributeName,
parentIndex: @parentIndex
index: @index
fieldHTML: options.fieldHTML || {}
inputHTML: options.inputHTML || {}
labelHTML: options.labelHTML || {}
errorHTML: options.errorHTML || {}
hintHtml: options.hintHtml || {}
new Tower.View.Form.Field([], _.extend(defaults, options)).render(block)
button: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as ||= "submit"
options.value = args.shift() || "Submit"
options.class = Tower.View.submitFieldsetClass if options.as == "submit"
@field options.value, options, block
submit: @::button
partial: (path, options = {}) ->
@template.render partial: path, locals: options.merge(fields: self)
tag: (key, args...) ->
@template.tag key, args
render: (block) ->
block(@)
class Tower.View.Form.Field extends Tower.View.Component
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
toId: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "-#{options.parentIndex}" if options.parentIndex
result += "-#{Tower.Support.String.parameterize(@attribute)}"
result += "-#{options.type || "field"}"
result += "-#{@index}" if @index?
result
toParam: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "[#{options.parentIndex}]" if options.parentIndex
result += "[#{@attribute}]"
result += "[#{@index}]" if @index?
result
constructor: (args, options) ->
@labelValue = options.label
delete options.label
super(args, options)
@required ||= false
# input type
field = @model.constructor.fields()[@attribute]
options.as ||= if field then Tower.Support.String.camelize(field.type, true) else "string"
@inputType = inputType = options.as
@required = !!(field && field.required == true)
# class
classes = [Tower.View.fieldClass, inputType]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
if options.validate != false && field.validations
classes.push Tower.View.validateClass
@fieldHTML.class = @addClass @fieldHTML.class, classes
# id
if !@fieldHTML.id && Tower.View.idEnabledOn.indexOf("field") > -1
@fieldHTML.id = @toId(type: "field", index: @index, parentIndex: @parentIndex)
@inputHTML.id = @toId(type: "input", index: @index, parentIndex: @parentIndex)
unless ["hidden", "submit"].indexOf(inputType) > -1
@labelHTML.for ||= @inputHTML.id
@labelHTML.class = @addClass @labelHTML.class, [Tower.View.labelClass]
unless @labelValue == false
@labelValue ||= Tower.Support.String.camelize(@attribute.toString())
unless options.hint == false
@errorHTML.class = @addClass @errorHTML.class, [Tower.View.errorClass]
if Tower.View.includeAria && Tower.View.hintIsPopup
@errorHTML.role ||= "tooltip"
@attributes = @fieldHTML
@inputHTML.name ||= @toParam() unless inputType == "submit"
@value = options.value
@dynamic = options.dynamic == true
@richInput = if options.hasOwnProperty("rich_input") then !!options.rich_input else Tower.View.richInput
@validate = options.validate != false
classes = [inputType, Tower.Support.String.parameterize(@attribute), @inputHTML.class]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
classes.push "input"
if options.validate != false && field.validations
classes.push Tower.View.validateClass
# class
@inputHTML.class = @addClass @inputHTML.class, classes
@inputHTML.placeholder = options.placeholder if options.placeholder
# value
unless @inputHTML.value?
if options.hasOwnProperty("value")
@inputHTML.value = options.value
unless @inputHTML.value?
value = @model.get(@attribute)
@inputHTML.value = value if value
# @inputHTML[:tabindex] = @tabindex
@inputHTML.maxlength ||= options.max if options.hasOwnProperty("max")
# expressions
pattern = options.match
pattern = pattern.toString() if _.isRegExp(pattern)
@inputHTML["data-match"] = pattern if pattern?
@inputHTML["aria-required"] = @required.toString()
@inputHTML.required = "true" if @required == true
@inputHTML.disabled = "true" if @disabled
@inputHTML.autofocus = "true" if @autofocus == true
@inputHTML["data-dynamic"] = "true" if @dynamic
@inputHTML.title ||= @inputHTML.placeholder if @inputHTML.placeholder
@autocomplete = @inputHTML.autocomplete == true
if @autocomplete && Tower.View.includeAria
@inputHTML["aria-autocomplete"] = switch @autocomplete
when "inline", "list", "both"
@autocomplete
else
"both"
input: (args...) ->
options = _.extend @inputHTML, Tower.Support.Array.extractOptions(args)
key = args.shift() || @attribute
@["#{@inputType}Input"](key, options)
checkboxInput: (key, options) ->
@tag "input", _.extend(type: "checkbox", options)
stringInput: (key, options) ->
@tag "input", _.extend(type: "text", options)
submitInput: (key, options) ->
@tag "input", _.extend(type: "submit", options)
fileInput: (key, options) ->
@tag "input", _.extend(type: "file", options)
textInput: (key, options) ->
@tag "textarea", options
password_input: (key, options) ->
@tag "input", _.extend(type: "password", options)
emailInput: (key, options) ->
@tag "input", _.extend(type: "email", options)
urlInput: (key, options) ->
@tag "input", _.extend(type: "url", options)
numberInput: (key, options) ->
@tag "input", _.extend(type: "string", "data-type": "numeric", options)
searchInput: (key, options) ->
@tag "input", _.extend(type: "search", "data-type": "search", options)
phoneInput: (key, options) ->
@tag "input", _.extend(type: "tel", "data-type": "phone", options)
label: ->
return unless @labelValue
@tag "label", @labelHTML, =>
@tag "span", @labelValue
if @required
@tag "abbr", title: Tower.View.requiredTitle, class: Tower.View.requiredClass, -> Tower.View.requiredAbbr
else
@tag "abbr", title: Tower.View.optionalTitle, class: Tower.View.optionalClass, -> Tower.View.optionalAbbr
render: (block) ->
@tag Tower.View.fieldTag, @attributes, =>
if block
block.call @
else
@label()
@input()
#elements = extractElements!(attributes)
#
#result = elements.map do |element|
# Array(send(element)).map(&"render")
#template.hamlConcat result.flatten.join.gsub(/\n$/, "") if result.present?
#
#yield(self) if blockGiven? # template.captureHaml(self, block)
extractElements: (options = {}) ->
elements = []
if ["hidden", "submit"].include?(inputType)
elements.push "inputs"
else
if @label.present? && @label.value?
elements.push "label"
elements = elements.concat ["inputs", "hints", "errors"]
elements
class Tower.View.Form.Fieldset extends Tower.View.Component
constructor: (args, options) ->
super
#@label = @localize("titles", options[:label], nil, (attributes[:locale_options] || {}).merge(:allow_blank => true)) if options[:label].present?
#merge_class! attributes, *[
# config.fieldset_class
#]
@attributes = attributes = {}
#attributes.id ||= label.underscore.strip.gsub(/[_\s]+/, config.separator) if label.present?
delete attributes.index
delete attributes.parentIndex
delete attributes.label
@builder = new Tower.View.Form.Builder([],
template: @template
model: @model
attribute: @attribute
index: @index
parentIndex: @parentIndex
)
# form.inputs :basic_info, :locale_options => {:count => 1, :past => true}
render: (block) ->
@tag "fieldset", @attributes, =>
if @label
@tag "legend", class: Tower.View.legendClass, =>
@tag "span", @label
@tag Tower.View.fieldListTag, class: Tower.View.fieldListClass, =>
@builder.render(block)
Tower.View.ComponentHelper =
formFor: ->
Tower.View.Form.render(__ck, arguments...)
tableFor: ->
Tower.View.Table.render(__ck, arguments...)
widget: ->
linkTo: (title, path, options = {}) ->
a _.extend(options, href: path, title: title), title.toString()
Tower.View.ElementHelper =
title: (value) ->
document.title = value
addClass: (string, parts...) ->
classes = string.split(/\ +/)
for part in parts
classes.push(part) if classes.indexOf(part) > -1
classes.join(" ")
# @elementId @user, "form"
# #=> "#user-form"
#
# @elementId @user, "<NAME>", "field"
# #=> "#user-first-name-field"
elementId: ->
"##{@elementKey(arguments...)}"
elementClass: ->
".#{@elementKey(arguments...)}"
elementKey: ->
Tower.Support.String.parameterize(@elementNameComponents(arguments...).join("-"))
# @elementName @user, "<NAME>"
# #=> "user[firstName]"
#
# @elementName @user, "address", "city"
# #=> "user[address][city]"
elementName: ->
result = @elementNameComponents(arguments...)
i = 1
for item, i in result
result[i] = "[#{item}]"
Tower.Support.String.parameterize(result.join(""))
elementNameComponents: ->
args = Tower.Support.Array.args(arguments)
result = []
for item in args
switch typeof item
when "function"
result.push item.constructor.name
when "string"
result.push item
else
result.push item.toString()
result
for filter in ["stylus", "less", "markdown"]
@[filter] = (text) ->
Tower.View.render(text, filter: filter)
Tower.View.HeadHelper =
metaTag: (name, content) ->
meta name: name, content: content
snapshotLinkTag: (href) ->
linkTag rel: "imageSrc", href: href
html4ContentTypeTag: (charset = "UTF-8", type = "text/html") ->
httpMetaTag "Content-Type", "#{type}; charset=#{charset}"
chromeFrameTag: ->
html4ContentTypeTag()
meta "http-equiv": "X-UA-Compatible", content: "IE=Edge,chrome=1"
html5ContentTypeTag: (charset = "UTF-8") ->
meta charset: charset
contentTypeTag: (charset) ->
html5ContentTypeTag charset
csrfMetaTag: ->
metaTag "csrf-token", @request.session._csrf
searchLinkTag: (href, title) ->
linkTag rel: "search", type: "application/opensearchdescription+xml", href: href, title: title
faviconLinkTag: (favicon = "/favicon.ico") ->
linkTag rel: "shortcut icon", href: favicon, type: "image/x-icon"
linkTag: (options = {}) ->
link options
ieApplicationMetaTags: (title, options = {}) ->
result = []
result.push metaTag("application-name", title)
result.push metaTag("msapplication-tooltip", options.tooltip) if options.hasOwnProperty("tooltip")
result.push metaTag("msapplication-starturl", options.url) if options.hasOwnProperty("url")
if options.hasOwnProperty("width") && options.hasOwnProperty("height")
result.push metaTag("msapplication-window", "width=#{options.width};height=#{options.height}")
result.push metaTag("msapplication-navbutton-color", options.color) if options.hasOwnProperty("color")
result.join("\n")
ieTaskMetaTag: (name, path, icon = null) ->
content = []
content.push "name=#{name}"
content.push "uri=#{path}"
content.push "icon-uri=#{icon}" if icon
@metaTag "msapplication-task", content.join(";")
appleMetaTags: (options = {}) ->
result = []
result.push appleViewportMetaTag(options)
result.push appleFullScreenMetaTag(options.fullScreen) if options.hasOwnProperty("fullScreen")
result.push appleMobileCompatibleMetaTag(options.mobile) if options.hasOwnProperty("mobile")
result.join()
# http://www.html5rocks.com/en/mobile/mobifying.html
appleViewportMetaTag: (options = {}) ->
viewport = []
viewport.push "width=#{options.width}" if options.hasOwnProperty("width")
viewport.push "height=#{options.height}" if options.hasOwnProperty("height")
viewport.push "initial-scale=#{options.scale || 1.0}"
viewport.push "minimum-scale=#{options.min}" if options.hasOwnProperty("min")
viewport.push "maximum-scale=#{options.max}" if options.hasOwnProperty("max")
viewport.push "user-scalable=#{boolean(options.scalable)}" if options.hasOwnProperty("scalable")
metaTag "viewport", viewport.join(", ")
appleFullScreenMetaTag: (value) ->
metaTag "apple-touch-fullscreen", boolean(value)
appleMobileCompatibleMetaTag: (value) ->
metaTag "apple-mobile-web-app-capable", boolean(value)
appleTouchIconLinkTag: (path, options = {}) ->
rel = ["apple-touch-icon"]
rel.push "#{options.size}x#{options.size}" if options.hasOwnProperty("size")
rel.push "precomposed" if options.precomposed
linkTag rel: rel.join("-"), href: path
appleTouchIconLinkTags: (path, sizes...) ->
if typeof sizes[sizes.length - 1] == "object"
options = sizes.pop()
else
options = {}
result = []
for size in sizes
result.push appleTouchIconLinkTag(path, _.extend(size: size, options))
result.join()
openGraphMetaTags: (options = {}) ->
openGraphMetaTag("og:title", options.title) if options.title
openGraphMetaTag("og:type", options.type) if options.type
openGraphMetaTag("og:image", options.image) if options.image
openGraphMetaTag("og:siteName", options.site) if options.site
openGraphMetaTag("og:description", options.description) if options.description
openGraphMetaTag("og:email", options.email) if options.email
openGraphMetaTag("og:phoneNumber", options.phone) if options.phone
openGraphMetaTag("og:faxNumber", options.fax) if options.fax
openGraphMetaTag("og:latitude", options.lat) if options.lat
openGraphMetaTag("og:longitude", options.lng) if options.lng
openGraphMetaTag("og:street-address", options.street) if options.street
openGraphMetaTag("og:locality", options.city) if options.city
openGraphMetaTag("og:region", options.state) if options.state
openGraphMetaTag("og:postal-code", options.zip) if options.zip
openGraphMetaTag("og:country-name", options.country) if options.country
null
openGraphMetaTag: (property, content) ->
meta property: property, content: content
Tower.View.RenderingHelper =
partial: (path, options, callback) ->
try
if typeof options == "function"
callback = options
options = {}
options ||= {}
options.locals ||= {}
locals = options.locals
path = path.split("/")
path[path.length - 1] = "_#{path[path.length - 1]}"
path = path.join("/")
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
template = @renderWithEngine(String(template))
if options.collection
name = options.as || Tower.Support.String.camelize(options.collection[0].constructor.name, true)
tmpl = eval "(function(data) { with(data) { this.#{name} = #{name}; #{String(template)} } })"
for item in options.collection
locals[name] = item
tmpl.call(@, locals)
delete @[name]
else
tmpl = "(function(data) { with(data) { #{String(template)} } })"
eval(tmpl).call(@, locals)
catch error
console.log error.stack || error
null
page: ->
args = Tower.Support.Array.args(arguments)
options = Tower.Support.Array.extractOptions(args)
browserTitle = args.shift() || options.title
@contentFor "title", ->
title browserTitle
urlFor: ->
Tower.urlFor(arguments...)
yields: (key) ->
value = @[key]
if typeof value == "function"
eval("(#{String(value)})()")
else
#__ck.indent()
ending = if value.match(/\n$/) then "\n" else ""
text(value.replace(/\n$/, "").replace(/^(?!\s+$)/mg, __ck.repeat(' ', __ck.tabs)) + ending)
null
hasContentFor: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
has: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
contentFor: (key, block) ->
@[key] = block
null
Tower.View.StringHelper =
# Characters that need to be escaped to HTML entities from user input
HTML_ESCAPE:
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
preserve: (text) ->
text.replace(/\n/g, '
').replace(/\r/g, '')
htmlEscape: (text) ->
text.replace /[\"><&]/g, (_) => @HTML_ESCAPE[_]
t: (string) ->
Tower.Support.I18n.translate(string)
l: (object) ->
Tower.Support.I18n.localize(string)
boolean: (boolean) ->
if boolean then "yes" else "no"
| true |
window.global ||= window
module = global.module || {}
global.Tower = Tower = {}
Tower.version = "0.3.0"
Tower.logger = console
require './support'
require './application'
require './client/application'
require './store'
require './client/store'
require './model'
require './view'
require './client/view'
require './controller'
require './client/controller'
require './http'
require './middleware'
class Tower.Controller extends Tower.Class
@include Tower.Support.Callbacks
@extend Tower.Support.EventEmitter
@include Tower.Support.EventEmitter
@instance: ->
@_instance ||= new @
@metadata: ->
@_metadata ||= {}
constructor: ->
@constructor._instance = @
@headers = {}
@status = 200
@request = null
@response = null
@params = {}
@query = {}
@resourceName = @constructor.resourceName()
@resourceType = @constructor.resourceType()
@collectionName = @constructor.collectionName()
@formats = _.keys(@constructor.mimes())
if @constructor._belongsTo
@hasParent = true
else
@hasParent = false
require './controller/callbacks'
require './controller/helpers'
require './controller/instrumentation'
require './controller/params'
require './controller/redirecting'
require './controller/rendering'
require './controller/resourceful'
require './controller/responder'
require './controller/responding'
Tower.Controller.include Tower.Controller.Callbacks
Tower.Controller.include Tower.Controller.Helpers
Tower.Controller.include Tower.Controller.Instrumentation
Tower.Controller.include Tower.Controller.Params
Tower.Controller.include Tower.Controller.Redirecting
Tower.Controller.include Tower.Controller.Rendering
Tower.Controller.include Tower.Controller.Resourceful
Tower.Controller.include Tower.Controller.Responding
Tower.HTTP = {}
require './http/agent'
require './http/cookies'
require './http/param'
require './http/route'
require './http/request'
require './http/response'
require './http/url'
class Tower.Model extends Tower.Class
# @example All configuration options
# class App.User extends Tower.Model
# @configure
#
# @example Configure using a function
# class App.User extends Tower.Model
# @configure ->
# defaultStore: Tower.Store.Memory
@configure: (object) ->
@config ||= {}
object = object.call @ if typeof object == "function"
_.extend @config, object
@
# @example All default options
# class App.User extends Tower.Model
# @defaults store: Tower.Store.Memory, scope: @desc("createdAt")
@defaults: (object) ->
@default(key, value) for key, value of object
@_defaults
# @example All default options
# class App.User extends Tower.Model
# @default "store", Tower.Store.Memory
# @default "scope", @desc("createdAt")
@default: (key, value) ->
@_defaults ||= {}
@_defaults[key] = value
constructor: (attrs, options) ->
@initialize attrs, options
initialize: (attrs = {}, options = {}) ->
definitions = @constructor.fields()
attributes = {}
for name, definition of definitions
attributes[name] = definition.defaultValue(@) unless attrs.hasOwnProperty(name)
@attributes = attributes
@changes = {}
@errors = {}
@readOnly = if options.hasOwnProperty("readOnly") then options.readOnly else false
@persistent = if options.hasOwnProperty("persistent") then options.persisted else false
@attributes[key] = value for key, value of attrs
require './model/scope'
require './model/criteria'
require './model/dirty'
require './model/conversion'
require './model/inheritance'
require './model/relation'
require './model/relations'
require './model/attribute'
require './model/attributes'
require './model/persistence'
require './model/scopes'
require './model/serialization'
require './model/validator'
require './model/validations'
require './model/timestamp'
require './model/locale/en'
Tower.Model.include Tower.Support.Callbacks
Tower.Model.include Tower.Model.Conversion
Tower.Model.include Tower.Model.Dirty
Tower.Model.include Tower.Model.Criteria
Tower.Model.include Tower.Model.Scopes
Tower.Model.include Tower.Model.Persistence
Tower.Model.include Tower.Model.Inheritance
Tower.Model.include Tower.Model.Serialization
Tower.Model.include Tower.Model.Relations
Tower.Model.include Tower.Model.Validations
Tower.Model.include Tower.Model.Attributes
Tower.Model.include Tower.Model.Timestamp
require 'underscore.logger'
global._ = require 'underscore'
_.mixin(require('underscore.string'))
Tower.version = JSON.parse(require("fs").readFileSync(require("path").normalize("#{__dirname}/../../package.json"))).version
Tower.logger = _console
require './support'
require './application'
require './server/application'
require './store'
require './server/store'
require './model'
require './view'
require './controller'
require './server/controller'
require './http'
require './middleware'
require './server/middleware'
require './server/command'
require './server/generator'
Tower.Model.defaultStore = Tower.Store.MongoDB
Tower.View.store(new Tower.Store.FileSystem(["app/views"]))
Tower.root = process.cwd()
Tower.publicPath = process.cwd() + "/public"
Tower.publicCacheDuration = 60 * 1000
Tower.sessionSecret = "tower-session-secret"
Tower.cookieSecret = "tower-cookie-secret"
Tower.render = (string, options = {}) ->
require("mint").render(options.type, string, options)
Tower.domain = "localhost"
Tower.date = ->
require('moment')(arguments...)._d
Tower.run = (argv) ->
(new Tower.Command.Server(argv)).run()
Tower.Support = {}
require './support/array'
require './support/callbacks'
require './support/class'
require './support/eventEmitter'
require './support/i18n'
require './support/number'
require './support/object'
require './support/regexp'
require './support/string'
require './support/url'
require './support/locale/en'
class Tower.View extends Tower.Class
@extend
cache: {}
engine: "coffee"
prettyPrint: false
loadPaths: ["app/views"]
componentSuffix: "widget"
hintClass: "hint"
hintTag: "figure"
labelClass: "label"
requiredClass: "required"
requiredAbbr: "*"
requiredTitle: "Required"
errorClass: "error"
errorTag: "output"
validClass: null
optionalClass: "optional"
optionalAbbr: ""
optionalTitle: "Optional"
labelMethod: "humanize"
labelAttribute: "toLabel"
validationMaxLimit: 255
defaultTextFieldSize: null
defaultTextAreaWidth: 300
allFieldsRequiredByDefault: true
fieldListTag: "ol"
fieldListClass: "fields"
fieldTag: "li"
separator: "-"
breadcrumb: " - "
includeBlankForSelectByDefault: true
collectionLabelMethods: ["toLabel", "displayName", "fullName", "name", "title", "toString"]
i18nLookupsByDefault: true
escapeHtmlEntitiesInHintsAndLabels: false
renameNestedAttributes: true
inlineValidations: true
autoIdForm: true
fieldsetClass: "fieldset"
fieldClass: "field"
validateClass: "validate"
legendClass: "legend"
formClass: "form"
idEnabledOn: ["input", "field"] # %w(field label error hint)
widgetsPath: "shared/widgets"
navClass: "list-item"
includeAria: true
activeClass: "active"
navTag: "li"
termsTag: "dl"
termClass: "term"
termKeyClass: "key"
termValueClass: "value"
hintIsPopup: false
listTag: "ul"
pageHeaderId: "header"
pageTitleId: "title"
autoIdNav: false
pageSubtitleId: "subtitle"
widgetClass: "widget"
headerClass: "header"
titleClass: "title"
subtitleClass: "subtitle"
contentClass: "content"
defaultHeaderLevel: 3
termSeparator: ":"
richInput: false
submitFieldsetClass: "submit-fieldset"
addLabel: "+"
removeLabel: "-"
cycleFields: false
alwaysIncludeHintTag: false
alwaysIncludeErrorTag: true
requireIfValidatesPresence: true
localizeWithNamespace: false
localizeWithNestedModel: false
localizeWithInheritance: true
defaultComponentHeaderLevel: 3
helpers: []
metaTags: [
"description",
"keywords",
"author",
"copyright",
"category",
"robots"
]
store: (store) ->
@_store = store if store
@_store ||= new Tower.Store.Memory(name: "view")
renderers: {}
constructor: (context = {}) ->
@_context = context
require './view/helpers'
require './view/rendering'
require './view/component'
require './view/table'
require './view/form'
require './view/helpers/assetHelper'
require './view/helpers/componentHelper'
require './view/helpers/elementHelper'
require './view/helpers/headHelper'
require './view/helpers/renderingHelper'
require './view/helpers/stringHelper'
Tower.View.include Tower.View.Rendering
Tower.View.include Tower.View.Helpers
Tower.View.include Tower.View.AssetHelper
Tower.View.include Tower.View.ComponentHelper
Tower.View.include Tower.View.HeadHelper
Tower.View.include Tower.View.RenderingHelper
Tower.View.include Tower.View.StringHelper
Tower.View.helpers.push Tower.View.AssetHelper
Tower.View.helpers.push Tower.View.ComponentHelper
Tower.View.helpers.push Tower.View.HeadHelper
Tower.View.helpers.push Tower.View.RenderingHelper
Tower.View.helpers.push Tower.View.StringHelper
require './controller/elements'
require './controller/events'
require './controller/handlers'
Tower.Controller.include Tower.Controller.Elements
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.Handlers
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
require './view/formHelper'
require './view/metaHelper'
require './view/validationHelper'
Tower.Controller.Callbacks =
ClassMethods:
beforeAction: ->
@before "action", arguments...
afterAction: ->
@after "action", arguments...
Tower.Controller.Helpers =
ClassMethods:
helper: (object) ->
@_helpers ||= []
@_helpers.push(object)
layout: (layout) ->
@_layout = layout
layout: ->
layout = @constructor._layout
if typeof(layout) == "function" then layout.call(@) else layout
Tower.Controller.Instrumentation =
call: (request, response, next) ->
@request = request
@response = response
@params = @request.params || {}
@cookies = @request.cookies || {}
@query = @request.query || {}
@session = @request.session || {}
@format = @params.format || "html"
@action = @params.action
@headers = {}
@callback = next
@process()
process: ->
@processQuery()
# hacking in logging for now
unless Tower.env.match(/(test|production)/)
console.log " Processing by #{@constructor.name}##{@action} as #{@format.toUpperCase()}"
console.log " Parameters:"
console.log @params
@runCallbacks "action", name: @action, (callback) =>
@[@action].call @, callback
processQuery: ->
clear: ->
@request = null
@response = null
@headers = null
Tower.Controller.Params =
ClassMethods:
params: (options, callback) ->
if typeof options == 'function'
callback = options
options = {}
if options
@_paramsOptions = Tower.Support.Object.extend(@_paramsOptions || {}, options)
callback.call(@)
@_params ||= {}
param: (key, options = {}) ->
@_params ||= {}
@_params[key] = Tower.HTTP.Param.create(key, Tower.Support.Object.extend({}, @_paramsOptions || {}, options))
criteria: ->
return @_criteria if @_criteria
@_criteria = criteria = new Tower.Model.Criteria
parsers = @constructor.params()
params = @params
for name, parser of parsers
if params.hasOwnProperty(name)
criteria.where(parser.toCriteria(params[name]))
criteria
Tower.Controller.Redirecting =
redirectTo: ->
@redirect arguments...
# @todo, better url extraction
redirect: ->
try
args = Tower.Support.Array.args(arguments)
console.log "redirect"
console.log @resourceType
console.log args
options = Tower.Support.Array.extractOptions(args)
console.log options
url = args.shift()
if !url && options.hasOwnProperty("action")
url = switch options.action
when "index", "new"
Tower.urlFor(@resourceType, action: options.action)
when "edit", "show"
Tower.urlFor(@resource, action: options.action)
url ||= "/"
console.log url
@response.redirect url
catch error
console.log error
@callback() if @callback
Tower.Controller.Rendering =
ClassMethods:
addRenderer: (key, block) ->
@renderers()[key] = block
addRenderers: (renderers = {}) ->
@addRenderer(key, block) for key, block of renderers
@
renderers: ->
@_renderers ||= {}
render: ->
@renderToBody @_normalizeRender(arguments...)
renderToBody: (options) ->
@_processRenderOptions(options)
@_renderTemplate(options)
renderToString: ->
@renderToBody @_normalizeRender(arguments...)
sendFile: (path, options = {}) ->
sendData: (data, options = {}) ->
_renderTemplate: (options) ->
_callback = options.callback
callback = (error, body) =>
if error
@status ||= 404
@body = error.stack
else
@status ||= 200
@body = body
_callback.apply @, arguments if _callback
@callback() if @callback
return if @_handleRenderers(options, callback)
@headers["Content-Type"] ||= "text/html"
view = new Tower.View(@)
try
view.render.call view, options, callback
catch error
callback error
_handleRenderers: (options, callback) ->
for name, renderer of Tower.Controller.renderers()
if options.hasOwnProperty(name)
renderer.call @, options[name], options, callback
return true
false
_processRenderOptions: (options = {}) ->
@status = options.status if options.status
@headers["Content-Type"] = options.contentType if options.contentType
@headers["Location"] = @urlFor(options.location) if options.location
@
_normalizeRender: ->
@_normalizeOptions @_normalizeArgs(arguments...)
_normalizeArgs: ->
args = Tower.Support.Array.args(arguments)
if typeof args[0] == "string"
action = args.shift()
if typeof args[0] == "object"
options = args.shift()
if typeof args[0] == "function"
callback = args.shift()
options ||= {}
if action
key = if !!action.match(/\//) then "file" else "action"
options[key] = action
options.callback = callback if callback
options
_normalizeOptions: (options = {}) ->
options.partial = @action if options.partial == true
options.prefixes ||= []
options.prefixes.push @collectionName
options.template ||= (options.file || (options.action || @action))
options
Tower.Controller.Resourceful =
ClassMethods:
resource: (options) ->
@_resourceName = options.name if options.hasOwnProperty("name")
@_resourceType = options.type if options.hasOwnProperty("type")
@_collectionName = options.collectionName if options.hasOwnProperty("collectionName")
@
resourceType: ->
@_resourceType ||= Tower.Support.String.singularize(@name.replace(/(Controller)$/, ""))
resourceName: ->
return @_resourceName if @_resourceName
parts = @resourceType().split(".")
@_resourceName = Tower.Support.String.camelize(parts[parts.length - 1], true)
collectionName: ->
@_collectionName ||= Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), true)
belongsTo: (key, options = {}) ->
options.key = key
options.type ||= Tower.Support.String.camelize(options.key)
@_belongsTo = options
actions: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
actions = ["index", "new", "create", "show", "edit", "update", "destroy"]
actionsToRemove = _.difference(actions, args, options.except || [])
for action in actionsToRemove
@[action] = null
delete @[action]
@
index: ->
#@_index arguments...
@_index (format) =>
format.html => @render "index"
format.json => @render json: @collection, status: 200
new: ->
@_new (format) =>
format.html => @render "new"
format.json => @render json: @resource, status: 200
create: (callback) ->
@_create (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
show: ->
@_show (format) =>
format.html => @render "show"
format.json => @render json: @resource, status: 200
edit: ->
@_edit (format) =>
format.html => @render "edit"
format.json => @render json: @resource, status: 200
update: ->
@_update (format) =>
format.html => @redirectTo action: "show"
format.json => @render json: @resource, status: 200
destroy: ->
@_destroy (format) =>
format.html => @redirectTo action: "index"
format.json => @render json: @resource, status: 200
_index: (callback) ->
@findCollection (error, collection) =>
@respondWith collection, callback
_new: (callback) ->
@buildResource (error, resource) =>
return @failure(error) unless resource
@respondWith(resource, callback)
_create: (callback) ->
@buildResource (error, resource) =>
return @failure(error, callback) unless resource
resource.save (error) =>
@respondWithStatus Tower.Support.Object.isBlank(resource.errors), callback
_show: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_edit: (callback) ->
@findResource (error, resource) =>
@respondWith resource, callback
_update: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.updateAttributes @params[@resourceName], (error) =>
@respondWithStatus !!!error && Tower.Support.Object.isBlank(resource.errors), callback
_destroy: (callback) ->
@findResource (error, resource) =>
return @failure(error, callback) if error
resource.destroy (error) =>
@respondWithStatus !!!error, callback
respondWithScoped: (callback) ->
@scoped (error, scope) =>
return @failure(error, callback) if error
@respondWith scope.build(), callback
respondWithStatus: (success, callback) ->
options = records: (@resource || @collection)
if callback && callback.length > 1
successResponder = new Tower.Controller.Responder(@, options)
failureResponder = new Tower.Controller.Responder(@, options)
callback.call @, successResponder, failureResponder
if success
successResponder[format].call @
else
failureResponder[format].call @, error
else
Tower.Controller.Responder.respond(@, options, callback)
buildResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
@[@resourceName] = @resource = resource = scope.build(@params[@resourceName])
callback.call @, null, resource if callback
resource
findResource: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.find @params.id, (error, resource) =>
@[@resourceName] = @resource = resource
callback.call @, error, resource
findCollection: (callback) ->
@scoped (error, scope) =>
return callback.call @, error, null if error
scope.all (error, collection) =>
@[@collectionName] = @collection = collection
callback.call @, error, collection if callback
findParent: (callback) ->
association = @constructor._belongsTo
if association
param = association.param || "#{association.key}Id"
parentClass = Tower.constant(association.type)
parentClass.find @params[param], (error, parent) =>
throw error if error && !callback
unless error
@parent = @[association.key] = parent
callback.call @, error, parent if callback
else
callback.call @, null, false if callback
false
scoped: (callback) ->
callbackWithScope = (error, scope) =>
callback.call @, error, scope.where(@criteria())
if @hasParent
@findParent (error, parent) =>
callbackWithScope(error, parent[@collectionName]())
else
callbackWithScope null, Tower.constant(@resourceType)
failure: (resource, callback) ->
callback()
class Tower.Controller.Responder
@respond: (controller, options, callback) ->
responder = new @(controller, options)
responder.respond callback
constructor: (controller, options = {}) ->
@controller = controller
@options = options
@accept(format) for format in @controller.formats
accept: (format) ->
@[format] = (callback) -> @["_#{format}"] = callback
respond: (callback) ->
callback.call @controller, @ if callback
method = @["_#{@controller.format}"]
if method then method.call(@) else @toFormat()
_html: ->
@controller.render action: @controller.action
_json: ->
@controller.render json: @options.records
toFormat: ->
try
if get? || !hasErrors?
@defaultRender()
else
@displayErrors()
catch error
@_apiBehavior(error)
_navigationBehavior: (error) ->
if get?
throw error
else if hasErrors? && defaultAction
@render action: @defaultAction
else
@redirectTo @navigationLocation
_apiBehavior: (error) ->
#throw error unless resourceful?
if get?
@display resource
else if post?
@display resource, status: "created", location: @apiLocation
else
@head "noContent"
isResourceful: ->
@resource.hasOwnProperty("to#{@format.toUpperCase()}")
resourceLocation: ->
@options.location || @resources
defaultRender: ->
@defaultResponse.call(options)
display: (resource, givenOptions = {}) ->
@controller.render _.extend givenOptions, @options, format: @resource
displayErrors: ->
@controller.render format: @resourceErrors, status: "unprocessableEntity"
hasErrors: ->
@resource.respondTo?("errors") && !@resource.errors.empty?
defaultAction: ->
@action ||= ACTIONS_FOR_VERBS[request.requestMethodSymbol]
resourceErrors: ->
if @hasOwnProperty("#{format}ResourceErrors") then @["#{format}RresourceErrors"] else @resource.errors
jsonResourceErrors: ->
errors: @resource.errors
Tower.Controller.Responding =
ClassMethods:
respondTo: ->
mimes = @mimes()
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
only = Tower.Support.Object.toArray(options.only) if options.only
except = Tower.Support.Object.toArray(options.except) if options.except
for name in args
mimes[name] = {}
mimes[name].only = only if only
mimes[name].except = except if except
@
mimes: ->
@_mimes ||= {json: {}, html: {}}
respondTo: (block) ->
Tower.Controller.Responder.respond(@, {}, block)
respondWith: ->
args = Tower.Support.Array.args(arguments)
callback = null
if typeof(args[args.length - 1]) == "function"
callback = args.pop()
if typeof(args[args.length - 1]) == "object" && !(args[args.length - 1] instanceof Tower.Model)
options = args.pop()
else
options = {}
options ||= {}
options.records = args[0]
Tower.Controller.Responder.respond(@, options, callback)
_mimesForAction: ->
action = @action
result = []
mimes = @constructor.mimes()
for mime, config of mimes
success = false
if config.except
success = !_.include(config.except, action)
else if config.only
success = _.include(config.only, action)
else
success = true
result.push mime if success
result
class Tower.HTTP.Agent
constructor: (attributes = {}) ->
_.extend @, attributes
toJSON: ->
family: @family
major: @major
minor: @minor
patch: @patch
version: @version
os: @os
name: @name
class Tower.HTTP.Cookies
@parse: (string = document.cookie) ->
result = {}
pairs = string.split(/[;,] */);
for pair in pairs
eqlIndex = pair.indexOf('=')
key = pair.substring(0, eqlIndex).trim().toLowerCase()
value = pair.substring(++eqlIndex, pair.length).trim()
# quoted values
value = value.slice(1, -1) if '"' == value[0]
# only assign once
if result[key] == undefined
value = value.replace(/\+/g, ' ')
try
result[key] = decodeURIComponent(value)
catch error
if error instanceof URIError
result[key] = value
else
throw err
new @(result)
constructor: (attributes = {}) ->
@[key] = value for key, value of attributes
class Tower.HTTP.Param
@perPage: 20
@sortDirection: "ASC"
@sortKey: "sort" # or "order", etc.
@limitKey: "limit" # or "perPage", etc.
@pageKey: "page"
@separator: "_" # or "-"
@create: (key, options) ->
options.type ||= "String"
new Tower.HTTP.Param[options.type](key, options)
constructor: (key, options = {}) ->
@controller = options.controller
@key = key
@attribute = options.as || @key
@modelName = options.modelName
@namespace = Tower.Support.String.pluralize(@modelName) if modelName?
@exact = options.exact || false
@default = options.default
parse: (value) -> value
render: (value) -> value
toCriteria: (value) ->
nodes = @parse(value)
criteria = new Tower.Model.Criteria
for set in nodes
for node in set
attribute = node.attribute
operator = node.operators[0]
conditions = {}
if operator == "$eq"
conditions[attribute] = node.value
else
conditions[attribute] = {}
conditions[attribute][operator] = node.value
criteria.where(conditions)
criteria
parseValue: (value, operators) ->
namespace: @namespace, key: @key, operators: operators, value: value, attribute: @attribute
_clean: (string) ->
string.replace(/^-/, "").replace(/^\+-/, "").replace(/^'|'$/, "").replace("+", " ").replace(/^\^/, "").replace(/\$$/, "").replace(/^\s+|\s+$/, "")
require './param/array'
require './param/date'
require './param/number'
require './param/string'
class Tower.HTTP.Request
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@method = data.method || "GET"
class Tower.HTTP.Response
constructor: (data = {}) ->
@url = data.url
@location = data.location
@pathname = @location.path
@query = @location.query
@title = data.title
@title ||= document?.title
@body = data.body || {}
@headers = data.headers || {}
@headerSent = false
@statusCode = 200
@body = ""
writeHead: (statusCode, headers) ->
@statusCode = statusCode
@headers = headers
setHeader: (key, value) ->
throw new Error("Headers already sent") if @headerSent
@headers[key] = value
write: (body = '') ->
@body += body
end: (body = '') ->
@body += body
@sent = true
@headerSent = true
redirect: (path, options = {}) ->
global.History.push options, null, path if global.History
class Tower.HTTP.Route extends Tower.Class
@store: ->
@_store ||= []
@create: (route) ->
@store().push(route)
@all: ->
@store()
@clear: ->
@_store = []
@draw: (callback) ->
callback.apply(new Tower.HTTP.Route.DSL(@))
@findController: (request, response, callback) ->
routes = Tower.Route.all()
for route in routes
controller = route.toController request
break if controller
if controller
controller.call request, response, ->
callback(controller)
else
callback(null)
controller
toController: (request) ->
match = @match(request)
return null unless match
method = request.method.toLowerCase()
keys = @keys
params = Tower.Support.Object.extend({}, @defaults, request.query || {}, request.body || {})
match = match[1..-1]
for capture, i in match
params[keys[i].name] ||= if capture then decodeURIComponent(capture) else null
controller = @controller
params.action = controller.action if controller
request.params = params
controller = new (Tower.constant(Tower.namespaced(@controller.className))) if controller
controller
constructor: (options) ->
options ||= options
@path = options.path
@name = options.name
@method = (options.method || "GET").toUpperCase()
@ip = options.ip
@defaults = options.defaults || {}
@constraints = options.constraints
@options = options
@controller = options.controller
@keys = []
@pattern = @extractPattern(@path)
@id = @path
if @controller
@id += @controller.name + @controller.action
match: (requestOrPath) ->
if typeof requestOrPath == "string" then return @pattern.exec(requestOrPath)
path = requestOrPath.location.path
return null unless requestOrPath.method.toUpperCase() == @method
match = @pattern.exec(path)
return null unless match
return null unless @matchConstraints(requestOrPath)
match
matchConstraints: (request) ->
constraints = @constraints
switch typeof(constraints)
when "object"
for key, value of constraints
switch typeof(value)
when "string", "number"
return false unless request[key] == value
when "function", "object"
# regexp?
return false unless !!request.location[key].match(value)
when "function"
return constraints.call(request, request)
else
return false
return true
urlFor: (options = {}) ->
result = @path
result = result.replace(new RegExp(":#{key}\\??", "g"), value) for key, value of options
result = result.replace(new RegExp("\\.?:\\w+\\??", "g"), "")
result
extractPattern: (path, caseSensitive, strict) ->
return path if path instanceof RegExp
self = @
return new RegExp('^' + path + '$') if path == "/"
path = path.replace(/(\(?)(\/)?(\.)?([:\*])(\w+)(\))?(\?)?/g, (_, open, slash, format, symbol, key, close, optional) ->
optional = (!!optional) || (open + close == "()")
splat = symbol == "*"
self.keys.push
name: key
optional: !!optional
splat: splat
slash ||= ""
result = ""
result += slash if !optional || !splat
result += "(?:"
# result += slash if optional
if format?
result += if splat then "\\.([^.]+?)" else "\\.([^/.]+?)"
else
result += if splat then "/?(.+)" else "([^/\\.]+)"
result += ")"
result += "?" if optional
result
)
new RegExp('^' + path + '$', if !!caseSensitive then '' else 'i')
Tower.Route = Tower.HTTP.Route
require './route/dsl'
require './route/urls'
require './route/polymorphicUrls'
Tower.HTTP.Route.include Tower.HTTP.Route.Urls
Tower.HTTP.Route.include Tower.HTTP.Route.PolymorphicUrls
Tower.HTTP.Sync =
ajax: ->
webSockets: ->
class Tower.HTTP.Url
@key: ["source", "protocol", "host", "userInfo", "user", "password", "hostname", "port", "relative", "path", "directory", "file", "query", "fragment"]
@aliases:
anchor: "fragment"
@parser:
strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/
loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
@querystringParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@fragmentParser: /(?:^|&|;)([^&=;]*)=?([^&;]*)/g
@typeParser: /(youtube|vimeo|eventbrite)/
parse: (string) ->
key = @constructor.key
string = decodeURI(string)
parsed = @constructor.parser[(if @strictMode or false then "strict" else "loose")].exec(string)
attributes = {}
@params = params = {}
@fragment = fragment = params: {}
i = 14
while i--
attributes[key[i]] = parsed[i] || ""
attributes["query"].replace @constructor.querystringParser, ($0, $1, $2) ->
params[$1] = $2 if $1
attributes["fragment"].replace @constructor.fragmentParser, ($0, $1, $2) ->
fragment.params[$1] = $2 if $1
@segments = attributes.path.replace(/^\/+|\/+$/g, "").split("/")
fragment.segments = attributes.fragment.replace(/^\/+|\/+$/g, "").split("/")
@[key] ||= value for key, value of attributes
@root = (if attributes.host then attributes.protocol + "://" + attributes.hostname + (if attributes.port then ":" + attributes.port else "") else "")
domains = @hostname.split(".")
@domain = domains[(domains.length - 1 - @depth)..(domains.length - 1)].join(".")
@subdomains = domains[0..(domains.length - 2 - @depth)]
@subdomain = @subdomains.join(".")
@port = parseInt(@port) if @port?
constructor: (url, depth = 1, strictMode) ->
@strictMode = strictMode or false
@depth = depth || 1
@url = url ||= window.location.toString() if window?
@parse(url)
class Tower.Model.Attribute
constructor: (owner, name, options = {}) ->
@owner = owner
@name = key = name
@type = options.type || "String"
if typeof @type != "string"
@type = "Array"
@_default = options.default
@_encode = options.encode
@_decode = options.decode
if Tower.accessors
Object.defineProperty @owner.prototype, name,
enumerable: true
configurable: true
get: -> @get(key)
set: (value) -> @set(key, value)
defaultValue: (record) ->
_default = @_default
if Tower.Support.Object.isArray(_default)
_default.concat()
else if Tower.Support.Object.isHash(_default)
Tower.Support.Object.extend({}, _default)
else if typeof(_default) == "function"
_default.call(record)
else
_default
encode: (value, binding) ->
@code @_encode, value, binding
decode: (value, binding) ->
@code @_decode, value, binding
code: (type, value, binding) ->
switch type
when "string"
binding[type].call binding[type], value
when "function"
type.call _encode, value
else
value
Tower.Model.Attributes =
ClassMethods:
field: (name, options) ->
@fields()[name] = new Tower.Model.Attribute(@, name, options)
fields: ->
@_fields ||= {}
get: (name) ->
unless @has(name)
field = @constructor.fields()[name]
@attributes[name] = field.defaultValue(@) if field
@attributes[name]
# post.set $pushAll: tags: ["ruby"]
# post.set $pushAll: tags: ["javascript"]
# post.attributes["tags"] #=> ["ruby", "javascript"]
# post.changes["tags"] #=> [[], ["ruby", "javascript"]]
# post.set $pop: tags: "ruby"
# post.attributes["tags"] #=> ["javascript"]
# post.changes["tags"] #=> [[], ["javascript"]]
# if the changes looked like this:
# post.changes["tags"] #=> [["ruby", "javascript"], ["javascript", "node.js"]]
# then the updates would be
# post.toUpdates() #=> {$popAll: {tags: ["ruby"]}, $pushAll: {tags: ["node.js"]}}
# popAll = _.difference(post.changes["tags"][0], post.changes["tags"][1])
# pushAll = _.difference(post.changes["tags"][1], post.changes["tags"][0])
set: (key, value) ->
if typeof key == "object"
updates = key
else
updates = {}
updates[key] = value
@_set(key, value) for key, value of updates
_set: (key, value) ->
@_attributeChange(key, value)
@attributes[key] = value
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
has: (key) ->
@attributes.hasOwnProperty(key)
Tower.Model.Conversion =
ClassMethods:
baseClass: ->
if @__super__ && @__super__.constructor.baseClass && @__super__.constructor != Tower.Model
@__super__.constructor.baseClass()
else
@
toParam: ->
return undefined if @ == Tower.Model
@metadata().paramNamePlural
toKey: ->
@metadata().paramName
# @url "/posts/:postId/comment"
# @url parent: "post"
# @url (model) -> return "/something"
url: (options) ->
@_url = switch typeof options
when "object"
if options.parent
url = "/#{Tower.Support.String.parameterize(Tower.Support.String.pluralize(options.parent))}/:#{Tower.Support.String.camelize(options.parent, true)}/#{@toParam()}"
else
options
collectionName: ->
Tower.Support.String.camelize(Tower.Support.String.pluralize(@name), true)
resourceName: ->
Tower.Support.String.camelize(@name, true)
# inheritance_column
metadata: ->
className = @name
metadata = @metadata[className]
return metadata if metadata
namespace = Tower.namespace()
name = Tower.Support.String.camelize(className, true)
namePlural = Tower.Support.String.pluralize(name)
classNamePlural = Tower.Support.String.pluralize(className)
paramName = Tower.Support.String.parameterize(name)
paramNamePlural = Tower.Support.String.parameterize(namePlural)
modelName = "#{namespace}.#{className}"
controllerName = "#{namespace}.#{classNamePlural}Controller"
@metadata[className] =
name: name
namePlural: namePlural
className: className
classNamePlural: classNamePlural
paramName: paramName
paramNamePlural: paramNamePlural
modelName: modelName
controllerName: controllerName
toLabel: ->
@className()
toPath: ->
result = @constructor.toParam()
return "/" if result == undefined
param = @toParam()
result += "/#{param}" if param
result
toParam: ->
id = @get("id")
if id? then String(id) else null
toKey: ->
@constructor.tokey()
toCacheKey: ->
toModel: ->
@
metadata: ->
@constructor.metadata()
class Tower.Model.Criteria
constructor: (args = {}) ->
@[key] = value for key, value of args
@_where ||= []
@_order ||= []
where: (conditions) ->
if conditions instanceof Tower.Model.Criteria
@merge(conditions)
else
@_where.push(conditions)
order: (attribute, direction = "asc") ->
@_order ||= []
@_order.push [attribute, direction]
#@mergeOptions sort: [[attribute, direction]]
asc: (attributes...) ->
@order(attribute) for attribute in attributes
desc: (attributes...) ->
@order(attribute, "desc") for attribute in attributes
allIn: (attributes) ->
@_whereOperator "$all", attributes
anyIn: (attributes) ->
@_whereOperator "$any", attributes
notIn: (attributes) ->
@_whereOperator "$nin", attributes
offset: (number) ->
@_offset = number
#@mergeOptions offset: number
limit: (number) ->
@_limit = number
@mergeOptions limit: number
select: ->
@_fields = Tower.Support.Array.args(arguments)
includes: ->
@_includes = Tower.Support.Array.args(arguments)
page: (number) ->
@offset(number)
paginate: (options) ->
limit = options.perPage || options.limit
page = options.page || 1
@limit(limit)
@offset((page - 1) * limit)
clone: ->
new @constructor(@attributes())
merge: (criteria) ->
attributes = criteria.attributes()
@_where = @_where.concat attributes._where if attributes._where.length > 0
@_order = @_order.concat attributes._order if attributes._order.length > 0
@_offset = attributes._offset if attributes._offset?
@_limit = attributes._limit if attributes._limit?
@_fields = attributes._fields if attributes._fields
@_offset = attributes._offset if attributes._offset?
@
options: ->
options = {}
options.offset = @_offset if @_offset?
options.limit = @_limit if @_limit?
options.fields = @_fields if @_fields
options.sort = @_order if @_order.length > 0
options
conditions: ->
result = {}
for conditions in @_where
Tower.Support.Object.deepMergeWithArrays(result, conditions)
result
attributes: (to = {}) ->
to._where = @_where.concat()
to._order = @_order.concat()
to._offset = @_offset if @_offset?
to._limit = @_limit if @_limit?
to._fields = @_fields if @_fields
to._includes = @_includes if @_includes
to
toQuery: ->
conditions: @conditions(), options: @options()
toUpdate: ->
@toQuery()
toCreate: ->
attributes = {}
options = {}
for conditions in @_where
# tags: $in: ["a", "b"]
# $push: tags: ["c"]
for key, value of conditions
if Tower.Store.isKeyword(key)
for _key, _value of value
attributes[_key] = _value
else if Tower.Support.Object.isHash(value) && Tower.Store.hasKeyword(value)
for _key, _value of value
attributes[key] = _value
else
attributes[key] = value
for key, value of attributes
delete attributes[key] if value == undefined
attributes: attributes, options: options
mergeOptions: (options) ->
options
_whereOperator: (operator, attributes) ->
query = {}
for key, value of attributes
query[key] = {}
query[key][operator] = value
@where query
Tower.Model.Dirty =
isDirty: ->
Tower.Support.Object.isPresent(@changes)
attributeChanged: (name) ->
change = @changes[name]
return false unless change
change[0] != change[1]
attributeChange: (name) ->
change = @changes[name]
return undefined unless change
change[1]
attributeWas: (name) ->
change = @changes[name]
return undefined unless change
change[0]
resetAttribute: (name) ->
array = @changes[name]
@set(name, array[0]) if array
@
toUpdates: ->
result = {}
attributes = @attributes
for key, array of @changes
result[key] = attributes[key]
result.updatedAt ||= new Date
result
_attributeChange: (attribute, value) ->
array = @changes[attribute] ||= []
beforeValue = array[0] ||= @attributes[attribute]
array[1] = value
array = null if array[0] == array[1]
if array then @changes[attribute] = array else delete @changes[attribute]
beforeValue
# @todo
# copied this from acts_as_nested_set, haven't messed with it yet.
Tower.Model.Hierarchical =
ClassMethods:
hierarchical: ->
@field "lft", type: "Integer"
@field "rgt", type: "Integer"
@field "parentId", type: "Integer"
root: (callback) ->
@roots.first(callback)
roots: ->
@where(parentColumnName: null).order(@quotedLeftColumnName())
leaves: ->
@where("#{@quotedRightColumnName()} - #{@quotedLeftColumnName()} = 1").order(@quotedLeftColumnName())
isRoot: ->
!!!@get("parentId")
root: (callback) ->
@selfAndAncestors.where(parentColumnName: null).first(callback)
selfAndAncestors: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} <= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} >= ?", left, right
])
ancestors: ->
@withoutSelf @selfAndAncestors
selfAndSiblings: ->
@nestedSetScope().where(parentColumnName: parentId)
siblings: ->
@withoutSelf @selfAndSiblings()
leaves: ->
@descendants().where("#{self.class.quotedTableName}.#{quotedRightColumnName} - #{self.class.quotedTableName}.#{quotedLeftColumnName} = 1")
level: (callback) ->
if get('parentId') == null then 0 else ancestors().count(callback)
selfAndDescendants: ->
@nestedSetScope().where([
"#{self.class.quotedTableName}.#{quotedLeftColumnName} >= ? AND #{self.class.quotedTableName}.#{quotedRightColumnName} <= ?", left, right
])
descendants: ->
@withoutSelf @selfAndDescendants()
isDescendantOf: (other) ->
other.left < self.left && self.left < other.right && sameScope?(other)
moveLeft: ->
@moveToLeftOf @leftSibling()
moveRight: ->
@moveToRightOf @rightSibling()
moveToLeftOf: (node) ->
@moveTo node, "left"
moveToRightOf: (node) ->
@moveTo node, "right"
moveToChildOf: (node) ->
@moveTo node, "child"
moveToRoot: ->
@moveTo null, "root"
moveTo: (target, position) ->
@runCallbacks "move", ->
isOrIsDescendantOf: (other) ->
other.left <= self.left && self.left < other.right && sameScope?(other)
isAncestorOf: (other) ->
self.left < other.left && other.left < self.right && sameScope?(other)
isOrIsAncestorOf: (other) ->
self.left <= other.left && other.left < self.right && sameScope?(other)
sameScope: (other) ->
Array(actsAsNestedSetOptions.scope).all (attr) ->
self.send(attr) == other.send(attr)
leftSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} < ?", left]).
order("#{self.class.quotedTableName}.#{quotedLeftColumnName} DESC").last
rightSibling: ->
siblings.where(["#{self.class.quotedTableName}.#{quotedLeftColumnName} > ?", left]).first
Tower.Model.Inheritance =
_computeType: ->
Tower.Model.Persistence =
ClassMethods:
defaultStore: if Tower.client then Tower.Store.Memory else Tower.Store.MongoDB
store: (value) ->
return @_store if !value && @_store
if typeof value == "function"
@_store = new value(name: @collectionName(), type: Tower.namespaced(@name))
else if typeof value == "object"
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
Tower.Support.Object.extend @_store, value
else if value
@_store = value
@_store ||= new @defaultStore(name: @collectionName(), type: Tower.namespaced(@name))
@_store
load: (records) ->
@store().load(records)
InstanceMethods:
# Create or update the record.
#
# @example Default save
# user.save -> console.log "saved"
#
# @example Save without validating
# user.save validate: false, -> console.log "saved"
save: (options, callback) ->
throw new Error("Record is read only") if @readOnly
if typeof options == "function"
callback = options
options = {}
options ||= {}
unless options.validate == false
@validate (error) =>
if error
callback.call @, null, false if callback
else
@_save callback
else
@_save callback
@
updateAttributes: (attributes, callback) ->
@set(attributes)
@_update(attributes, callback)
destroy: (callback) ->
if @isNew()
callback.call @, null if callback
else
@_destroy callback
@
delete: (callback) ->
@destroy(callback)
isPersisted: ->
!!(@persistent)# && @attributes.hasOwnProperty("id") && @attributes.id != null && @attributes.id != undefined)
isNew: ->
!!!@isPersisted()
reload: ->
store: ->
@constructor.store()
_save: (callback) ->
@runCallbacks "save", (block) =>
complete = @_callback(block, callback)
if @isNew()
@_create(complete)
else
@_update(@toUpdates(), complete)
_create: (callback) ->
@runCallbacks "create", (block) =>
complete = @_callback(block, callback)
@constructor.create @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_update: (updates, callback) ->
@runCallbacks "update", (block) =>
complete = @_callback(block, callback)
@constructor.update @get("id"), updates, instantiate: false, (error) =>
throw error if error && !callback
unless error
@changes = {}
@persistent = true
complete.call(@, error)
@
_destroy: (callback) ->
@runCallbacks "destroy", (block) =>
complete = @_callback(block, callback)
@constructor.destroy @, instantiate: false, (error) =>
throw error if error && !callback
unless error
@persistent = false
@changes = {}
delete @attributes.id
complete.call(@, error)
@
# @todo
# https://github.com/technoweenie/coffee-resque
Tower.Model.Queue =
ClassMethods:
enqueue: ->
class Tower.Model.Relation extends Tower.Class
# hasMany "commenters", source: "person", sourceType: "User", foreignKey: "userId", type
constructor: (owner, name, options = {}, callback) ->
@[key] = value for key, value of options
@owner = owner
@name = name
@type = Tower.namespaced(options.type || Tower.Support.String.camelize(Tower.Support.String.singularize(name)))
@ownerType = Tower.namespaced(owner.name)
@dependent ||= false
@counterCache ||= false
@cache = false unless @hasOwnProperty("cache")
@readOnly = false unless @hasOwnProperty("readOnly")
@validate = false unless @hasOwnProperty("validate")
@autoSave = false unless @hasOwnProperty("autoSave")
@touch = false unless @hasOwnProperty("touch")
@inverseOf ||= undefined
@polymorphic = options.hasOwnProperty("as") || !!options.polymorphic
@default = false unless @hasOwnProperty("default")
@singularName = Tower.Support.String.camelize(owner.name, true)
@pluralName = Tower.Support.String.pluralize(owner.name) # collectionName?
@singularTargetName = Tower.Support.String.singularize(name)
@pluralTargetName = Tower.Support.String.pluralize(name)
@targetType = @type
# hasMany "posts", foreignKey: "postId", cacheKey: "postIds"
unless @foreignKey
if @as
@foreignKey = "#{@as}Id"
else
@foreignKey = "#{@singularName}Id"
@foreignType ||= "#{@as}Type" if @polymorphic
if @cache
if typeof @cache == "string"
@cacheKey = @cache
@cache = true
else
@cacheKey = @singularTargetName + "Ids"
@owner.field @cacheKey, type: "Array", default: []
if @counterCache
if typeof @counterCache == "string"
@counterCacheKey = @counterCache
@counterCache = true
else
@counterCacheKey = "#{@singularTargetName}Count"
@owner.field @counterCacheKey, type: "Integer", default: 0
@owner.prototype[name] = ->
@relation(name)
scoped: (record) ->
new @constructor.Scope(model: @klass(), owner: record, relation: @)
targetKlass: ->
Tower.constant(@targetType)
klass: ->
Tower.constant(@type)
inverse: ->
return @_inverse if @_inverse
relations = @targetKlass().relations()
for name, relation of relations
# need a way to check if class extends another class in coffeescript...
return relation if relation.inverseOf == @name
return relation if relation.targetType == @ownerType
null
class @Scope extends Tower.Model.Scope
isConstructable: ->
!!!@relation.polymorphic
constructor: (options = {}) ->
super(options)
@owner = options.owner
@relation = options.relation
clone: ->
new @constructor(model: @model, criteria: @criteria.clone(), owner: @owner, relation: @relation)
setInverseInstance: (record) ->
if record && @invertibleFor(record)
inverse = record.relation(@inverseReflectionFor(record).name)
inverse.target = owner
invertibleFor: (record) ->
true
inverse: (record) ->
require './relation/belongsTo'
require './relation/hasMany'
require './relation/hasOne'
Tower.Model.Relations =
ClassMethods:
# One-to-one association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasOne "address"
#
# class App.Address extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# address = user.createAddress()
#
# @example Example using all the `hasOne` options
# class App.User extends Tower.Model
# @hasOne "location", type: "Address", embed: true, as: "addressable"
#
# class App.Address extends Tower.Model
# @belongsTo "addressable", polymorphic: true
hasOne: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasOne(@, name, options)
# One-to-many association, where the id is stored on the associated object.
#
# @example Basic example
# class App.User extends Tower.Model
# @hasMany "comments"
#
# class App.Comment extends Tower.Model
# @belongsTo "user"
#
# user = App.User.create()
# comment = user.comments().create()
#
# @example Example using all the `hasMany` options
# class App.User extends Tower.Model
# @hasMany "comments", as: "commentable", embed: true
#
# class App.Comment extends Tower.Model
# @belongsTo "commentable", polymorphic: true
#
# @param [String] name Name of the association
# @param [Object] options Association options
# @option options [String] as Polymorphic key, if the associated object's relationship is polymorphic
# @option options [Boolean] embed If true, the data store will try to embed the data in the record (MongoDB currently)
hasMany: (name, options = {}) ->
@relations()[name] = new Tower.Model.Relation.HasMany(@, name, options)
belongsTo: (name, options) ->
@relations()[name] = new Tower.Model.Relation.BelongsTo(@, name, options)
relations: ->
@_relations ||= {}
relation: (name) ->
relation = @relations()[name]
throw new Error("Relation '#{name}' does not exist on '#{@name}'") unless relation
relation
relation: (name) ->
@constructor.relation(name).scoped(@)
buildRelation: (name, attributes, callback) ->
@relation(name).build(attributes, callback)
createRelation: (name, attributes, callback) ->
@relation(name).create(attributes, callback)
destroyRelations: ->
class Tower.Model.Scope extends Tower.Class
constructor: (options = {}) ->
@model = options.model
@criteria = options.criteria || new Tower.Model.Criteria
@store = @model.store()
toQuery: (sortDirection) ->
@toCriteria(sortDirection).toQuery()
toCriteria: (sortDirection) ->
criteria = @criteria.clone()
if sortDirection || !criteria._order.length > 0
sort = @model.defaultSort()
criteria[sortDirection || sort.direction](sort.name) if sort
criteria
toCreate: ->
@toQuery()
toUpdate: ->
@toQuery()
toDestroy: ->
merge: (scope) ->
@criteria.merge(scope.criteria)
clone: ->
new @constructor(model: @model, criteria: @criteria.clone())
_extractArgs: (args, opts = {}) ->
args = Tower.Support.Array.args(args)
callback = Tower.Support.Array.extractBlock(args)
last = args[args.length - 1]
if opts.data && (Tower.Support.Object.isHash(last) || Tower.Support.Object.isArray(last))
data = args.pop()
if Tower.Support.Object.isHash(args[args.length - 1])
if data
options = data
data = args.pop()
else
if Tower.Support.Object.isBaseObject(args[args.length - 1])
options = args.pop()
data = {} unless opts.data
data ||= {}
criteria = @criteria.clone()
options ||= {}
options.instantiate = true unless options.hasOwnProperty("instantiate")
ids = _.flatten(args) if opts.ids && args.length > 0
if ids && ids.length > 0
ids = _.map(ids, (idOrRecord) -> if idOrRecord instanceof Tower.Model then idOrRecord.get("id") else idOrRecord)
criteria.where id: $in: ids
criteria: criteria, data: data, callback: callback, options: options
require './scope/finders'
require './scope/persistence'
require './scope/queries'
Tower.Model.Scope.include Tower.Model.Scope.Finders
Tower.Model.Scope.include Tower.Model.Scope.Persistence
Tower.Model.Scope.include Tower.Model.Scope.Queries
for key in Tower.Model.Scope.queryMethods
do (key) =>
Tower.Model.Scope::[key] = ->
clone = @clone()
clone.criteria[key](arguments...)
clone
Tower.Model.Scopes =
ClassMethods:
scope: (name, scope) ->
@[name] = if scope instanceof Tower.Model.Scope then scope else @where(scope)
scoped: ->
scope = new Tower.Model.Scope(model: @)
scope.where(type: @name) if @baseClass().name != @name
scope
defaultSort: (object) ->
@_defaultSort = object if object
@_defaultSort ||= {name: "createdAt", direction: "desc"}
for key in Tower.Model.Scope.queryMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.finderMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
for key in Tower.Model.Scope.persistenceMethods
do (key) ->
Tower.Model.Scopes.ClassMethods[key] = ->
@scoped()[key](arguments...)
Tower.Model.Serialization =
ClassMethods:
fromJSON: (data) ->
records = JSON.parse(data)
records = [records] unless records instanceof Array
for record, i in records
records[i] = new @(record)
records
toJSON: (records, options = {}) ->
result = []
result.push(record.toJSON()) for record in records
result
toJSON: (options) ->
@_serializableHash(options)
clone: ->
new @constructor(Tower.Support.Object.clone(@attributes))
_serializableHash: (options = {}) ->
result = {}
attributeNames = Tower.Support.Object.keys(@attributes)
if only = options.only
attributeNames = _.union(Tower.Support.Object.toArray(only), attributeNames)
else if except = options.except
attributeNames = _.difference(Tower.Support.Object.toArray(except), attributeNames)
for name in attributeNames
result[name] = @_readAttributeForSerialization(name)
if methods = options.methods
methodNames = Tower.Support.Object.toArray(methods)
for name in methods
result[name] = @[name]()
# TODO: async!
if includes = options.include
includes = Tower.Support.Object.toArray(includes)
for include in includes
unless Tower.Support.Object.isHash(include)
tmp = {}
tmp[include] = {}
include = tmp
tmp = undefined
for name, opts of include
records = @[name]().all()
for record, i in records
records[i] = record._serializableHash(opts)
result[name] = records
result
_readAttributeForSerialization: (name, type = "json") ->
@attributes[name]
Tower.Model.Sync =
sync: ->
syncAction = @syncAction
@runCallbacks "sync", =>
@runCallbacks "#{syncAction}Sync", =>
@store["#{syncAction}Sync"](@)
updateSyncAction: (action) ->
@syncAction = switch action # create, update, delete
# if it was create, and it's never been synced, then we can just remove it from memory and be all cool
when "delete" then "delete"
when "update"
switch @syncAction
when "create" then "create"
else
"update"
else
switch @syncAction
when "update" then "delete"
else
action
Tower.Model.Timestamp =
ClassMethods:
timestamps: ->
@include Tower.Model.Timestamp.CreatedAt
@include Tower.Model.Timestamp.UpdatedAt
@field "createdAt", type: "Date"
@field "updatedAt", type: "Date"
@before "create", "setCreatedAt"
@before "save", "setUpdatedAt"
CreatedAt:
ClassMethods: {}
setCreatedAt: ->
@set "createdAt", new Date
UpdatedAt:
ClassMethods: {}
setUpdatedAt: ->
@set "updatedAt", new Date
Tower.Model.Validations =
ClassMethods:
validates: ->
attributes = Tower.Support.Array.args(arguments)
options = attributes.pop()
validators = @validators()
for key, value of options
validators.push Tower.Model.Validator.create(key, value, attributes)
validators: ->
@_validators ||= []
validate: (callback) ->
success = false
@runCallbacks "validate", (block) =>
complete = @_callback(block, callback)
validators = @constructor.validators()
errors = @errors = {}
iterator = (validator, next) =>
validator.validateEach @, errors, next
Tower.async validators, iterator, (error) =>
success = true unless error || Tower.Support.Object.isPresent(errors)
complete.call(@, !success)
success
success
class Tower.Model.Validator
@create: (name, value, attributes) ->
switch name
when "presence"
new @Presence(name, value, attributes)
when "count", "length", "min", "max"
new @Length(name, value, attributes)
when "format"
new @Format(name, value, attributes)
constructor: (name, value, attributes) ->
@name = name
@value = value
@attributes = attributes
validateEach: (record, errors, callback) ->
iterator = (attribute, next) =>
@validate record, attribute, errors, (error) =>
next()
Tower.async @attributes, iterator, (error) =>
callback.call(@, error) if callback
success: (callback) ->
callback.call @ if callback
true
failure: (record, attribute, errors, message, callback) ->
errors[attribute] ||= []
errors[attribute].push message
callback.call @, message if callback
false
require './validator/format'
require './validator/length'
require './validator/presence'
require './validator/uniqueness'
require './controller/caching'
require './controller/events'
require './controller/http'
require './controller/sockets'
Tower.Controller.include Tower.Controller.Caching
Tower.Controller.include Tower.Controller.Events
Tower.Controller.include Tower.Controller.HTTP
Tower.Controller.include Tower.Controller.Sockets
require './controller/renderers'
class Tower.Mailer extends Tower.Class
require './mailer/configuration'
require './mailer/rendering'
Tower.Mailer.include Tower.Mailer.Configuration
Tower.Mailer.include Tower.Mailer.Rendering
Tower.Support.Array =
extractOptions: (args) ->
if typeof args[args.length - 1] == "object" then args.pop() else {}
extractBlock: (args) ->
if typeof args[args.length - 1] == "function" then args.pop() else null
args: (args, index = 0, withCallback = false, withOptions = false) ->
args = Array.prototype.slice.call(args, index, args.length)
if withCallback && !(args.length >= 2 && typeof(args[args.length - 1]) == "function")
throw new Error("You must pass a callback to the render method")
args
# Sort objects by one or more attributes.
#
# cityPrimer = (string) ->
# string.toLowerCase()
# sortObjects deals, ["city", ["price", "desc"]], city: cityPrimer
#
sortBy: (objects) ->
sortings = @args(arguments, 1)
callbacks = if sortings[sortings.length - 1] instanceof Array then {} else sortings.pop()
valueComparator = (x, y) ->
if x > y then 1 else (if x < y then -1 else 0)
arrayComparator = (a, b) ->
x = []
y = []
sortings.forEach (sorting) ->
attribute = sorting[0]
direction = sorting[1]
aValue = a[attribute]
bValue = b[attribute]
unless typeof callbacks[attribute] is "undefined"
aValue = callbacks[attribute](aValue)
bValue = callbacks[attribute](bValue)
x.push(direction * valueComparator(aValue, bValue))
y.push(direction * valueComparator(bValue, aValue))
if x < y then -1 else 1
sortings = sortings.map (sorting) ->
sorting = [sorting, "asc"] unless sorting instanceof Array
if sorting[1] == "desc"
sorting[1] = -1
else
sorting[1] = 1
sorting
objects.sort (a, b) ->
arrayComparator a, b
Tower.Support.Callbacks =
ClassMethods:
before: ->
@appendCallback "before", arguments...
# @example
# class App.User extends Tower.Model
# @before "save", "beforeSave"
#
# beforeSave: (callback) ->
# # before
# callback.call @
# # after
after: ->
@appendCallback "after", arguments...
callback: ->
args = Tower.Support.Array.args(arguments)
args = ["after"].concat args unless args[0].match(/^(?:before|around|after)$/)
@appendCallback args...
removeCallback: (action, phase, run) ->
@
appendCallback: (phase) ->
args = Tower.Support.Array.args(arguments, 1)
if typeof args[args.length - 1] != "object"
method = args.pop()
if typeof args[args.length - 1] == "object"
options = args.pop()
method ||= args.pop()
options ||= {}
callbacks = @callbacks()
for filter in args
callback = callbacks[filter] ||= new Tower.Support.Callbacks.Chain
callback.push phase, method, options
@
prependCallback: (action, phase, run, options = {}) ->
@
callbacks: ->
@_callbacks ||= {}
runCallbacks: (kind, options, block, complete) ->
if typeof options == "function"
complete = block
block = options
options = {}
options ||= {}
chain = @constructor.callbacks()[kind]
if chain
chain.run(@, options, block, complete)
else
block.call @
complete.call @ if complete
_callback: (callbacks...) ->
(error) =>
for callback in callbacks
callback.call(@, error) if callback
class Tower.Support.Callbacks.Chain
constructor: (options = {}) ->
@[key] = value for key, value of options
@before ||= []
@after ||= []
run: (binding, options, block, complete) ->
runner = (callback, next) =>
callback.run(binding, options, next)
Tower.async @before, runner, (error) =>
unless error
if block
switch block.length
when 0
block.call(binding)
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
block.call binding, (error) =>
unless error
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
else
Tower.async @after, runner, (error) =>
complete.call binding if complete
binding
push: (phase, method, filters, options) ->
@[phase].push new Tower.Support.Callback(method, filters, options)
class Tower.Support.Callback
constructor: (method, conditions = {}) ->
@method = method
@conditions = conditions
conditions.only = Tower.Support.Object.toArray(conditions.only) if conditions.hasOwnProperty("only")
conditions.except = Tower.Support.Object.toArray(conditions.except) if conditions.hasOwnProperty("except")
run: (binding, options, next) ->
conditions = @conditions
if options && options.hasOwnProperty("name")
if conditions.hasOwnProperty("only")
return next() if _.indexOf(conditions.only, options.name) == -1
else if conditions.hasOwnProperty("except")
return next() if _.indexOf(conditions.except, options.name) != -1
method = @method
method = binding[method] if typeof method == "string"
switch method.length
when 0
result = method.call binding
next(if !result then new Error("Callback did not pass") else null)
else
method.call binding, next
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
class Tower.Class
@global: (value) ->
@_global = value unless value == undefined
@_global = true if @_global == undefined
if value == true
global[@name] = @
else if value == false
delete global[@name]
@_global
@alias: (to, from) ->
Tower.Support.Object.alias(@::, to, from)
@accessor: (key, callback) ->
Tower.Support.Object.accessor(@::, key, callback)
@
@getter: (key, callback) ->
Tower.Support.Object.getter(@::, key, callback)
@
@setter: (key) ->
Tower.Support.Object.setter(@::, key)
@
@classAlias: (to, from) ->
Tower.Support.Object.alias(@, to, from)
@
@classAccessor: (key, callback) ->
Tower.Support.Object.accessor(@, key, callback)
@
@classGetter: (key, callback) ->
Tower.Support.Object.getter(@, key, callback)
@
@classSetter: (key) ->
Tower.Support.Object.setter(@, key)
@
@classEval: (block) ->
block.call(@)
@delegate: (key, options = {}) ->
Tower.Support.Object.delegate(@::, key, options)
@
@mixin: (self, object) ->
for key, value of object when key not in specialProperties
self[key] = value
object
@extend: (object) ->
@mixin(@, object)
extended = object.extended
extended.apply(object) if extended
object
@self: (object) ->
@extend object
@include: (object) ->
@extend(object.ClassMethods) if object.hasOwnProperty("ClassMethods")
@include(object.InstanceMethods) if object.hasOwnProperty("InstanceMethods")
@mixin(@::, object)
included = object.included
included.apply(object) if included
object
@className: ->
Tower.Support.Object.functionName(@)
className: ->
@constructor.className()
constructor: ->
@initialize()
initialize: ->
Tower.Support.EventEmitter =
#included: ->
# @events = {}
isEventEmitter: true
events: ->
@_events ||= {}
hasEventListener: (key) ->
Tower.Support.Object.isPresent(@events(), key)
event: (key) ->
@events()[key] ||= new Tower.Event(@, key)
# Examples:
#
# @on "click .item a", "clickItem"
# @on "click", "clickItem", target: ".item a"
#
# Use jQuery to set relavant parent/child elements using jQuery `find`, `parents`, `closest`, etc.
#
# @on "click", "clickItem", selector: ".item a", find: {meta: "span small"}, closest: {title: ".item h1"}
# #=> @titleElement = @targetElement.closest(".item h1")
on: ->
args = Tower.Support.Array.args(arguments)
if typeof args[args.length - 1] == "object"
options = args.pop()
if args.length == 0
eventMap = options
options = {}
else
options = {}
if typeof args[args.length - 1] == "object"
eventMap = args.pop()
else
eventMap = {}
eventMap[args.shift()] = args.shift()
# this is essentially what I'm doing above
#switch args.length
# # @on click: "clickHandler", keypress: "keypressHandler"
# when 1
# # @on "click", "clickHandler"
# # @on "click", -> alert '!'
# # @on {click: "clickHandler", keypress: "keypressHandler"}, {type: "socket"}
# when 2
# # @on "click", "clickHandler", type: "socket"
# when 3
for eventType, handler of eventMap
@addEventHandler(eventType, handler, options)
addEventHandler: (type, handler, options) ->
@event(type).addHandler(handler)
mutation: (wrappedFunction) ->
->
result = wrappedFunction.apply(this, arguments)
@event('change').fire(this, this)
result
prevent: (key) ->
@event(key).prevent()
@
allow: (key) ->
@event(key).allow()
@
isPrevented: (key) ->
@event(key).isPrevented()
fire: (key) ->
event = @event(key)
event.fire.call event, Tower.Support.Array.args(arguments, 1)
allowAndFire: (key) ->
@event(key).allowAndFire(Tower.Support.Array.args(arguments, 1))
Tower.Support.I18n =
PATTERN: /(?:%%|%\{(\w+)\}|%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps]))/g
defaultLanguage: "en"
load: (pathOrObject, language = @defaultLanguage) ->
store = @store()
language = store[language] ||= {}
Tower.Support.Object.deepMerge(language, if typeof(pathOrObject) == "string" then require(pathOrObject) else pathOrObject)
@
translate: (key, options = {}) ->
if options.hasOwnProperty("tense")
key += ".PI:KEY:<KEY>END_PIoptions.tense}"
if options.hasOwnProperty("count")
switch options.count
when 0 then key += ".none"
when 1 then key += ".one"
else key += ".other"
@interpolate(@lookup(key, options.language), options)
localize: ->
@translate arguments...
lookup: (key, language = @defaultLanguage) ->
parts = key.split(".")
result = @store()[language]
try
for part in parts
result = result[part]
catch error
result = null
throw new Error("Translation doesn't exist for '#{key}'") unless result?
result
store: ->
@_store ||= {}
# https://github.com/svenfuchs/i18n/blob/master/lib/i18n/interpolate/ruby.rb
interpolate: (string, locals = {}) ->
string.replace @PATTERN, (match, $1, $2, $3) ->
if match == '%%'
'%'
else
key = $1 || $2
if locals.hasOwnProperty(key)
value = locals[key]
else
throw new Error("Missing interpolation argument #{key}")
value = value.call(locals) if typeof value == 'function'
if $3 then sprintf("%#{$3}", value) else value
Tower.Support.I18n.t = Tower.Support.I18n.translate
Tower.Support.Number =
isInt: (n) ->
n == +n && n == (n|0)
isFloat: (n) ->
n == +n && n != (n|0)
specialProperties = ['included', 'extended', 'prototype', 'ClassMethods', 'InstanceMethods']
Tower.Support.Object =
extend: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
object[key] = value
object
cloneHash: (options) ->
result = {}
for key, value of options
if @isArray(value)
result[key] = @cloneArray(value)
else if @isHash(value)
result[key] = @cloneHash(value)
else
result[key] = value
result
cloneArray: (value) ->
result = value.concat()
for item, i in result
if @isArray(item)
result[i] = @cloneArray(item)
else if @isHash(item)
result[i] = @cloneHash(item)
result
deepMerge: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
if object[key] && typeof value == 'object'
object[key] = Tower.Support.Object.deepMerge(object[key], value)
else
object[key] = value
object
deepMergeWithArrays: (object) ->
args = Tower.Support.Array.args(arguments, 1)
for node in args
for key, value of node when key not in specialProperties
oldValue = object[key]
if oldValue
if @isArray(oldValue)
object[key] = oldValue.concat value
else if typeof oldValue == "object" && typeof value == "object"
object[key] = Tower.Support.Object.deepMergeWithArrays(object[key], value)
else
object[key] = value
else
object[key] = value
object
defineProperty: (object, key, options = {}) ->
Object.defineProperty object, key, options
functionName: (fn) ->
return fn.__name__ if fn.__name__
return fn.name if fn.name
fn.toString().match(/\W*function\s+([\w\$]+)\(/)?[1]
alias: (object, to, from) ->
object[to] = object[from]
accessor: (object, key, callback) ->
object._accessors ||= []
object._accessors.push(key)
@getter(key, object, callback)
@setter(key, object)
@
setter: (object, key) ->
unless object.hasOwnProperty("_setAttribute")
@defineProperty object, "_setAttribute",
enumerable: false,
configurable: true,
value: (key, value) ->
@["_#{key}"] = value
object._setters ||= []
object._setters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
set: (value) ->
@["_setAttribute"](key, value)
@
getter: (object, key, callback) ->
unless object.hasOwnProperty("_getAttribute")
@defineProperty object, "_getAttribute",
enumerable: false,
configurable: true,
value: (key) ->
@["_#{key}"]
object._getters ||= []
object._getters.push(key)
@defineProperty object, key,
enumerable: true,
configurable: true,
get: ->
@["_getAttribute"](key) || (@["_#{key}"] = callback.apply(@) if callback)
@
variables: (object) ->
accessors: (object) ->
methods: (object) ->
result = []
for key, value of object
result.push(key) if @isFunction(value)
result
delegate: (object, keys..., options = {}) ->
to = options.to
isFunction = @isFunction(object)
for key in keys
if isFunction
object[key] = ->
@[to]()[key](arguments...)
else
@defineProperty object, key,
enumerable: true,
configurable: true,
get: -> @[to]()[key]
object
isFunction: (object) ->
!!(object && object.constructor && object.call && object.apply)
toArray: (object) ->
if @isArray(object) then object else [object]
keys: (object) ->
Object.keys(object)
isA: (object, isa) ->
isRegExp: (object) ->
!!(object && object.test && object.exec && (object.ignoreCase || object.ignoreCase == false))
isHash: (object) ->
@isObject(object) && !(@isFunction(object) || @isArray(object) || _.isDate(object) || _.isRegExp(object))
isBaseObject: (object) ->
object && object.constructor && object.constructor.name == "Object"
isArray: Array.isArray || (object) ->
toString.call(object) == '[object Array]'
kind: (object) ->
type = typeof(object)
switch type
when "object"
return "array" if _.isArray(object)
return "arguments" if _.isArguments(object)
return "boolean" if _.isBoolean(object)
return "date" if _.isDate(object)
return "regex" if _.isRegExp(object)
return "NaN" if _.isNaN(object)
return "null" if _.isNull(object)
return "undefined" if _.isUndefined(object)
return "object"
when "number"
return "integer" if object == +object && object == (object|0)
return "float" if object == +object && object != (object|0)
return "number"
when "function"
return "regex" if _.isRegExp(object)
return "function"
else
return type
isObject: (object) ->
return object == Object(object)
isPresent: (object) ->
!@isBlank(object)
isBlank: (object) ->
return (object == "") if typeof object == "string"
return false for key, value of object
return true
has: (object, key) ->
object.hasOwnProperty(key)
Tower.Support.RegExp =
regexpEscape: (string) ->
string.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&")
Tower.Support.String =
camelize_rx: /(?:^|_|\-)(.)/g
capitalize_rx: /(^|\s)([a-z])/g
underscore_rx1: /([A-Z]+)([A-Z][a-z])/g
underscore_rx2: /([a-z\d])([A-Z])/g
parameterize: (string) ->
Tower.Support.String.underscore(string).replace("_", "-")
constantize: (string, scope = global) ->
scope[@camelize(string)]
camelize: (string, firstLetterLower) ->
string = string.replace @camelize_rx, (str, p1) -> p1.toUpperCase()
if firstLetterLower then string.substr(0,1).toLowerCase() + string.substr(1) else string
underscore: (string) ->
string.replace(@underscore_rx1, '$1_$2')
.replace(@underscore_rx2, '$1_$2')
.replace('-', '_').toLowerCase()
singularize: (string) ->
len = string.length
if string.substr(len - 3) is 'ies'
string.substr(0, len - 3) + 'y'
else if string.substr(len - 1) is 's'
string.substr(0, len - 1)
else
string
pluralize: (count, string) ->
if string
return string if count is 1
else
string = count
len = string.length
lastLetter = string.substr(len - 1)
if lastLetter is 'y'
"#{string.substr(0, len - 1)}ies"
else if lastLetter is 's'
string
else
"#{string}s"
capitalize: (string) -> string.replace @capitalize_rx, (m,p1,p2) -> p1 + p2.toUpperCase()
trim: (string) -> if string then string.trim() else ""
interpolate: (stringOrObject, keys) ->
if typeof stringOrObject is 'object'
string = stringOrObject[keys.count]
unless string
string = stringOrObject['other']
else
string = stringOrObject
for key, value of keys
string = string.replace(new RegExp("%\\{#{key}\\}", "g"), value)
string
# use single quotes, otherwise they're escaped
Tower.Support.String.toQueryValue = (value, negate = "") ->
if Tower.Support.Object.isArray(value)
items = []
for item in value
result = negate
result += item
items.push result
result = items.join(",")
else
result = negate
result += value.toString()
result = result.replace(" ", "+").replace /[#%\"\|<>]/g, (_) -> encodeURIComponent(_)
result
# toQuery likes: 10
# toQuery likes: ">=": 10
# toQuery likes: ">=": 10, "<=": 20
# toQuery tags: ["ruby", "javascript"]
# toQuery tags: "!=": ["java", ".net"]
# #=> tags=-java,-ruby
# toQuery tags: "!=": ["java", ".net"], "==": ["ruby", "javascript"]
# #=> tags=ruby,javascript,-java,-ruby
Tower.Support.String.toQuery = (object, schema = {}) ->
result = []
for key, value of object
param = "#{key}="
type = schema[key] || "string"
negate = if type == "string" then "-" else "^"
if Tower.Support.Object.isHash(value)
data = {}
data.min = value[">="] if value.hasOwnProperty(">=")
data.min = value[">"] if value.hasOwnProperty(">")
data.max = value["<="] if value.hasOwnProperty("<=")
data.max = value["<"] if value.hasOwnProperty("<")
data.match = value["=~"] if value.hasOwnProperty("=~")
data.notMatch = value["!~"] if value.hasOwnProperty("!~")
data.eq = value["=="] if value.hasOwnProperty("==")
data.neq = value["!="] if value.hasOwnProperty("!=")
data.range = data.hasOwnProperty("min") || data.hasOwnProperty("max")
set = []
if data.range && !(data.hasOwnProperty("eq") || data.hasOwnProperty("match"))
range = ""
if data.hasOwnProperty("min")
range += Tower.Support.String.toQueryValue(data.min)
else
range += "n"
range += ".."
if data.hasOwnProperty("max")
range += Tower.Support.String.toQueryValue(data.max)
else
range += "n"
set.push range
if data.hasOwnProperty("eq")
set.push Tower.Support.String.toQueryValue(data.eq)
if data.hasOwnProperty("match")
set.push Tower.Support.String.toQueryValue(data.match)
if data.hasOwnProperty("neq")
set.push Tower.Support.String.toQueryValue(data.neq, negate)
if data.hasOwnProperty("notMatch")
set.push Tower.Support.String.toQueryValue(data.notMatch, negate)
param += set.join(",")
else
param += Tower.Support.String.toQueryValue(value)
result.push param
result.sort().join("&")
Tower.Support.String.extractDomain = (host, tldLength = 1) ->
return null unless @namedHost(host)
parts = host.split('.')
parts[0..parts.length - 1 - 1 + tldLength].join(".")
Tower.Support.String.extractSubdomains = (host, tldLength = 1) ->
return [] unless @namedHost(host)
parts = host.split('.')
parts[0..-(tldLength+2)]
Tower.Support.String.extractSubdomain = (host, tldLength = 1) ->
@extractSubdomains(host, tldLength).join('.')
Tower.Support.String.namedHost = (host) ->
!!!(host == null || /\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.exec(host))
Tower.Support.String.rewriteAuthentication = (options) ->
if options.user && options.password
"#{encodeURI(options.user)}:#{encodeURI(options.password)}@"
else
""
Tower.Support.String.hostOrSubdomainAndDomain = (options) ->
return options.host if options.subdomain == null && options.domain == null
tldLength = options.tldLength || 1
host = ""
unless options.subdomain == false
subdomain = options.subdomain || @extractSubdomain(options.host, tldLength)
host += "#{subdomain}." if subdomain
host += (options.domain || @extractDomain(options.host, tldLength))
host
# urlFor controller: "posts", action: "index"
# urlFor @user
# urlFor User
# urlFor "admin", @user
# Tower._urlFor({onlyPath: true, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript /i], "!=": ["java"]}}, trailingSlash: false}, {likes: "integer"})
# "?likes=-10..20,^13,^15&tags=ruby,/javascript+/i,-java"
Tower.Support.String.urlFor = (options) ->
unless options.host || options.onlyPath
throw new Error('Missing host to link to! Please provide the :host parameter, set defaultUrlOptions[:host], or set :onlyPath to true')
result = ""
params = options.params || {}
path = (options.path || "").replace(/\/+/, "/")
schema = options.schema || {}
delete options.path
delete options.schema
unless options.onlyPath
port = options.port
delete options.port
unless options.protocol == false
result += options.protocol || "http"
result += ":" unless result.match(Tower.Support.RegExp.regexpEscape(":|//"))
result += "//" unless result.match("//")
result += @rewriteAuthentication(options)
result += @hostOrSubdomainAndDomain(options)
result += ":#{port}" if port
# params.reject! {|k,v| v.toParam.nil? }
if options.trailingSlash
result += path.replace /\/$/, "/"
else
result += path
result += "?#{Tower.Support.String.toQuery(params, schema)}" unless Tower.Support.Object.isBlank(params)
result += "##{Tower.Support.String.toQuery(options.anchor)}" if options.anchor
result
# Tower.urlFor(RW.MongoUser.first(), {onlyPath: false, params: {likes: {">=": -10, "<=": 20, "!=": [13, 15]}, tags: {"==": ["ruby", /javascript#/i], "!=": ["java"]}}, trailingSlash: true, host: "rituwall.com", user: "lance", password: "PI:PASSWORD:<PASSWORD>END_PI", anchor: {likes: 10}})
# "http://lance:pollard@rituwall.com/mongo-users/1?likes=-10..20,-13,-15&tags=ruby,/javascript%23/i,-java#likes=10"
Tower.urlFor = ->
args = Tower.Support.Array.args(arguments)
return null unless args[0]
if args[0] instanceof Tower.Model || (typeof(args[0])).match(/(string|function)/)
last = args[args.length - 1]
if last instanceof Tower.Model || (typeof(last)).match(/(string|function)/)
options = {}
else
options = args.pop()
options ||= args.pop()
result = ""
if options.controller && options.action
route = Tower.Route.find(name: Tower.Support.String.camelize(options.controller).replace(/(Controller)?$/, "Controller"), action: options.action)
if route
result = "/" + Tower.Support.String.parameterize(options.controller)
else
for item in args
result += "/"
if typeof(item) == "string"
result += item
else if item instanceof Tower.Model
result += item.toPath()
else if typeof(item) == "function" # need better, b/c i'm meaning constructor here
result += item.toParam()
result += switch options.action
when "new" then "/new"
when "edit" then "/edit"
else
""
options.onlyPath = true unless options.hasOwnProperty("onlyPath")
options.path = result
Tower.Support.String.urlFor(options)
Tower.Support.String.parameterize = (string) ->
Tower.Support.String.underscore(string).replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "-").replace(/^-+|-+$/g, '')
Tower.Support.Url = {}
class Tower.View.Component
@render: ->
args = Tower.Support.Array.args(arguments)
template = args.shift()
block = Tower.Support.Array.extractBlock(args)
unless args[args.length - 1] instanceof Tower.Model || typeof(args[args.length - 1]) != "object"
options = args.pop()
options ||= {}
options.template = template
(new @(args, options)).render(block)
constructor: (args, options) ->
@[key] = value for key, value of options
tag: (key, args...) ->
@template.tag key, args
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
class Tower.View.Form extends Tower.View.Component
constructor: (args, options) ->
super
@model = args.shift() || new Tower.Model
if typeof @model == "string"
klass = Tower.constant(Tower.Support.String.camelize(@model))
@model = if klass then new klass else null
@attributes = @_extractAttributes(options)
render: (callback) ->
@tag "form", @attributes, =>
@tag "input", type: "hidden", name: "_method", value: @attributes["data-method"]
if callback
builder = new Tower.View.Form.Builder([],
template: @template
tabindex: 1
accessKeys: {}
model: @model
)
builder.render(callback)
_extractAttributes: (options = {}) ->
attributes = options.html || {}
attributes.action = options.url || Tower.urlFor(@model)
attributes.class = options["class"] if options.hasOwnProperty("class")
#@mergeClass attributes, config.formClass
attributes.id = options.id if options.hasOwnProperty("id")
attributes.id ||= Tower.Support.String.parameterize("#{@model.constructor.name}-form")
attributes.enctype = "multipart/form-data" if (options.multipart || attributes.multipart == true)
attributes.role = "form"
attributes.novalidate = "true" # needs to be true b/c the error popups are horribly ugly!# if options.validate == false
attributes["data-validate"] = options.validate.toString() if options.hasOwnProperty("validate")
method = attributes.method || options.method
if !method || method == ""
if @model && @model.get("id")
method = "put"
else
method = "post"
attributes["data-method"] = method
attributes.method = if method == "get" then "get" else "post"
attributes
require './form/builder'
require './form/field'
require './form/fieldset'
Tower.View.Helpers =
titleTag: (title) ->
"<title>#{title}</title>"
metaTag: (name, content) ->
"""<meta name="#{name}" content="#{content}"/>"""
tag: (name, options) ->
linkTag: (title, path, options) ->
imageTag: (path, options) ->
csrfMetaTag: ->
@metaTag("csrf-token", @request.session._csrf)
contentTypeTag: (type = "UTF-8") ->
"<meta charset=\"#{type}\" />"
javascriptTag: (path) ->
"<script type=\"text/javascript\" src=\"#{path}\" ></script>"
stylesheetTag: (path) ->
"<link href=\"#{path}\" media=\"screen\" rel=\"stylesheet\" type=\"text/css\"/>"
mobileTags: ->
"""
<meta content='yes' name='apple-mobile-web-app-capable'>
<meta content='yes' name='apple-touch-fullscreen'>
<meta content='initial-scale = 1.0, maximum-scale = 1.0, user-scalable = no, width = device-width' name='viewport'>
"""
Tower.View.Rendering =
render: (options, callback) ->
options.type ||= @constructor.engine
options.layout = @_context.layout() if !options.hasOwnProperty("layout") && @_context.layout
options.locals = @_renderingContext(options)
@_renderBody options, (error, body) =>
return callback(error, body) if error
@_renderLayout(body, options, callback)
partial: (path, options, callback) ->
if typeof options == "function"
callback = options
options = {}
options ||= {}
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
@_renderString(template, options, callback)
_renderBody: (options, callback) ->
if options.text
callback(null, options.text)
else if options.json
callback(null, if typeof(options.json) == "string" then options.json else JSON.stringify(options.json))
else
unless options.inline
options.template = @_readTemplate(options.template, options.prefixes, options.type)
@_renderString(options.template, options, callback)
_renderLayout: (body, options, callback) ->
if options.layout
layout = @_readTemplate("layouts/#{options.layout}", [], options.type)
options.locals.body = body
@_renderString(layout, options, callback)
else
callback(null, body)
_renderString: (string, options = {}, callback) ->
if !!options.type.match(/coffee/)
e = null
result = null
# tmp hack
coffeekup = if Tower.client then global.CoffeeKup else require("coffeekup")
try
locals = options.locals
locals.renderWithEngine = @renderWithEngine
locals._readTemplate = @_readTemplate
locals.cache = Tower.env != "development"
locals.format = true
hardcode = {}
for helper in Tower.View.helpers
hardcode = _.extend(hardcode, helper)
hardcode = _.extend(hardcode, tags: coffeekup.tags)
locals.hardcode = hardcode
locals._ = _
result = coffeekup.render string, locals
catch error
e = error
callback e, result
else if options.type
mint = require "mint"
engine = require("mint").engine(options.type)
mint[engine](string, options.locals, callback)
else
mint = require "mint"
engine = require("mint")
options.locals.string = string
engine.render(options.locals, callback)
_renderingContext: (options) ->
locals = this
_ref = @_context
for key of _ref
value = _ref[key]
locals[key] = value unless key.match(/^(constructor|head)/)
#newlocals = {}
#newlocals.locals = locals
#locals = newlocals
locals = Tower.Support.Object.extend(locals, options.locals)
locals.pretty = true if @constructor.prettyPrint
locals
_readTemplate: (template, prefixes, ext) ->
return template unless typeof template == "string"
# tmp
result = @constructor.cache["app/views/#{template}"] ||= @constructor.store().find(path: template, ext: ext, prefixes: prefixes)
throw new Error("Template '#{template}' was not found.") unless result
result
renderWithEngine: (template, engine) ->
if Tower.client
"(#{template}).call(this);"
else
mint = require("mint")
mint[mint.engine(engine || "coffee")] template, {}, (error, result) ->
console.log error if error
class Tower.View.Table extends Tower.View.Component
constructor: (args, options) ->
super
recordOrKey = args.shift()
@key = @recordKey(recordOrKey)
@rowIndex = 0
@cellIndex = 0
@scope = "table"
@headers = []
options.summary ||= "Table for #{_.titleize(@key)}"
#options.class = ["data-table", options.class].compact.uniq.join(" ")
options.role = "grid"
options.class = @addClass(options.class || "", ["table"])
data = options.data ||= {}
#data.url = options.url || @template.controller.request.path
#data.for = options.for || options.model || @key
data.total = options.total if options.hasOwnProperty("total")
data.page = options.page if options.hasOwnProperty("page")
data.count = options.count if options.hasOwnProperty("count")
aria = options.aria || {}
delete options.aria
aria["aria-multiselectable"] = false unless aria.hasOwnProperty("aria-multiselectable") || options.multiselect == true
options.id ||= "#{recordOrKey}-table"
@options =
summary: options.summary
role: options.role
data: options.data
class: options.class
render: (block) ->
@tag "table", @options, =>
block(@) if block
null
tableQueryRowClass: ->
["search-row", if queryParams.except("page", "sort").blank? then null else "search-results"].compact.join(" ")
linkToSort: (title, attribute, options = {}) ->
sortParam = sortValue(attribute, oppositeSortDirection(attribute))
linkTo title, withParams(request.path, sort: sortParam), options
nextPagePath: (collection) ->
withParams(request.path, page: collection.nextPage)
prevPagePath: (collection) ->
withParams(request.path, page: collection.prevPage)
firstPagePath: (collection) ->
withParams(request.path, page: 1)
lastPagePath: (collection) ->
withParams(request.path, page: collection.lastPage)
currentPageNum: ->
page = if params.page then params.page else 1
page = 1 if page < 1
page
caption: ->
# scope='col'
head: (attributes = {}, block) ->
@hideHeader = attributes.visible == false
delete attributes.visible
@_section "head", attributes, block
# scope='row'
# <td headers='x'/>
body: (attributes = {}, block) ->
@_section "body", attributes, block
foot: (attributes = {}, block) ->
@_section "foot", attributes, block
_section: (scope, attributes, block) ->
@rowIndex = 0
@scope = scope
@tag "t#{scope}", attributes, block
@rowIndex = 0
@scope = "table"
row: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
attributes.scope = "row"
if @scope == "body"
#attributes.class = [template.cycle("odd", "even"), attributes.class].compact.uniq.join(" ")
attributes.role = "row"
@rowIndex += 1
@cellIndex = 0
@tag "tr", attributes, block
@cellIndex = 0
column: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
@headers.push attributes.id
tag "col", attributes
@cellIndex += 1
# direction => "ascending"
# valid directions: ascending, descending, none, other
# abbr is what the header controls (for sorting)
header: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.abbr ||= value
attributes.role = "columnheader"
attributes.id ||= @idFor("header", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
attributes.scope = "col"
attributes.abbr ||= attributes.for if attributes.hasOwnProperty("for")
attributes.abbr ||= value
delete attributes.for
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
sort = attributes.sort == true
delete attributes.sort
if sort
attributes.class = @addClass attributes.class || "", [attributes.sortClass || "sortable"]
attributes.direction ||= "asc"#@template.sortClass(value)
delete attributes.sortClass
label = attributes.label || _.titleize(value.toString())
delete attributes.label
direction = attributes.direction
delete attributes.direction
if direction
attributes["aria-sort"] = direction
attributes.class = [attributes.class, direction].join(" ")
attributes["aria-selected"] = true
else
attributes["aria-sort"] = "none"
attributes["aria-selected"] = false
@headers.push(attributes.id)
if block
@tag "th", attributes, block
else
if sort
@tag "th", attributes, =>
@linkToSort(label, value)
else
@tag "th", attributes, =>
@tag "span", label
@cellIndex += 1
linkToSort: (label, value) ->
direction = "+"
@tag "a", href: "?sort=#{direction}", =>
@tag "span", label
cell: (args..., block) ->
attributes = Tower.Support.Array.extractOptions(args)
value = args.shift()
attributes.role = "gridcell"
attributes.id ||= @idFor("cell", key, value, @rowIndex, @cellIndex) if Tower.View.idEnabledOn.include?("table")
#attributes[:"aria-describedby"] = @headers[@cellIndex]
attributes.headers = @headers[@cellIndex]
attributes.width = @pixelate(attributes.width) if attributes.hasOwnProperty("width")
attributes.height = @pixelate(attributes.height) if attributes.hasOwnProperty("height")
if block
@tag "td", attributes, block
else
@tag "td", value, attributes
@cellIndex += 1
recordKey: (recordOrKey) ->
if typeof recordOrKey == "string"
recordOrKey
else
recordOrKey.constructor.name
idFor: (type, key, value, row_index = @row_index, column_index = @column_index) ->
[key, type, row_index, column_index].compact.map (node) ->
node.replace(/[\s_]/, "-")
end.join("-")
pixelate: (value) ->
if typeof value == "string" then value else "#{value}px"
Tower.Controller.Elements =
ClassMethods:
# @extractElements $(".item a"), find: {meta: "span small"}, closest: {title: ".item h1"}
extractElements: (target, options = {}) ->
result = {}
for method, selectors of options
for key, selector of selectors
result[key] = target[method](selector)
result
processElements: (target, options = {}) ->
@elements = @extractElements(target, options)
clickHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
try
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
catch error
console.log error
return false
invalidForm: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
Tower.Controller.Events =
ClassMethods:
DOM_EVENTS: [
"click",
"dblclick",
"blur",
"error",
"focus",
"focusIn",
"focusOut",
"hover",
"keydown",
"keypress",
"keyup",
"load",
"mousedown",
"mouseenter",
"mouseleave",
"mousemove",
"mouseout",
"mouseover",
"mouseup",
"mousewheel",
"ready",
"resize",
"scroll",
"select",
"submit",
"tap",
"taphold",
"swipe",
"swipeleft",
"swiperight"
]
dispatcher: global
addEventHandler: (name, handler, options) ->
if options.type == "socket" || !name.match(@DOM_EVENT_PATTERN)
@addSocketEventHandler(name, handler, options)
else
@addDomEventHandler(name, handler, options)
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
@io ||= Tower.Application.instance().io.connect(@socketNamespace())
@io.on name, (data) =>
@_dispatch undefined, handler, data
# http://www.ravelrumba.com/blog/event-delegation-jquery-performance/
addDomEventHandler: (name, handler, options) ->
parts = name.split(/\ +/)
name = parts.shift()
selector = parts.join(" ")
options.target = selector if selector && selector != ""
options.target ||= "body"
eventType = name.split(/[\.:]/)[0]
method = @["#{eventType}Handler"]
if method
method.call @, name, handler, options
else
$(@dispatcher).on name, options.target, (event) => @_dispatch handler, options
@
_dispatch: (handler, options = {}) ->
controller = @instance()
controller.elements ||= {}
controller.params ||= {}
_.extend controller.params, options.params if options.params
_.extend controller.elements, options.elements if options.elements
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.Events.ClassMethods.DOM_EVENT_PATTERN = new RegExp("^(#{Tower.Controller.Events.ClassMethods.DOM_EVENTS.join("|")})")
Tower.Controller.Handlers =
ClassMethods:
submitHandler: (name, handler, options) ->
$(@dispatcher).on name, (event) =>
target = $(event.target)
form = target.closest("form")
action = form.attr("action")
method = (form.attr("data-method") || form.attr("method")).toUpperCase()
params = form.serializeParams()
params.method = method
params.action = action
elements = _.extend {target: target, form: form}, {}#, @extractElements(target, options)
@_dispatch handler, elements: elements, params: params
$.fn.serializeParams = (coerce) ->
$.serializeParams($(this).serialize(), coerce)
$.serializeParams = (params, coerce) ->
obj = {}
coerce_types =
true: not 0
false: not 1
null: null
array = params.replace(/\+/g, " ").split("&")
for item, index in array
param = item.split("=")
key = decodeURIComponent(param[0])
val = undefined
cur = obj
i = 0
keys = key.split("][")
keys_last = keys.length - 1
if /\[/.test(keys[0]) and /\]$/.test(keys[keys_last])
keys[keys_last] = keys[keys_last].replace(/\]$/, "")
keys = keys.shift().split("[").concat(keys)
keys_last = keys.length - 1
else
keys_last = 0
if param.length is 2
val = decodeURIComponent(param[1])
val = (if val and not isNaN(val) then +val else (if val is "undefined" then `undefined` else (if coerce_types[val] isnt `undefined` then coerce_types[val] else val))) if coerce
if keys_last
while i <= keys_last
key = (if keys[i] is "" then cur.length else keys[i])
cur = cur[key] = (if i < keys_last then cur[key] or (if keys[i + 1] and isNaN(keys[i + 1]) then {} else []) else val)
i++
else
if $.isArray(obj[key])
obj[key].push val
else if obj[key] isnt `undefined`
obj[key] = [ obj[key], val ]
else
obj[key] = val
else obj[key] = (if coerce then `undefined` else "") if key
obj
Tower.View.MetaHelper =
title: (string) ->
document.title = string
Tower.View.ValidationHelper =
success: ->
@redirectTo "/"
failure: (error) ->
if error
@flashError(error)
else
@invalidate()
invalidate: ->
element = $("##{@resourceName}-#{@elementName}")
for attribute, errors of @resource.errors
field = $("##{@resourceName}-#{attribute}-field")
if field.length
field.css("background", "yellow")
$("input", field).after("<output class='error'>#{errors.join("\n")}</output>")
class Tower.HTTP.Param.Array extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
class Tower.HTTP.Param.Date extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[\s,\+]/)
for string in array
isRange = false
string.replace /([^\.]+)?(\.\.)([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
values.push [@parseValue(string, ["$eq"])] unless isRange
values
parseValue: (value, operators) ->
super(Tower.date(value), operators)
class Tower.HTTP.Param.Number extends Tower.HTTP.Param
parse: (value) ->
values = []
array = value.toString().split(/[,\|]/)
for string in array
isRange = false
negation = !!string.match(/^\^/)
string = string.replace(/^\^/, "")
string.replace /([^\.]+)?(\.{2})([^\.]+)?/, (_, startsOn, operator, endsOn) =>
isRange = true
range = []
range.push @parseValue(startsOn, ["$gte"]) if !!(startsOn && startsOn.match(/^\d/))
range.push @parseValue(endsOn, ["$lte"]) if !!(endsOn && endsOn.match(/^\d/))
values.push range
unless isRange
values.push [@parseValue(string, ["$eq"])]
values
parseValue: (value, operators) ->
super(parseFloat(value), operators)
class Tower.HTTP.Param.String extends Tower.HTTP.Param
parse: (value) ->
arrays = value.split(/(?:[\s|\+]OR[\s|\+]|\||,)/)
for node, i in arrays
values = []
# ([\+\-\^]?[\w@\-_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')
node.replace /([\+\-\^]?[\w@_\s\d\.\$]+|-?\'[\w@-_\s\d\+\.\$]+\')/g, (_, token) =>
negation = false
exact = false
token = token.replace /^(\+?-+)/, (_, $1) ->
negation = $1 && $1.length > 0
""
token = token.replace /^\'(.+)\'$/, (_, $1) ->
exact = $1 && $1.length > 0
$1
if negation
operators = [if exact then "$neq" else "$notMatch"]
else
operators = [if exact then "$eq" else "$match"]
operators.push "^" if !!token.match(/^\+?\-?\^/)
operators.push "$" if !!token.match(/\$$/)
values.push @parseValue(@_clean(token), operators)
_
arrays[i] = values
arrays
class Tower.HTTP.Route.DSL
constructor: ->
@_scope = {}
match: ->
@scope ||= {}
Tower.HTTP.Route.create(new Tower.HTTP.Route(@_extractOptions(arguments...)))
get: ->
@matchMethod("get", Tower.Support.Array.args(arguments))
post: ->
@matchMethod("post", Tower.Support.Array.args(arguments))
put: ->
@matchMethod("put", Tower.Support.Array.args(arguments))
delete: ->
@matchMethod("delete", Tower.Support.Array.args(arguments))
matchMethod: (method, args) ->
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
name = args.shift()
options.method = method
options.action = name
options.name = name
if @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
path = "/#{name}"
path = @_scope.path + path if @_scope.path
@match(path, options)
@
scope: (options = {}, block) ->
originalScope = @_scope ||= {}
@_scope = Tower.Support.Object.extend {}, originalScope, options
block.call(@)
@_scope = originalScope
@
controller: (controller, options, block) ->
options.controller = controller
@scope(options, block)
namespace: (path, options, block) ->
if typeof options == 'function'
block = options
options = {}
else
options = {}
options = Tower.Support.Object.extend(name: path, path: path, as: path, module: path, shallowPath: path, shallowPrefix: path, options)
if options.name && @_scope.name
options.name = @_scope.name + Tower.Support.String.camelize(options.name)
@scope(options, block)
constraints: (options, block) ->
@scope(constraints: options, block)
defaults: (options, block) ->
@scope(defaults: options, block)
resource: (name, options = {}) ->
options.controller = name
@match "#{name}/new", Tower.Support.Object.extend({action: "new"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{name}/", Tower.Support.Object.extend({action: "show"}, options)
@match "#{name}/edit", Tower.Support.Object.extend({action: "edit"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{name}", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
resources: (name, options, callback) ->
if typeof options == 'function'
callback = options
options = {}
else
options = {}
options.controller ||= name
path = "/#{name}"
path = @_scope.path + path if @_scope.path
if @_scope.name
many = @_scope.name + Tower.Support.String.camelize(name)
else
many = name
one = Tower.Support.String.singularize(many)
@match "#{path}", Tower.Support.Object.extend({name: "#{many}", action: "index"}, options)
@match "#{path}/new", Tower.Support.Object.extend({name: "new#{Tower.Support.String.camelize(one)}", action: "new"}, options)
@match "#{path}", Tower.Support.Object.extend({action: "create", method: "POST"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({name: "#{one}", action: "show"}, options)
@match "#{path}/:id/edit", Tower.Support.Object.extend({name: "edit#{Tower.Support.String.camelize(one)}", action: "edit"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "update", method: "PUT"}, options)
@match "#{path}/:id", Tower.Support.Object.extend({action: "destroy", method: "DELETE"}, options)
if callback
@scope Tower.Support.Object.extend({path: "#{path}/:#{Tower.Support.String.singularize(name)}Id", name: one}, options), callback
@
collection: ->
member: ->
root: (options) ->
@match '/', Tower.Support.Object.extend(as: "root", options)
_extractOptions: ->
args = Tower.Support.Array.args(arguments)
path = "/" + args.shift().replace(/^\/|\/$/, "")
if typeof args[args.length - 1] == "object"
options = args.pop()
else
options = {}
options.to ||= args.shift() if args.length > 0
options.path = path
format = @_extractFormat(options)
options.path = @_extractPath(options)
method = @_extractRequestMethod(options)
constraints = @_extractConstraints(options)
defaults = @_extractDefaults(options)
controller = @_extractController(options)
anchor = @_extractAnchor(options)
name = @_extractName(options)
options = Tower.Support.Object.extend options,
method: method
constraints: constraints
defaults: defaults
name: name
format: format
controller: controller
anchor: anchor
ip: options.ip
options
_extractFormat: (options) ->
_extractName: (options) ->
options.as || options.name
_extractConstraints: (options) ->
Tower.Support.Object.extend(@_scope.constraints || {}, options.constraints || {})
_extractDefaults: (options) ->
options.defaults || {}
_extractPath: (options) ->
"#{options.path}.:format?"
_extractRequestMethod: (options) ->
(options.method || options.via || "GET").toUpperCase()
_extractAnchor: (options) ->
options.anchor
_extractController: (options = {}) ->
to = options.to
if to
to = to.split('#')
if to.length == 1
action = to[0]
else
controller = to[0]
action = to[1]
controller ||= options.controller || @_scope.controller
action ||= options.action
throw new Error("No controller was specified for the route #{options.path}") unless controller
controller = controller.toLowerCase().replace(/(?:[cC]ontroller)?$/, "Controller")
#action = action.toLowerCase()
name: controller, action: action, className: Tower.Support.String.camelize("#{controller}")
Tower.HTTP.Route.PolymorphicUrls =
ClassMethods:
polymorphicUrl: ->
Tower.HTTP.Route.Urls =
ClassMethods:
urlFor: (options) ->
switch typeof(options)
when "string"
options
else
# https://github.com/kieran/barista/blob/master/lib/route.js#L157
{controller, action, host, port, anchor} = options
Tower.Support.I18n.load model:
errors:
presence: "%{attribute} can't be blank"
minimum: "%{attribute} must be a minimum of %{value}"
maximum: "%{attribute} must be a maximum of %{value}"
length: "%{attribute} must be equal to %{value}"
format: "%{attribute} must be match the format %{value}"
inclusion: "%{attribute} is not included in the list"
exclusion: "%{attribute} is reserved"
invalid: "%{attribute} is invalid"
confirmation: "%{attribute} doesn't match confirmation"
accepted: "%{attribute} must be accepted"
empty: "%{attribute} can't be empty"
blank: "%{attribute} can't be blank"
tooLong: "%{attribute} is too long (maximum is %{count} characters)"
tooShort: "%{attribute} is too short (minimum is %{count} characters)"
wrongLength: "%{attribute} is the wrong length (should be %{count} characters)"
taken: "%{attribute} has already been taken"
notANumber: "%{attribute} is not a number"
greaterThan: "%{attribute} must be greater than %{count}"
greaterThanOrEqualTo: "%{attribute} must be greater than or equal to %{count}"
equalTo: "%{attribute} must be equal to %{count}"
lessThan: "%{attribute} must be less than %{count}"
lessThanOrEqualTo: "%{attribute} must be less than or equal to %{count}"
odd: "%{attribute} must be odd"
even: "%{attribute} must be even"
recordInvalid: "Validation failed: %{errors}"
# Append your own errors here or at the model/attributes scope.
fullMessages:
format: "%{message}"
#format: "%{attribute} %{message}"
class Tower.Model.Relation.BelongsTo extends Tower.Model.Relation
constructor: (owner, name, options = {}) ->
super(owner, name, options)
@foreignKey = PI:KEY:<KEY>END_PI"
owner.field @foreignKey, type: "Id"
if @polymorphic
@foreignType = "#{name}Type"
owner.field @foreignType, type: "String"
owner.prototype[name] = (callback) ->
@relation(name).first(callback)
self = @
owner.prototype["build#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@buildRelation(name, attributes, callback)
owner.prototype["create#{Tower.Support.String.camelize(name)}"] = (attributes, callback) ->
@createRelation(name, attributes, callback)
class @Scope extends @Scope
# need to do something here about Reflection
class Tower.Model.Relation.HasMany extends Tower.Model.Relation
class @Scope extends @Scope
create: ->
unless @owner.isPersisted()
throw new Error("You cannot call create unless the parent is saved")
relation = @relation
inverseRelation = relation.inverse()
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
id = @owner.get("id")
if inverseRelation && inverseRelation.cache
array = data[inverseRelation.cacheKey] || []
array.push(id) if array.indexOf(id) == -1
data[inverseRelation.cacheKey] = array
else if relation.foreignKey
data[relation.foreignKey] = id if id != undefined
# must check here if owner is instance of foreignType
data[relation.foreignType] ||= @owner.constructor.name if @relation.foreignType
criteria.where(data)
criteria.mergeOptions(options)
if inverseRelation && inverseRelation.counterCacheKey
defaults = {}
defaults[inverseRelation.counterCacheKey] = 1
criteria.where(defaults)
instantiate = options.instantiate != false
{attributes, options} = criteria.toCreate()
options.instantiate = true
@_create criteria, attributes, options, (error, record) =>
unless error
# add the id to the array on the owner record after it's created
if relation && (relation.cache || relation.counterCache)
if relation.cache
push = {}
push[relation.cacheKey] = record.get("id")
if relation.counterCacheKey
inc = {}
inc[relation.counterCacheKey] = 1
updates = {}
updates["$push"] = push if push
updates["$inc"] = inc if inc
@owner.updateAttributes updates, callback
else
callback.call @, error, record if callback
else
callback.call @, error, record if callback
update: ->
destroy: ->
concat: ->
_serializeAttributes: (attributes = {}) ->
target = Tower.constant(@relation.targetClassName)
for name, relation of target.relations()
if attributes.hasOwnProperty(name)
value = attributes[name]
delete attributes[name]
if relation instanceof Tower.Model.Relation.BelongsTo
attributes[relation.foreignKey] = value.id
attributes[relation.foreignType] = value.type if relation.polymorphic
attributes
toCriteria: ->
criteria = super
relation = @relation
if relation.cache
defaults = {}
defaults[relation.foreignKey + "s"] = $in: [@owner.get("id")]
criteria.where(defaults)
criteria
class Tower.Model.Relation.HasOne extends Tower.Model.Relation
Tower.Model.Scope.Finders =
ClassMethods:
finderMethods: [
"find",
"all",
"first",
"last",
"count",
"exists"
]
find: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
{conditions, options} = criteria.toQuery()
@_find conditions, options, callback
first: (callback) ->
{conditions, options} = @toQuery("asc")
@store.findOne conditions, options, callback
last: (callback) ->
{conditions, options} = @toQuery("desc")
@store.findOne conditions, options, callback
all: (callback) ->
{conditions, options} = @toQuery()
@store.find conditions, options, callback
count: (callback) ->
{conditions, options} = @toQuery()
@store.count conditions, options, callback
exists: (callback) ->
{conditions, options} = @toQuery()
@store.exists conditions, options, callback
batch: ->
fetch: ->
_find: (conditions, options, callback) ->
if conditions.id && conditions.id.hasOwnProperty("$in") && conditions.id.$in.length == 1
@store.findOne conditions, options, callback
else if conditions.id && !conditions.id.hasOwnProperty("$in")
conditions.id = {$in: Tower.Support.Object.toArray(conditions.id)}
@store.findOne conditions, options, callback
else
@store.find conditions, options, callback
# @todo
Tower.Model.Scope.Modifiers =
ClassMethods:
atomicModifiers:
"$set": "$set"
"$unset": "$unset"
"$push": "$push"
"$pushAll": "$pushAll"
"$pull": "$pull"
"$pullAll": "$pullAll"
"$inc": "$inc"
"$pop": "$pop"
# { $push : { field : value } }
push: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= []
# @todo check if valid type from schema!
if all && _.isArray(value)
attributes[key] = attributes[key].concat(value)
else
attributes[key].push(value)
@changeAttribute(changes, key, oldValue, attributes[key])
changes
changeAttribute: (changes, key, oldValue, newValue) ->
unless !!changes[key]
changes[key] = [oldValue, newValue]
else
changes[key][1] = newValue
delete changes[key] if changes[key][0] == changes[key][1]
changes
# { $pushAll : { field : array } }
pushAll: (record, updates) ->
@push record, updates, true
pull: (record, updates, all) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
attributeValue = attributes[key]
oldValue = undefined
if attributeValue && _.isArray(attributeValue)
oldValue = attributeValue.concat()
if all && _.isArray(value)
for item in value
attributeValue.splice _attributeValue.indexOf(item), 1
else
attributeValue.splice _attributeValue.indexOf(value), 1
@changeAttribute(changes, key, oldValue, attributeValue)
changes
pullAll: (record, updates) ->
@pull record, updates, true
inc: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] ||= 0
attributes[key] += value
@changeAttribute changes, key, oldValue, attributes[key]
attributes
set: (record, updates) ->
attributes = record.attributes
schema = record.constructor.schema()
changes = record.changes
for key, value of updates
field = schema[key]
oldValue = attributes[key]
if field && field.type == "Array" && !Tower.Support.Object.isArray(value)
attributes[key] ||= []
attributes[key].push value
else
attributes[key] = value
@changeAttribute changes, key, oldValue, attributes[key]
changes
unset: (record, updates) ->
attributes = record.attributes
changes = record.changes
for key, value of updates
oldValue = attributes[key]
attributes[key] = undefined
@changeAttribute changes, key, oldValue, attributes[key]
changes
update: (record, updates) ->
set = null
for key, value of updates
if @isAtomicModifier(key)
@["#{key.replace("$", "")}"](record, value)
else
set ||= {}
set[key] = value
@set(record, set) if set
record
assignAttributes: (attributes) ->
for key, value of attributes
delete @changes[key]
@attributes[key] = value
@
resetAttributes: (keys) ->
@resetAttributes(key) for key in keys
@
resetAttribute: (key) ->
array = @changes[key]
if array
delete @changes[key]
@attributes[key] = array[0]
@
toUpdates: (record) ->
result = {}
changes = record.changes
schema = record.constructor.schema()
for key, value of changes
field = field[key]
if field
if field.type == "Array"
pop = _.difference(value[0], value[1])
if pop.length > 0
result.$pop ||= {}
result.$pop[key] = pop
push = _.difference(value[1], value[0])
if push.length > 0
result.$push ||= {}
result.$push[key] = push
else if field.type == "Integer"
result.$inc ||= {}
result.$inc[key] = (value[1] || 0) - (value[0] || 0)
else
result[key]
result
Tower.Model.Scope.Persistence =
ClassMethods:
persistenceMethods: [
"create",
"update",
"destroy"
]
build: (attributes, options) ->
{conditions, options} = @toCreate()
@_build attributes, conditions, options
# User.create(firstName: "PI:NAME:<NAME>END_PI")
# User.where(firstName: "PI:NAME:<NAME>END_PI").create()
# User.where(firstName: "PI:NAME:<NAME>END_PI").create([{lastName: "PI:NAME:<NAME>END_PI"}, {lastName: "PI:NAME:<NAME>END_PI"}])
# User.where(firstName: "PI:NAME:<NAME>END_PI").create(new User(lastName: "PI:NAME:<NAME>END_PI"))
# create(attributes)
# create([attributes, attributes])
# create(attributes, options)
create: ->
{criteria, data, options, callback} = @_extractArgs(arguments, data: true)
criteria.mergeOptions(options)
@_create criteria, data, options, callback
# User.where(firstName: "PI:NAME:<NAME>END_PI").update(1, 2, 3)
# User.update(User.first(), User.last(), firstName: "PI:NAME:<NAME>END_PI")
# User.update([User.first(), User.last()], firstName: "PI:NAME:<NAME>END_PI")
# User.update([1, 2], firstName: "PI:NAME:<NAME>END_PI")
update: ->
{criteria, data, options, callback} = @_extractArgs(arguments, ids: true, data: true)
criteria.mergeOptions(options)
@_update criteria, data, options, callback
destroy: ->
{criteria, options, callback} = @_extractArgs(arguments, ids: true)
criteria.mergeOptions(options)
@_destroy criteria, options, callback
sync: ->
transaction: ->
_build: (attributes, conditions, options) ->
if Tower.Support.Object.isArray(attributes)
result = []
for object in attributes
result.push @store.serializeModel(Tower.Support.Object.extend({}, conditions, object))
result
else
@store.serializeModel(Tower.Support.Object.extend({}, conditions, attributes))
_create: (criteria, data, opts, callback) ->
if opts.instantiate
isArray = Tower.Support.Object.isArray(data)
records = Tower.Support.Object.toArray(@build(data))
iterator = (record, next) ->
if record
record.save(next)
else
next()
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
return callback(error) if error
if isArray
callback(error, records)
else
callback(error, records[0])
else
@store.create data, opts, callback
_update: (criteria, data, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.updateAttributes(data, next)
@_each conditions, options, iterator, callback
else
@store.update data, conditions, options, callback
_destroy: (criteria, opts, callback) ->
{conditions, options} = criteria.toQuery()
if opts.instantiate
iterator = (record, next) ->
record.destroy(next)
@_each conditions, options, iterator, callback
else
@store.destroy conditions, options, callback
_each: (conditions, options, iterator, callback) ->
@store.find conditions, options, (error, records) =>
if error
callback.call @, error, records
else
Tower.async records, iterator, (error) =>
unless callback
throw error if error
else
callback.call @, error, records if callback
Tower.Model.Scope.Queries =
ClassMethods:
queryMethods: [
"where",
"order",
"asc",
"desc",
"limit",
"offset",
"select",
"joins",
"includes",
"excludes",
"paginate",
"within",
"allIn",
"allOf",
"alsoIn",
"anyIn",
"anyOf",
"near",
"notIn"
]
queryOperators:
">=": "$gte"
"$gte": "$gte"
">": "$gt"
"$gt": "$gt"
"<=": "$lte"
"$lte": "$lte"
"<": "$lt"
"$lt": "$lt"
"$in": "$in"
"$nin": "$nin"
"$any": "$any"
"$all": "$all"
"=~": "$regex"
"$m": "$regex"
"$regex": "$regex"
"$match": "$match"
"$notMatch": "$notMatch"
"!~": "$nm"
"$nm": "$nm"
"=": "$eq"
"$eq": "$eq"
"!=": "$neq"
"$neq": "$neq"
"$null": "$null"
"$notNull": "$notNull"
class Tower.Model.Validator.Format
constructor: (value, attributes) ->
super(value, attributes)
@value = if typeof(value) == 'string' then new RegExp(value) else value
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless !!@value.exec(value)
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.format", attribute: attribute, value: @value.toString())
callback
)
else
@success(callback)
class Tower.Model.Validator.Length extends Tower.Model.Validator
constructor: (name, value, attributes) ->
super
@validate = switch name
when "min" then @validateMinimum
when "max" then @validateMaximum
else
@validateLength
validateMinimum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value >= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.minimum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateMaximum: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value <= @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.maximum", attribute: attribute, value: @value),
callback
)
@success(callback)
validateLength: (record, attribute, errors, callback) ->
value = record.get(attribute)
unless typeof(value) == 'number' && value == @value
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.length", attribute: attribute, value: @value)
callback
)
@success(callback)
class Tower.Model.Validator.Presence extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
unless Tower.Support.Object.isPresent(record.get(attribute))
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.presence", attribute: attribute),
callback
)
@success(callback)
class Tower.Model.Validator.Uniqueness extends Tower.Model.Validator
validate: (record, attribute, errors, callback) ->
value = record.get(attribute)
conditions = {}
conditions[attribute] = value
record.constructor.where(conditions).exists (error, result) =>
if result
return @failure(
record,
attribute,
errors,
Tower.t("model.errors.uniqueness", attribute: attribute, value: value),
callback
)
else
@success(callback)
Tower.Controller.Caching =
freshWhen: ->
stale: ->
expiresIn: ->
Tower.Controller.Events =
ClassMethods:
addEventHandler: (name, handler, options) ->
@_addSocketEventHandler name, handler, options
socketNamespace: ->
Tower.Support.String.pluralize(Tower.Support.String.camelize(@name.replace(/(Controller)$/, ""), false))
addSocketEventHandler: (name, handler, options) ->
unless @io
@_socketHandlers = {}
@io = Tower.Application.instance().socket.of(@socketNamespace()).on "connection", (socket) =>
for eventType, handler of @_socketHandlers
do (eventType, handler) ->
if eventType isnt 'connection' and eventType isnt 'disconnect'
socket.on eventType, (data) =>
@_dispatch undefined, handler, data
@_socketHandlers[name] = handler
_dispatch: (event, handler, locals = {}) ->
controller = new @
for key, value of locals
controller.params[key] = value
if typeof handler == "string"
controller[handler].call controller, event
else
handler.call controller, event
Tower.Controller.HTTP =
head: (status, options = {}) ->
if typeof status == "object"
options = status
status = null
status ||= options.status || "ok"
location = options.location
delete options.status
delete options.location
#for key, value of options
# @headers[key.dasherize.split('-').each { |v| v[0] = v[0].chr.upcase }.join('-')] = value.to_s
@status = status
@location = Tower.urlFor(location) if location
@headers["Content-Type"] = Mime[formats.first] if formats
@body = " "
Tower.Controller.addRenderers
json: (json, options, callback) ->
json = JSON.stringify(json) unless typeof(json) == "string"
json = "#{options.callback}(#{json})" if options.callback
@headers["Content-Type"] ||= require("mime").lookup("json")
callback null, json if callback
json
# https://github.com/wdavidw/node-csv-parser
# csv: (csv, options, callback) ->
# https://github.com/devongovett/pdfkit
# pdf: (data, options, callback) ->
Tower.Controller.Sockets =
broadcast: ->
emit: ->
connect: ->
Tower.Mailer.Configuration =
ClassMethods:
lib: -> require('mailer')
Tower.Mailer.Rendering =
ClassMethods:
mail: (options = {}, callback) ->
@host = options.host
@port = options.port
@domain = options.domain
@to = options.to
@from = options.from
@subject = options.subject
@locals = options.locals || {}
@template = options.template
deliver: ->
email = @constructor.lib()
self = @
Shift.render path: @template, @locals, (error, body) ->
options =
host: self.host
port: self.port
domain: self.domain
to: self.to
from: self.from
subject: self.subject
body: body
authentication: self.login
username: self.username
password: PI:PASSWORD:<PASSWORD>END_PI
email.send options, (error, result) ->
console.log error if error
console.log result
Tower.Support.I18n.load date:
formats:
# Use the strftime parameters for formats.
# When no format has been given", it uses default.
# You can provide other formats here if you like!
default: "%Y-%m-%d"
short: "%b %d"
long: "%B %d, %Y"
dayNames: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
abbrDayNames: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]
# Don't forget the nil at the beginning; there's no such thing as a 0th month
monthNames: [null, "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
abbrMonthNames: [null, "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
# Used in dateSelect and datetimeSelect.
order: ["year", "month", "day"]
time:
formats:
default: "%a, %d %b %Y %H:%M:%S %z"
short: "%d %b %H:%M"
long: "%B %d, %Y %H:%M"
am: "am"
pm: "pm"
# Used in array.toSentence.
support:
array:
wordsConnector: ", "
twoWordsConnector: " and "
lastWordConnector: ", and "
class Tower.View.Form.Builder extends Tower.View.Component
constructor: (args, options = {}) ->
@template = options.template
@model = options.model
@attribute = options.attribute
@parentIndex = options.parentIndex
@index = options.index
@tabindex = options.tabindex
@accessKeys = options.accessKeys
#@attributes = @cloneAttributes(options.except(:template, :model, :attribute, :accessKeys, :index, :tabindex))
defaultOptions: (options = {}) ->
options.model ||= @model
options.index ||= @index
options.attribute ||= @attribute
options.template ||= @template
options
fieldset: (args...) ->
block = args.pop()
options = @defaultOptions(Tower.Support.Array.extractOptions(args))
options.label ||= args.shift()
new Tower.View.Form.Fieldset([], options).render(block)
fields: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as = "fields"
options.label ||= false
attribute = args.shift() || @attribute
@field attribute, options, (_field) =>
@fieldset(block)
fieldsFor: ->
options = args.extractOptions
attribute = args.shift
macro = model.macroFor(attribute)
attrName = nil
if options.as == "object"
attrName = attribute.toS
else
attrName = if Tower.View.renameNestedAttributes then "#{attribute}_attributes" else attribute.toS
# -> something here for counts
subParent = model.object
subObject = args.shift
index = options.delete("index")
unless index.present? && typeof index == "string"
if subObject.blank? && index.present?
subObject = subParent.send(attribute)[index]
else if index.blank? && subObject.present? && macro == "hasMany"
index = subParent.send(attribute).index(subObject)
subObject ||= model.default(attribute) || model.toS.camelize.constantize.new
keys = [model.keys, attrName]
options.merge(
template: template
model: model
parentIndex: index
accessKeys: accessKeys
tabindex: tabindex
)
new Tower.View.Form.Builder(options).render(block)
field: ->
args = Tower.Support.Array.args(arguments)
last = args[args.length - 1]
args.pop() if last == null || last == undefined
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
attributeName = args.shift() || "attribute.name"
#attribute = Storefront:"Attribute".new(
# name: attributeName,
# model: @model,
# required: options.required == true,
# disabled: options.disabled == true,
# topLevel: options.attribute == false
#)
defaults =
template: @template
model: @model
attribute: attributeName,
parentIndex: @parentIndex
index: @index
fieldHTML: options.fieldHTML || {}
inputHTML: options.inputHTML || {}
labelHTML: options.labelHTML || {}
errorHTML: options.errorHTML || {}
hintHtml: options.hintHtml || {}
new Tower.View.Form.Field([], _.extend(defaults, options)).render(block)
button: ->
args = Tower.Support.Array.args(arguments)
block = Tower.Support.Array.extractBlock(args)
options = Tower.Support.Array.extractOptions(args)
options.as ||= "submit"
options.value = args.shift() || "Submit"
options.class = Tower.View.submitFieldsetClass if options.as == "submit"
@field options.value, options, block
submit: @::button
partial: (path, options = {}) ->
@template.render partial: path, locals: options.merge(fields: self)
tag: (key, args...) ->
@template.tag key, args
render: (block) ->
block(@)
class Tower.View.Form.Field extends Tower.View.Component
addClass: (string, args) ->
result = if string then string.split(/\s+/g) else []
for arg in args
continue unless arg
result.push(arg) unless result.indexOf(arg) > -1
result.join(" ")
toId: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "-#{options.parentIndex}" if options.parentIndex
result += "-#{Tower.Support.String.parameterize(@attribute)}"
result += "-#{options.type || "field"}"
result += "-#{@index}" if @index?
result
toParam: (options = {}) ->
result = Tower.Support.String.parameterize(@model.constructor.name)#@model.toKey()
result += "[#{options.parentIndex}]" if options.parentIndex
result += "[#{@attribute}]"
result += "[#{@index}]" if @index?
result
constructor: (args, options) ->
@labelValue = options.label
delete options.label
super(args, options)
@required ||= false
# input type
field = @model.constructor.fields()[@attribute]
options.as ||= if field then Tower.Support.String.camelize(field.type, true) else "string"
@inputType = inputType = options.as
@required = !!(field && field.required == true)
# class
classes = [Tower.View.fieldClass, inputType]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
if options.validate != false && field.validations
classes.push Tower.View.validateClass
@fieldHTML.class = @addClass @fieldHTML.class, classes
# id
if !@fieldHTML.id && Tower.View.idEnabledOn.indexOf("field") > -1
@fieldHTML.id = @toId(type: "field", index: @index, parentIndex: @parentIndex)
@inputHTML.id = @toId(type: "input", index: @index, parentIndex: @parentIndex)
unless ["hidden", "submit"].indexOf(inputType) > -1
@labelHTML.for ||= @inputHTML.id
@labelHTML.class = @addClass @labelHTML.class, [Tower.View.labelClass]
unless @labelValue == false
@labelValue ||= Tower.Support.String.camelize(@attribute.toString())
unless options.hint == false
@errorHTML.class = @addClass @errorHTML.class, [Tower.View.errorClass]
if Tower.View.includeAria && Tower.View.hintIsPopup
@errorHTML.role ||= "tooltip"
@attributes = @fieldHTML
@inputHTML.name ||= @toParam() unless inputType == "submit"
@value = options.value
@dynamic = options.dynamic == true
@richInput = if options.hasOwnProperty("rich_input") then !!options.rich_input else Tower.View.richInput
@validate = options.validate != false
classes = [inputType, Tower.Support.String.parameterize(@attribute), @inputHTML.class]
unless ["submit", "fieldset"].indexOf(inputType) > -1
classes.push if field.required then Tower.View.requiredClass else Tower.View.optionalClass
classes.push if field.errors then Tower.View.errorClass else Tower.View.validClass
classes.push "input"
if options.validate != false && field.validations
classes.push Tower.View.validateClass
# class
@inputHTML.class = @addClass @inputHTML.class, classes
@inputHTML.placeholder = options.placeholder if options.placeholder
# value
unless @inputHTML.value?
if options.hasOwnProperty("value")
@inputHTML.value = options.value
unless @inputHTML.value?
value = @model.get(@attribute)
@inputHTML.value = value if value
# @inputHTML[:tabindex] = @tabindex
@inputHTML.maxlength ||= options.max if options.hasOwnProperty("max")
# expressions
pattern = options.match
pattern = pattern.toString() if _.isRegExp(pattern)
@inputHTML["data-match"] = pattern if pattern?
@inputHTML["aria-required"] = @required.toString()
@inputHTML.required = "true" if @required == true
@inputHTML.disabled = "true" if @disabled
@inputHTML.autofocus = "true" if @autofocus == true
@inputHTML["data-dynamic"] = "true" if @dynamic
@inputHTML.title ||= @inputHTML.placeholder if @inputHTML.placeholder
@autocomplete = @inputHTML.autocomplete == true
if @autocomplete && Tower.View.includeAria
@inputHTML["aria-autocomplete"] = switch @autocomplete
when "inline", "list", "both"
@autocomplete
else
"both"
input: (args...) ->
options = _.extend @inputHTML, Tower.Support.Array.extractOptions(args)
key = args.shift() || @attribute
@["#{@inputType}Input"](key, options)
checkboxInput: (key, options) ->
@tag "input", _.extend(type: "checkbox", options)
stringInput: (key, options) ->
@tag "input", _.extend(type: "text", options)
submitInput: (key, options) ->
@tag "input", _.extend(type: "submit", options)
fileInput: (key, options) ->
@tag "input", _.extend(type: "file", options)
textInput: (key, options) ->
@tag "textarea", options
password_input: (key, options) ->
@tag "input", _.extend(type: "password", options)
emailInput: (key, options) ->
@tag "input", _.extend(type: "email", options)
urlInput: (key, options) ->
@tag "input", _.extend(type: "url", options)
numberInput: (key, options) ->
@tag "input", _.extend(type: "string", "data-type": "numeric", options)
searchInput: (key, options) ->
@tag "input", _.extend(type: "search", "data-type": "search", options)
phoneInput: (key, options) ->
@tag "input", _.extend(type: "tel", "data-type": "phone", options)
label: ->
return unless @labelValue
@tag "label", @labelHTML, =>
@tag "span", @labelValue
if @required
@tag "abbr", title: Tower.View.requiredTitle, class: Tower.View.requiredClass, -> Tower.View.requiredAbbr
else
@tag "abbr", title: Tower.View.optionalTitle, class: Tower.View.optionalClass, -> Tower.View.optionalAbbr
render: (block) ->
@tag Tower.View.fieldTag, @attributes, =>
if block
block.call @
else
@label()
@input()
#elements = extractElements!(attributes)
#
#result = elements.map do |element|
# Array(send(element)).map(&"render")
#template.hamlConcat result.flatten.join.gsub(/\n$/, "") if result.present?
#
#yield(self) if blockGiven? # template.captureHaml(self, block)
extractElements: (options = {}) ->
elements = []
if ["hidden", "submit"].include?(inputType)
elements.push "inputs"
else
if @label.present? && @label.value?
elements.push "label"
elements = elements.concat ["inputs", "hints", "errors"]
elements
class Tower.View.Form.Fieldset extends Tower.View.Component
constructor: (args, options) ->
super
#@label = @localize("titles", options[:label], nil, (attributes[:locale_options] || {}).merge(:allow_blank => true)) if options[:label].present?
#merge_class! attributes, *[
# config.fieldset_class
#]
@attributes = attributes = {}
#attributes.id ||= label.underscore.strip.gsub(/[_\s]+/, config.separator) if label.present?
delete attributes.index
delete attributes.parentIndex
delete attributes.label
@builder = new Tower.View.Form.Builder([],
template: @template
model: @model
attribute: @attribute
index: @index
parentIndex: @parentIndex
)
# form.inputs :basic_info, :locale_options => {:count => 1, :past => true}
render: (block) ->
@tag "fieldset", @attributes, =>
if @label
@tag "legend", class: Tower.View.legendClass, =>
@tag "span", @label
@tag Tower.View.fieldListTag, class: Tower.View.fieldListClass, =>
@builder.render(block)
Tower.View.ComponentHelper =
formFor: ->
Tower.View.Form.render(__ck, arguments...)
tableFor: ->
Tower.View.Table.render(__ck, arguments...)
widget: ->
linkTo: (title, path, options = {}) ->
a _.extend(options, href: path, title: title), title.toString()
Tower.View.ElementHelper =
title: (value) ->
document.title = value
addClass: (string, parts...) ->
classes = string.split(/\ +/)
for part in parts
classes.push(part) if classes.indexOf(part) > -1
classes.join(" ")
# @elementId @user, "form"
# #=> "#user-form"
#
# @elementId @user, "PI:NAME:<NAME>END_PI", "field"
# #=> "#user-first-name-field"
elementId: ->
"##{@elementKey(arguments...)}"
elementClass: ->
".#{@elementKey(arguments...)}"
elementKey: ->
Tower.Support.String.parameterize(@elementNameComponents(arguments...).join("-"))
# @elementName @user, "PI:NAME:<NAME>END_PI"
# #=> "user[firstName]"
#
# @elementName @user, "address", "city"
# #=> "user[address][city]"
elementName: ->
result = @elementNameComponents(arguments...)
i = 1
for item, i in result
result[i] = "[#{item}]"
Tower.Support.String.parameterize(result.join(""))
elementNameComponents: ->
args = Tower.Support.Array.args(arguments)
result = []
for item in args
switch typeof item
when "function"
result.push item.constructor.name
when "string"
result.push item
else
result.push item.toString()
result
for filter in ["stylus", "less", "markdown"]
@[filter] = (text) ->
Tower.View.render(text, filter: filter)
Tower.View.HeadHelper =
metaTag: (name, content) ->
meta name: name, content: content
snapshotLinkTag: (href) ->
linkTag rel: "imageSrc", href: href
html4ContentTypeTag: (charset = "UTF-8", type = "text/html") ->
httpMetaTag "Content-Type", "#{type}; charset=#{charset}"
chromeFrameTag: ->
html4ContentTypeTag()
meta "http-equiv": "X-UA-Compatible", content: "IE=Edge,chrome=1"
html5ContentTypeTag: (charset = "UTF-8") ->
meta charset: charset
contentTypeTag: (charset) ->
html5ContentTypeTag charset
csrfMetaTag: ->
metaTag "csrf-token", @request.session._csrf
searchLinkTag: (href, title) ->
linkTag rel: "search", type: "application/opensearchdescription+xml", href: href, title: title
faviconLinkTag: (favicon = "/favicon.ico") ->
linkTag rel: "shortcut icon", href: favicon, type: "image/x-icon"
linkTag: (options = {}) ->
link options
ieApplicationMetaTags: (title, options = {}) ->
result = []
result.push metaTag("application-name", title)
result.push metaTag("msapplication-tooltip", options.tooltip) if options.hasOwnProperty("tooltip")
result.push metaTag("msapplication-starturl", options.url) if options.hasOwnProperty("url")
if options.hasOwnProperty("width") && options.hasOwnProperty("height")
result.push metaTag("msapplication-window", "width=#{options.width};height=#{options.height}")
result.push metaTag("msapplication-navbutton-color", options.color) if options.hasOwnProperty("color")
result.join("\n")
ieTaskMetaTag: (name, path, icon = null) ->
content = []
content.push "name=#{name}"
content.push "uri=#{path}"
content.push "icon-uri=#{icon}" if icon
@metaTag "msapplication-task", content.join(";")
appleMetaTags: (options = {}) ->
result = []
result.push appleViewportMetaTag(options)
result.push appleFullScreenMetaTag(options.fullScreen) if options.hasOwnProperty("fullScreen")
result.push appleMobileCompatibleMetaTag(options.mobile) if options.hasOwnProperty("mobile")
result.join()
# http://www.html5rocks.com/en/mobile/mobifying.html
appleViewportMetaTag: (options = {}) ->
viewport = []
viewport.push "width=#{options.width}" if options.hasOwnProperty("width")
viewport.push "height=#{options.height}" if options.hasOwnProperty("height")
viewport.push "initial-scale=#{options.scale || 1.0}"
viewport.push "minimum-scale=#{options.min}" if options.hasOwnProperty("min")
viewport.push "maximum-scale=#{options.max}" if options.hasOwnProperty("max")
viewport.push "user-scalable=#{boolean(options.scalable)}" if options.hasOwnProperty("scalable")
metaTag "viewport", viewport.join(", ")
appleFullScreenMetaTag: (value) ->
metaTag "apple-touch-fullscreen", boolean(value)
appleMobileCompatibleMetaTag: (value) ->
metaTag "apple-mobile-web-app-capable", boolean(value)
appleTouchIconLinkTag: (path, options = {}) ->
rel = ["apple-touch-icon"]
rel.push "#{options.size}x#{options.size}" if options.hasOwnProperty("size")
rel.push "precomposed" if options.precomposed
linkTag rel: rel.join("-"), href: path
appleTouchIconLinkTags: (path, sizes...) ->
if typeof sizes[sizes.length - 1] == "object"
options = sizes.pop()
else
options = {}
result = []
for size in sizes
result.push appleTouchIconLinkTag(path, _.extend(size: size, options))
result.join()
openGraphMetaTags: (options = {}) ->
openGraphMetaTag("og:title", options.title) if options.title
openGraphMetaTag("og:type", options.type) if options.type
openGraphMetaTag("og:image", options.image) if options.image
openGraphMetaTag("og:siteName", options.site) if options.site
openGraphMetaTag("og:description", options.description) if options.description
openGraphMetaTag("og:email", options.email) if options.email
openGraphMetaTag("og:phoneNumber", options.phone) if options.phone
openGraphMetaTag("og:faxNumber", options.fax) if options.fax
openGraphMetaTag("og:latitude", options.lat) if options.lat
openGraphMetaTag("og:longitude", options.lng) if options.lng
openGraphMetaTag("og:street-address", options.street) if options.street
openGraphMetaTag("og:locality", options.city) if options.city
openGraphMetaTag("og:region", options.state) if options.state
openGraphMetaTag("og:postal-code", options.zip) if options.zip
openGraphMetaTag("og:country-name", options.country) if options.country
null
openGraphMetaTag: (property, content) ->
meta property: property, content: content
Tower.View.RenderingHelper =
partial: (path, options, callback) ->
try
if typeof options == "function"
callback = options
options = {}
options ||= {}
options.locals ||= {}
locals = options.locals
path = path.split("/")
path[path.length - 1] = "_#{path[path.length - 1]}"
path = path.join("/")
prefixes = options.prefixes
prefixes ||= [@_context.collectionName] if @_context
template = @_readTemplate(path, prefixes, options.type || Tower.View.engine)
template = @renderWithEngine(String(template))
if options.collection
name = options.as || Tower.Support.String.camelize(options.collection[0].constructor.name, true)
tmpl = eval "(function(data) { with(data) { this.#{name} = #{name}; #{String(template)} } })"
for item in options.collection
locals[name] = item
tmpl.call(@, locals)
delete @[name]
else
tmpl = "(function(data) { with(data) { #{String(template)} } })"
eval(tmpl).call(@, locals)
catch error
console.log error.stack || error
null
page: ->
args = Tower.Support.Array.args(arguments)
options = Tower.Support.Array.extractOptions(args)
browserTitle = args.shift() || options.title
@contentFor "title", ->
title browserTitle
urlFor: ->
Tower.urlFor(arguments...)
yields: (key) ->
value = @[key]
if typeof value == "function"
eval("(#{String(value)})()")
else
#__ck.indent()
ending = if value.match(/\n$/) then "\n" else ""
text(value.replace(/\n$/, "").replace(/^(?!\s+$)/mg, __ck.repeat(' ', __ck.tabs)) + ending)
null
hasContentFor: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
has: (key) ->
!!(@hasOwnProperty(key) && @[key] && @[key] != "")
contentFor: (key, block) ->
@[key] = block
null
Tower.View.StringHelper =
# Characters that need to be escaped to HTML entities from user input
HTML_ESCAPE:
'&': '&'
'<': '<'
'>': '>'
'"': '"'
"'": '''
preserve: (text) ->
text.replace(/\n/g, '
').replace(/\r/g, '')
htmlEscape: (text) ->
text.replace /[\"><&]/g, (_) => @HTML_ESCAPE[_]
t: (string) ->
Tower.Support.I18n.translate(string)
l: (object) ->
Tower.Support.I18n.localize(string)
boolean: (boolean) ->
if boolean then "yes" else "no"
|
[
{
"context": "ope', ($scope) ->\n $scope.persons = [\n name: 'green'\n age: 25\n createTime: '2012-10-10T06:11:32",
"end": 349,
"score": 0.9994710087776184,
"start": 344,
"tag": "NAME",
"value": "green"
},
{
"context": ": 13183284234\n money: 12.347878\n ,\n name: 'w... | src/filter/app.coffee | boiawang/angular-tutorial | 1 | angular.module 'app.filter', []
.filter 'orderAge', [() ->
return (persons) ->
return persons.sort (left, right) ->
a = left.age
b = right.age
if a isnt b
if a > b
return 1
if a < b
return -1
]
.controller 'FilterController', ['$scope', ($scope) ->
$scope.persons = [
name: 'green'
age: 25
createTime: '2012-10-10T06:11:32Z'
phone: 13183284234
money: 12.347878
,
name: 'wood'
age: 15
createTime: '2014-10-10T17:11:42Z'
phone: 13183284244
money: 23.48578
,
name: 'evan'
age: 35
createTime: '2013-11-03T16:15:02Z'
phone: 13183284264
money: 8.348777
,
name: 'jackson'
age: 17
createTime: '2013-12-01T06:11:32Z'
phone: 13183528092
money: 3.494588
,
name: 'clarke'
age: 33
createTime: '2012-08-03T11:11:11Z'
phone: 13182936347
money: 45.3874787
]
]
| 223610 | angular.module 'app.filter', []
.filter 'orderAge', [() ->
return (persons) ->
return persons.sort (left, right) ->
a = left.age
b = right.age
if a isnt b
if a > b
return 1
if a < b
return -1
]
.controller 'FilterController', ['$scope', ($scope) ->
$scope.persons = [
name: '<NAME>'
age: 25
createTime: '2012-10-10T06:11:32Z'
phone: 13183284234
money: 12.347878
,
name: '<NAME>'
age: 15
createTime: '2014-10-10T17:11:42Z'
phone: 13183284244
money: 23.48578
,
name: '<NAME>'
age: 35
createTime: '2013-11-03T16:15:02Z'
phone: 13183284264
money: 8.348777
,
name: '<NAME>'
age: 17
createTime: '2013-12-01T06:11:32Z'
phone: 13183528092
money: 3.494588
,
name: '<NAME>'
age: 33
createTime: '2012-08-03T11:11:11Z'
phone: 13182936347
money: 45.3874787
]
]
| true | angular.module 'app.filter', []
.filter 'orderAge', [() ->
return (persons) ->
return persons.sort (left, right) ->
a = left.age
b = right.age
if a isnt b
if a > b
return 1
if a < b
return -1
]
.controller 'FilterController', ['$scope', ($scope) ->
$scope.persons = [
name: 'PI:NAME:<NAME>END_PI'
age: 25
createTime: '2012-10-10T06:11:32Z'
phone: 13183284234
money: 12.347878
,
name: 'PI:NAME:<NAME>END_PI'
age: 15
createTime: '2014-10-10T17:11:42Z'
phone: 13183284244
money: 23.48578
,
name: 'PI:NAME:<NAME>END_PI'
age: 35
createTime: '2013-11-03T16:15:02Z'
phone: 13183284264
money: 8.348777
,
name: 'PI:NAME:<NAME>END_PI'
age: 17
createTime: '2013-12-01T06:11:32Z'
phone: 13183528092
money: 3.494588
,
name: 'PI:NAME:<NAME>END_PI'
age: 33
createTime: '2012-08-03T11:11:11Z'
phone: 13182936347
money: 45.3874787
]
]
|
[
{
"context": "##############################################\n#\n# Markus 1/23/2017\n#\n#####################################",
"end": 75,
"score": 0.9987528324127197,
"start": 69,
"tag": "NAME",
"value": "Markus"
}
] | server/methods/logging.coffee | agottschalk10/worklearn | 0 | ################################################################
#
# Markus 1/23/2017
#
################################################################
################################################################
Meteor.methods
log_navigation: (old_url, new_url) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(old_url) + "," + String(new_url)
log_event msg, event_navigation, event_info
log_action: (url, method) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(url) + "," + String(method)
log_event msg, event_general, event_info
log_user: () ->
headers = this.connection.httpHeaders
con_ip = String headers["x-forwarded-for"]
date = new Date()
user = this.userId
request = require('request')
con_ip = con_ip.split(",")[0]
url = 'http://ipinfo.io/' + con_ip + "/json"
call = Meteor.bindEnvironment (err, res, body) ->
if !err && res.statusCode == 200
try
ip = JSON.parse(body)
catch
ip = "unknown"
else
ip =
error: err
body: body
msg =
date: date
user: user
con_ip: con_ip
merge msg, headers
merge msg, ip
if err
msg["error"] = err
#store_document Logging, msg
log = JSON.stringify msg
log_event log, "login", event_info
request(url, call)
#user = if Meteor.userId() then "user: " + Meteor.userId() else "unknown user"
return true
| 66891 | ################################################################
#
# <NAME> 1/23/2017
#
################################################################
################################################################
Meteor.methods
log_navigation: (old_url, new_url) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(old_url) + "," + String(new_url)
log_event msg, event_navigation, event_info
log_action: (url, method) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(url) + "," + String(method)
log_event msg, event_general, event_info
log_user: () ->
headers = this.connection.httpHeaders
con_ip = String headers["x-forwarded-for"]
date = new Date()
user = this.userId
request = require('request')
con_ip = con_ip.split(",")[0]
url = 'http://ipinfo.io/' + con_ip + "/json"
call = Meteor.bindEnvironment (err, res, body) ->
if !err && res.statusCode == 200
try
ip = JSON.parse(body)
catch
ip = "unknown"
else
ip =
error: err
body: body
msg =
date: date
user: user
con_ip: con_ip
merge msg, headers
merge msg, ip
if err
msg["error"] = err
#store_document Logging, msg
log = JSON.stringify msg
log_event log, "login", event_info
request(url, call)
#user = if Meteor.userId() then "user: " + Meteor.userId() else "unknown user"
return true
| true | ################################################################
#
# PI:NAME:<NAME>END_PI 1/23/2017
#
################################################################
################################################################
Meteor.methods
log_navigation: (old_url, new_url) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(old_url) + "," + String(new_url)
log_event msg, event_navigation, event_info
log_action: (url, method) ->
user = get_profile_name_by_user_id this.userId
msg = user + "," + String(url) + "," + String(method)
log_event msg, event_general, event_info
log_user: () ->
headers = this.connection.httpHeaders
con_ip = String headers["x-forwarded-for"]
date = new Date()
user = this.userId
request = require('request')
con_ip = con_ip.split(",")[0]
url = 'http://ipinfo.io/' + con_ip + "/json"
call = Meteor.bindEnvironment (err, res, body) ->
if !err && res.statusCode == 200
try
ip = JSON.parse(body)
catch
ip = "unknown"
else
ip =
error: err
body: body
msg =
date: date
user: user
con_ip: con_ip
merge msg, headers
merge msg, ip
if err
msg["error"] = err
#store_document Logging, msg
log = JSON.stringify msg
log_event log, "login", event_info
request(url, call)
#user = if Meteor.userId() then "user: " + Meteor.userId() else "unknown user"
return true
|
[
{
"context": ": 'nikita/admin@DOMAIN.COM'\n kadmin_password: 'test'\n ldap:\n url: 'ldap://openldap.domain'\n bi",
"end": 1095,
"score": 0.9995602965354919,
"start": 1091,
"tag": "PASSWORD",
"value": "test"
},
{
"context": "'\n binddn: 'cn=manager,cn=config'\n passwd:... | packages/core/test.sample.coffee | chibanemourad/node-nikita | 0 |
module.exports =
scratch: '/tmp/nikita-test-core'
tags:
api: true
api_if_os: false # disable_conditions_if_os
conditions_if_os: false
cron: false # disable_cron
db: false # disable_db
docker: false # disable_docker
docker_volume: false
krb5_addprinc: false
krb5_delprinc: false
krb5_ktadd: false
ldap_acl: false
ldap_index: false
ldap_user: false
posix: true
rubygem: false # disable_tools_rubygems
service_install: false
service_startup: false
service_systemctl: false
sudo: false
system_authconfig: false
system_chmod: false
system_cgroups: false
system_discover: false
system_execute_arc_chroot: false
system_info: false
system_limits: false
system_tmpfs: false
tools_repo: false
tools_rubygems: false
system_user: false
yum_conf: false
docker: # eg `docker-machine create --driver virtualbox nikita`
machine: 'nikita'
krb5:
realm: 'DOMAIN.COM'
kadmin_server: 'domain.com'
kadmin_principal: 'nikita/admin@DOMAIN.COM'
kadmin_password: 'test'
ldap:
url: 'ldap://openldap.domain'
binddn: 'cn=manager,cn=config'
passwd: 'test'
suffix_dn: 'ou=users,dc=domain,dc=com' # used by ldap_user
ssh: [
null
,
ssh: host: '127.0.0.1', username: process.env.USER
# no password, will use private key
# if found in "~/.ssh/id_rsa"
]
| 34305 |
module.exports =
scratch: '/tmp/nikita-test-core'
tags:
api: true
api_if_os: false # disable_conditions_if_os
conditions_if_os: false
cron: false # disable_cron
db: false # disable_db
docker: false # disable_docker
docker_volume: false
krb5_addprinc: false
krb5_delprinc: false
krb5_ktadd: false
ldap_acl: false
ldap_index: false
ldap_user: false
posix: true
rubygem: false # disable_tools_rubygems
service_install: false
service_startup: false
service_systemctl: false
sudo: false
system_authconfig: false
system_chmod: false
system_cgroups: false
system_discover: false
system_execute_arc_chroot: false
system_info: false
system_limits: false
system_tmpfs: false
tools_repo: false
tools_rubygems: false
system_user: false
yum_conf: false
docker: # eg `docker-machine create --driver virtualbox nikita`
machine: 'nikita'
krb5:
realm: 'DOMAIN.COM'
kadmin_server: 'domain.com'
kadmin_principal: 'nikita/admin@DOMAIN.COM'
kadmin_password: '<PASSWORD>'
ldap:
url: 'ldap://openldap.domain'
binddn: 'cn=manager,cn=config'
passwd: '<PASSWORD>'
suffix_dn: 'ou=users,dc=domain,dc=com' # used by ldap_user
ssh: [
null
,
ssh: host: '127.0.0.1', username: process.env.USER
# no password, will use private key
# if found in "~/.ssh/id_rsa"
]
| true |
module.exports =
scratch: '/tmp/nikita-test-core'
tags:
api: true
api_if_os: false # disable_conditions_if_os
conditions_if_os: false
cron: false # disable_cron
db: false # disable_db
docker: false # disable_docker
docker_volume: false
krb5_addprinc: false
krb5_delprinc: false
krb5_ktadd: false
ldap_acl: false
ldap_index: false
ldap_user: false
posix: true
rubygem: false # disable_tools_rubygems
service_install: false
service_startup: false
service_systemctl: false
sudo: false
system_authconfig: false
system_chmod: false
system_cgroups: false
system_discover: false
system_execute_arc_chroot: false
system_info: false
system_limits: false
system_tmpfs: false
tools_repo: false
tools_rubygems: false
system_user: false
yum_conf: false
docker: # eg `docker-machine create --driver virtualbox nikita`
machine: 'nikita'
krb5:
realm: 'DOMAIN.COM'
kadmin_server: 'domain.com'
kadmin_principal: 'nikita/admin@DOMAIN.COM'
kadmin_password: 'PI:PASSWORD:<PASSWORD>END_PI'
ldap:
url: 'ldap://openldap.domain'
binddn: 'cn=manager,cn=config'
passwd: 'PI:PASSWORD:<PASSWORD>END_PI'
suffix_dn: 'ou=users,dc=domain,dc=com' # used by ldap_user
ssh: [
null
,
ssh: host: '127.0.0.1', username: process.env.USER
# no password, will use private key
# if found in "~/.ssh/id_rsa"
]
|
[
{
"context": "ame: 'Cookinseln'},\r\n {value: 'CR', name: 'Costa Rica'},\r\n {value: 'CI', name: 'Cote d\\'Ivoire'}",
"end": 3358,
"score": 0.7162541151046753,
"start": 3348,
"tag": "NAME",
"value": "Costa Rica"
},
{
"context": "me: 'Costa Rica'},\r\n {value: 'CI... | coffeescripts/donate.coffee | MaziarBarzi/DTTextField | 0 | window.donateController = ['$scope', '$stateParams', '$translate', '$state', '$http',
($scope, $stateParams, $translate, $state, $http) ->
#Payment Intervals
$scope.paymentIntervals = [
{id: 1, name: 'DONATE_INTERVAL_ONCE'},
{id: 2, name: 'DONATE_INTERVAL_MONTHLY'},
{id: 3, name: 'DONATE_INTERVAL_QUARTERLY'},
{id: 4, name: 'DONATE_INTERVAL_HALFYEAR'},
{id: 5, name: 'DONATE_INTERVAL_YEARLY'}
]
# Payment Reason
$scope.paymentReasons = [
{id: 1, name: 'PROJECTS_WORLD_WIDE'},
{id: 2, name: 'PROJECTS_FLORA'},
{id: 3, name: 'PROJECTS_WATER'},
{id: 4, name: 'PROJECTS_FAUNA'},
{id: 5, name: 'PROJECTS_DISASTER_PREVENTION'}
{id: 6, name: 'PROJECTS_CLIMATE_CHANGE'}
{id: 7, name: 'PROJECTS_NUTRITION'}
{id: 8, name: 'PROJECTS_COUNSELING'}
{id: 9, name: 'PROJECTS_EDUCATION'}
{id: 10, name: 'PROJECTS_RESEARCH'}
{id: 11, name: 'PROJECTS_REFUGEE_AID'}
{id: 12, name: 'PROJECTS_HEALTH'}
]
# Donate as
$scope.donateAsItems = [
{id: 1, name: 'DONATE_DONATE_AS_PRIVATE'},
{id: 2, name: 'DONATE_DONATE_AS_COMPANY'},
{id: 3, name: 'DONATE_DONATE_AS_CONGREGATION'},
{id: 4, name: 'DONATE_DONATE_AS_SCHOOL'}
]
# Title
$scope.titles = [
{id: 1, name: 'DONATE_DONATOR_TITLE_MR'},
{id: 2, name: 'DONATE_DONATOR_TITLE_MRS'},
{id: 3, name: 'DONATE_DONATOR_TITLE_MR_AND_MRS'}
]
countries =
'de': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Ägypten'},
{value: 'AX', name: 'Aland'},
{value: 'AL', name: 'Albanien'},
{value: 'DZ', name: 'Algerien'},
{value: 'AS', name: 'Amerikanisch-Samoa'},
{value: 'VI', name: 'Amerikanische Jungferninseln'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarktis'},
{value: 'AG', name: 'Antigua und Barbuda'},
{value: 'GQ', name: 'Äquatorialguinea'},
{value: 'AR', name: 'Argentinien'},
{value: 'AM', name: 'Armenien'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Aserbaidschan'},
{value: 'ET', name: 'Äthiopien'},
{value: 'AU', name: 'Australien'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesch'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgien'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivien'},
{value: 'BA', name: 'Bosnien und Herzegowina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvetinsel'},
{value: 'BR', name: 'Brasilien'},
{value: 'BN', name: 'Brunei'},
{value: 'BG', name: 'Bulgarien'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cookinseln'},
{value: 'CR', name: 'Costa Rica'},
{value: 'CI', name: 'Cote d\'Ivoire'},
{value: 'DK', name: 'Dänemark'},
{value: 'DE', name: 'Deutschland'},
{value: 'DG', name: 'Diego Garcia'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominikanische Republik'},
{value: 'DJ', name: 'Dschibuti'},
{value: 'EC', name: 'Ecuador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estland'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falklandinseln'},
{value: 'FO', name: 'Färöer'},
{value: 'FJ', name: 'Fidschi'},
{value: 'FI', name: 'Finnland'},
{value: 'FR', name: 'Frankreich'},
{value: 'GF', name: 'Französisch-Guayana'},
{value: 'PF', name: 'Französisch-Polynesien'},
{value: 'GA', name: 'Gabun'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgien'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Griechenland'},
{value: 'GL', name: 'Grönland'},
{value: 'GB', name: 'Großbritannien'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-Bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: 'Heard und McDonaldinseln'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hongkong'},
{value: 'IN', name: 'Indien'},
{value: 'ID', name: 'Indonesien'},
{value: 'IQ', name: 'Irak'},
{value: 'IR', name: 'Iran'},
{value: 'IE', name: 'Irland'},
{value: 'IS', name: 'Island'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italien'},
{value: 'JM', name: 'Jamaika'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Jemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordanien'},
{value: 'KY', name: 'Kaimaninseln'},
{value: 'KH', name: 'Kambodscha'},
{value: 'CM', name: 'Kamerun'},
{value: 'CA', name: 'Kanada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: 'Kap Verde'},
{value: 'KZ', name: 'Kasachstan'},
{value: 'QA', name: 'Katar'},
{value: 'KE', name: 'Kenia'},
{value: 'KG', name: 'Kirgisistan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Kokosinseln'},
{value: 'CO', name: 'Kolumbien'},
{value: 'KM', name: 'Komoren'},
{value: 'CG', name: 'Kongo'},
{value: 'HR', name: 'Kroatien'},
{value: 'CU', name: 'Kuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Laos'},
{value: 'LS', name: 'Lesotho'},
{value: 'LV', name: 'Lettland'},
{value: 'LB', name: 'Libanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyen'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Litauen'},
{value: 'LU', name: 'Luxemburg'},
{value: 'MO', name: 'Macao'},
{value: 'MG', name: 'Madagaskar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: 'Malediven'},
{value: 'ML', name: 'Mali'},
{value: 'MT', name: 'Malta'},
{value: 'MA', name: 'Marokko'},
{value: 'MH', name: 'Marshallinseln'},
{value: 'MQ', name: 'Martinique'},
{value: 'MR', name: 'Mauretanien'},
{value: 'MU', name: 'Mauritius'},
{value: 'YT', name: 'Mayotte'},
{value: 'MK', name: 'Mazedonien'},
{value: 'MX', name: 'Mexiko'},
{value: 'FM', name: 'Mikronesien'},
{value: 'MD', name: 'Moldawien'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolei'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mosambik'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'Neukaledonien'},
{value: 'NZ', name: 'Neuseeland'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Niederlande'},
{value: 'AN', name: 'Niederländische Antillen'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'Nordkorea'},
{value: 'MP', name: 'Nördliche Marianen'},
{value: 'NF', name: 'Norfolkinsel'},
{value: 'NO', name: 'Norwegen'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Österreich'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palästina'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua-Neuguinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippinen'},
{value: 'PN', name: 'Pitcairninseln'},
{value: 'PL', name: 'Polen'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'Réunion'},
{value: 'RW', name: 'Ruanda'},
{value: 'RO', name: 'Rumänien'},
{value: 'RU', name: 'Russische Föderation'},
{value: 'SB', name: 'Salomonen'},
{value: 'ZM', name: 'Sambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'São Tomé und Príncipe'},
{value: 'SA', name: 'Saudi-Arabien'},
{value: 'SE', name: 'Schweden'},
{value: 'CH', name: 'Schweiz'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychellen'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Simbabwe'},
{value: 'SG', name: 'Singapur'},
{value: 'SK', name: 'Slowakei'},
{value: 'SI', name: 'Slowenien'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spanien'},
{value: 'LK', name: 'Sri Lanka'},
{value: 'SH', name: 'St. Helena'},
{value: 'KN', name: 'St. Kitts und Nevis'},
{value: 'LC', name: 'St. Lucia'},
{value: 'PM', name: 'St. Pierre und Miquelon'},
{value: 'VC', name: 'St. Vincent/Grenadinen (GB)'},
{value: 'ZA', name: 'Südafrika, Republik'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'Südkorea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'Svalbard und Jan Mayen'},
{value: 'SZ', name: 'Swasiland'},
{value: 'SY', name: 'Syrien'},
{value: 'TJ', name: 'Tadschikistan'},
{value: 'TW', name: 'Taiwan'},
{value: 'TZ', name: 'Tansania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-Leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad und Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Tschad'},
{value: 'CZ', name: 'Tschechische Republik'},
{value: 'TN', name: 'Tunesien'},
{value: 'TR', name: 'Türkei'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks- und Caicosinseln'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Ungarn'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Usbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Vatikanstadt'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'Vereinigte Arabische Emirate'},
{value: 'US', name: 'Vereinigte Staaten von Amerika'},
{value: 'VN', name: 'Vietnam'},
{value: 'WF', name: 'Wallis und Futuna'},
{value: 'CX', name: 'Weihnachtsinsel'},
{value: 'BY', name: 'Weißrussland'},
{value: 'EH', name: 'Westsahara'},
{value: 'CF', name: 'Zentralafrikanische Republik'},
{value: 'CY', name: 'Zypern'}
]
'en': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Egypt'},
{value: 'AX', name: 'Åland Islands'},
{value: 'AL', name: 'Albania'},
{value: 'DZ', name: 'Algeria'},
{value: 'AS', name: 'American Samoa'},
{value: 'VI', name: 'Virgin Islands, U.s.'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarctica'},
{value: 'AG', name: 'Antigua And Barbuda'},
{value: 'GQ', name: 'Equatorial Guinea'},
{value: 'AR', name: 'Argentina'},
{value: 'AM', name: 'Armenia'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Azerbaijan'},
{value: 'ET', name: 'Ethiopia'},
{value: 'AU', name: 'Australia'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesh'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgium'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivia'},
{value: 'BA', name: 'Bosnia And Herzegovina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvet Island'},
{value: 'BR', name: 'Brazil'},
{value: 'BN', name: 'Brunei Darussalam'},
{value: 'BG', name: 'Bulgaria'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cook Islands'},
{value: 'CR', name: 'Costa Rica'},
{value: 'CI', name: 'CÔte D\'ivoire'},
{value: 'DK', name: 'Denmark'},
{value: 'DE', name: 'Germany'},
{value: 'DG', name: 'Diego Garcia'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominican Republic'},
{value: 'DJ', name: 'Djibouti'},
{value: 'EC', name: 'Ecuador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estonia'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falkland Islands (malvinas)'},
{value: 'FO', name: 'Faroe Islands'},
{value: 'FJ', name: 'Fiji'},
{value: 'FI', name: 'Finland'},
{value: 'FR', name: 'France'},
{value: 'GF', name: 'French Guiana'},
{value: 'PF', name: 'French Polynesia'},
{value: 'GA', name: 'Gabon'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgia'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Greece'},
{value: 'GL', name: 'Greenland'},
{value: 'GB', name: 'Create Britain'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: 'Heard Island And Mcdonald Islands'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hong Kong'},
{value: 'IN', name: 'India'},
{value: 'ID', name: 'Indonesia'},
{value: 'IQ', name: 'Iraq'},
{value: 'IR', name: 'Iran, Islamic Republic Of'},
{value: 'IE', name: 'Ireland'},
{value: 'IS', name: 'Iceland'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italy'},
{value: 'JM', name: 'Jamaica'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Yemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordan'},
{value: 'KY', name: 'Cayman Islands'},
{value: 'KH', name: 'Cambodia'},
{value: 'CM', name: 'Cameroon'},
{value: 'CA', name: 'Canada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: 'Cape Verde'},
{value: 'KZ', name: 'Kazakhstan'},
{value: 'QA', name: 'Qatar'},
{value: 'KE', name: 'Kenya'},
{value: 'KG', name: 'Kyrgyzstan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Cocos (keeling) Islands'},
{value: 'CO', name: 'Colombia'},
{value: 'KM', name: 'Comoros'},
{value: 'CG', name: 'Congo'},
{value: 'HR', name: 'Croatia'},
{value: 'CU', name: 'Cuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Lao People\'s Democratic Republic'},
{value: 'LS', name: 'Lesotho'},
{value: 'LV', name: 'Latvia'},
{value: 'LB', name: 'Lebanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyan Arab Jamahiriya'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Lithuania'},
{value: 'LU', name: 'Luxembourg'},
{value: 'MO', name: 'Macao'},
{value: 'MG', name: 'Madagascar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: 'Maldives'},
{value: 'ML', name: 'Mali'},
{value: 'MT', name: 'Malta'},
{value: 'MA', name: 'Morocco'},
{value: 'MH', name: 'Marshall Islands'},
{value: 'MQ', name: 'Martinique'},
{value: 'MR', name: 'Mauritania'},
{value: 'MU', name: 'Mauritius'},
{value: 'YT', name: 'Mayotte'},
{value: 'MK', name: 'Macedonia, The Former Yugoslav Republic Of'},
{value: 'MX', name: 'Mexico'},
{value: 'FM', name: 'Micronesia'},
{value: 'MD', name: 'Moldova'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolia'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mozambique'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'New Caledonia'},
{value: 'NZ', name: 'New Zealand'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Netherlands'},
{value: 'AN', name: 'Netherlands Antilles'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'North Korea'},
{value: 'MP', name: 'Northern Mariana Islands'},
{value: 'NF', name: 'Norfolk Island'},
{value: 'NO', name: 'Norway'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Austria'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palestinian Territory'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua New Guinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippines'},
{value: 'PN', name: 'Pitcairn'},
{value: 'PL', name: 'Poland'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'RÉunion'},
{value: 'RW', name: 'Rwanda'},
{value: 'RO', name: 'Romania'},
{value: 'RU', name: 'Russian Federation'},
{value: 'SB', name: 'Solomon Islands'},
{value: 'ZM', name: 'Zambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'Sao Tome And Principe'},
{value: 'SA', name: 'Saudi Arabia'},
{value: 'SE', name: 'Sweden'},
{value: 'CH', name: 'Switzerland'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychelles'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Zimbabwe'},
{value: 'SG', name: 'Singapore'},
{value: 'SK', name: 'Slovakia'},
{value: 'SI', name: 'Slovenia'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spain'},
{value: 'LK', name: 'Sri Lanka'},
{value: 'SH', name: 'Saint Helena'},
{value: 'KN', name: 'Saint Kitts And Nevis'},
{value: 'LC', name: 'Saint Lucia'},
{value: 'PM', name: 'Saint Pierre And Miquelon'},
{value: 'VC', name: 'Saint Vincent/Grenadines'},
{value: 'ZA', name: 'South Africa'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'South Korea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'Svalbard And Jan Mayen'},
{value: 'SZ', name: 'Swaziland'},
{value: 'SY', name: 'Syrian Arab Republic'},
{value: 'TJ', name: 'Tajikistan'},
{value: 'TW', name: 'Taiwan, Province Of China'},
{value: 'TZ', name: 'Tanzania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad And Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Chad'},
{value: 'CZ', name: 'Czech Republic'},
{value: 'TN', name: 'Tunisia'},
{value: 'TR', name: 'Turkey'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks And Caicos Islands'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Hungary'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Uzbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Holy See (vatican City State)'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'United Arab Emirates'},
{value: 'US', name: 'United States'},
{value: 'VN', name: 'Viet Nam'},
{value: 'WF', name: 'Wallis And Futuna'},
{value: 'CX', name: 'Christmas Island'},
{value: 'BY', name: 'Belarus'},
{value: 'EH', name: 'Western Sahara'},
{value: 'CF', name: 'Central African Republic'},
{value: 'CY', name: 'Cyprus'}
]
$scope.currentPage = $state.current.name;
$scope.donate = {}
$scope.record = {}
$scope.donate.donator = {};
$scope.donate.donator.address = {};
$scope.donate.paymentInterval = $scope.paymentIntervals[0]
$scope.donate.paymentReason = $scope.paymentReasons[0]
$scope.donate.donateAs = $scope.donateAsItems[0]
$scope.donate.donator.title = $scope.titles[0]
if ($scope.donate.paymentValue != undefined && $scope.donate.paymentValue < 0)
$scope.donate.paymentValue = Math.abs($scope.donate.paymentValue)
$scope.translateComboBoxes = -> (
_.map($scope.paymentIntervals, (paymentInterval, id) ->
$translate(paymentInterval.name).then((text) ->
paymentInterval.name = text
return
)
)
_.map($scope.paymentReasons, (paymentReason, id) ->
$translate(paymentReason.name).then((text) ->
paymentReason.name = text
return
)
)
_.map($scope.donateAsItems, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
_.map($scope.titles, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
currentLanguage = $translate.proposedLanguage() || $translate.use()
$scope.countries = countries[currentLanguage]
$scope.donate.language = currentLanguage
$scope.donate.donator.address.country = _.first(_.filter(countries.de, (c) ->
c.value == 'DE'
))
return
)
$scope.validateStep = ($event) -> (
if !$('.payment-form').isValid({'de', 'en'}, $.formUtils.defaultConfig(), true)
$event.preventDefault()
return false
return true
)
$scope.validateStep1 = ($event) -> (
if (! $scope.validateStep($event))
$event.preventDefault()
return
$event.preventDefault()
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/checkcard.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
$state.go('root.donate.step2', $stateParams, {reload: false});
return
return true
)
$scope.processForm = () -> (
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/process.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
# if successful, bind success message to message
$('#confirm-dialog').modal('show');
return
)
$scope.translateComboBoxes()
return
]
| 205776 | window.donateController = ['$scope', '$stateParams', '$translate', '$state', '$http',
($scope, $stateParams, $translate, $state, $http) ->
#Payment Intervals
$scope.paymentIntervals = [
{id: 1, name: 'DONATE_INTERVAL_ONCE'},
{id: 2, name: 'DONATE_INTERVAL_MONTHLY'},
{id: 3, name: 'DONATE_INTERVAL_QUARTERLY'},
{id: 4, name: 'DONATE_INTERVAL_HALFYEAR'},
{id: 5, name: 'DONATE_INTERVAL_YEARLY'}
]
# Payment Reason
$scope.paymentReasons = [
{id: 1, name: 'PROJECTS_WORLD_WIDE'},
{id: 2, name: 'PROJECTS_FLORA'},
{id: 3, name: 'PROJECTS_WATER'},
{id: 4, name: 'PROJECTS_FAUNA'},
{id: 5, name: 'PROJECTS_DISASTER_PREVENTION'}
{id: 6, name: 'PROJECTS_CLIMATE_CHANGE'}
{id: 7, name: 'PROJECTS_NUTRITION'}
{id: 8, name: 'PROJECTS_COUNSELING'}
{id: 9, name: 'PROJECTS_EDUCATION'}
{id: 10, name: 'PROJECTS_RESEARCH'}
{id: 11, name: 'PROJECTS_REFUGEE_AID'}
{id: 12, name: 'PROJECTS_HEALTH'}
]
# Donate as
$scope.donateAsItems = [
{id: 1, name: 'DONATE_DONATE_AS_PRIVATE'},
{id: 2, name: 'DONATE_DONATE_AS_COMPANY'},
{id: 3, name: 'DONATE_DONATE_AS_CONGREGATION'},
{id: 4, name: 'DONATE_DONATE_AS_SCHOOL'}
]
# Title
$scope.titles = [
{id: 1, name: 'DONATE_DONATOR_TITLE_MR'},
{id: 2, name: 'DONATE_DONATOR_TITLE_MRS'},
{id: 3, name: 'DONATE_DONATOR_TITLE_MR_AND_MRS'}
]
countries =
'de': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Ägypten'},
{value: 'AX', name: 'Aland'},
{value: 'AL', name: 'Albanien'},
{value: 'DZ', name: 'Algerien'},
{value: 'AS', name: 'Amerikanisch-Samoa'},
{value: 'VI', name: 'Amerikanische Jungferninseln'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarktis'},
{value: 'AG', name: 'Antigua und Barbuda'},
{value: 'GQ', name: 'Äquatorialguinea'},
{value: 'AR', name: 'Argentinien'},
{value: 'AM', name: 'Armenien'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Aserbaidschan'},
{value: 'ET', name: 'Äthiopien'},
{value: 'AU', name: 'Australien'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesch'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgien'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivien'},
{value: 'BA', name: 'Bosnien und Herzegowina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvetinsel'},
{value: 'BR', name: 'Brasilien'},
{value: 'BN', name: 'Brunei'},
{value: 'BG', name: 'Bulgarien'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cookinseln'},
{value: 'CR', name: '<NAME>'},
{value: 'CI', name: 'C<NAME> d\'I<NAME>ire'},
{value: 'DK', name: 'Dänemark'},
{value: 'DE', name: 'Deutschland'},
{value: 'DG', name: '<NAME>'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominikanische Republik'},
{value: 'DJ', name: 'D<NAME>'},
{value: 'EC', name: 'E<NAME>ador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estland'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falklandinseln'},
{value: 'FO', name: '<NAME>'},
{value: 'FJ', name: '<NAME>'},
{value: 'FI', name: 'Finnland'},
{value: 'FR', name: 'Frankreich'},
{value: 'GF', name: 'Französisch-Guayana'},
{value: 'PF', name: 'Französisch-Polynesien'},
{value: 'GA', name: '<NAME>abun'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgien'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Griechenland'},
{value: 'GL', name: 'Grönland'},
{value: 'GB', name: 'Großbritannien'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-Bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: '<NAME>'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hongkong'},
{value: 'IN', name: 'Indien'},
{value: 'ID', name: 'Indonesien'},
{value: 'IQ', name: 'Irak'},
{value: 'IR', name: 'Iran'},
{value: 'IE', name: 'Irland'},
{value: 'IS', name: 'Island'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italien'},
{value: 'JM', name: 'Jamaika'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Jemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordanien'},
{value: 'KY', name: 'Kaimaninseln'},
{value: 'KH', name: 'Kambodscha'},
{value: 'CM', name: 'Kamerun'},
{value: 'CA', name: 'Kanada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: '<NAME>'},
{value: 'KZ', name: 'Kasachstan'},
{value: 'QA', name: 'Katar'},
{value: 'KE', name: 'Kenia'},
{value: 'KG', name: 'Kirgisistan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Kokosinseln'},
{value: 'CO', name: 'Kolumbien'},
{value: 'KM', name: 'Komoren'},
{value: 'CG', name: 'Kongo'},
{value: 'HR', name: 'Kroatien'},
{value: 'CU', name: 'Kuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Laos'},
{value: 'LS', name: '<NAME>o'},
{value: 'LV', name: 'Lettland'},
{value: 'LB', name: 'Libanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyen'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Litauen'},
{value: 'LU', name: 'Luxemburg'},
{value: 'MO', name: '<NAME>'},
{value: 'MG', name: '<NAME>agaskar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: '<NAME>'},
{value: 'ML', name: '<NAME>ali'},
{value: 'MT', name: '<NAME>'},
{value: 'MA', name: '<NAME>'},
{value: 'MH', name: '<NAME>'},
{value: 'MQ', name: '<NAME>'},
{value: 'MR', name: '<NAME>'},
{value: 'MU', name: '<NAME>'},
{value: 'YT', name: '<NAME>'},
{value: 'MK', name: 'M<NAME>'},
{value: 'MX', name: 'Mexiko'},
{value: 'FM', name: 'Mikronesien'},
{value: 'MD', name: 'Moldawien'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolei'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mosambik'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'Neukaledonien'},
{value: 'NZ', name: 'Neuseeland'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Niederlande'},
{value: 'AN', name: 'Niederländische Antillen'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'Nordkorea'},
{value: 'MP', name: 'Nördliche Marianen'},
{value: 'NF', name: 'Norfolkinsel'},
{value: 'NO', name: 'Norwegen'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Österreich'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palästina'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua-Neuguinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippinen'},
{value: 'PN', name: 'Pitcair<NAME>'},
{value: 'PL', name: 'Polen'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'Réunion'},
{value: 'RW', name: 'Ruanda'},
{value: 'RO', name: 'Rumänien'},
{value: 'RU', name: 'Russische Föderation'},
{value: 'SB', name: 'Salomonen'},
{value: 'ZM', name: 'Sambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'São Tomé und Príncipe'},
{value: 'SA', name: 'Saudi-Arabien'},
{value: 'SE', name: 'Schweden'},
{value: 'CH', name: 'Schweiz'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychellen'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Simbabwe'},
{value: 'SG', name: 'Singapur'},
{value: 'SK', name: 'Slowakei'},
{value: 'SI', name: 'Slowenien'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spanien'},
{value: 'LK', name: 'S<NAME> L<NAME>a'},
{value: 'SH', name: 'St. Helena'},
{value: 'KN', name: 'St. Kitts und Nevis'},
{value: 'LC', name: 'St. Lucia'},
{value: 'PM', name: 'St. Pierre und Miquelon'},
{value: 'VC', name: 'St. Vincent/Grenadinen (GB)'},
{value: 'ZA', name: 'Südafrika, Republik'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'Südkorea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'S<NAME>ard und <NAME>'},
{value: 'SZ', name: 'Swasiland'},
{value: 'SY', name: 'Syrien'},
{value: 'TJ', name: 'Tadschikistan'},
{value: 'TW', name: 'Taiwan'},
{value: 'TZ', name: 'Tansania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-Leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad und Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Tschad'},
{value: 'CZ', name: 'Tschechische Republik'},
{value: 'TN', name: 'Tunesien'},
{value: 'TR', name: 'Türkei'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks- und Caicosinseln'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Ungarn'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Usbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Vatikanstadt'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'Vereinigte Arabische Emirate'},
{value: 'US', name: 'Vereinigte Staaten von Amerika'},
{value: 'VN', name: 'Vietnam'},
{value: 'WF', name: 'Wallis und Futuna'},
{value: 'CX', name: 'Weihnachtsinsel'},
{value: 'BY', name: 'Weißrussland'},
{value: 'EH', name: 'Westsahara'},
{value: 'CF', name: 'Zentralafrikanische Republik'},
{value: 'CY', name: 'Z<NAME>n'}
]
'en': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Egypt'},
{value: 'AX', name: 'Åland Islands'},
{value: 'AL', name: 'Albania'},
{value: 'DZ', name: 'Algeria'},
{value: 'AS', name: 'American Samoa'},
{value: 'VI', name: 'Virgin Islands, U.s.'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarctica'},
{value: 'AG', name: 'Antigua And Barbuda'},
{value: 'GQ', name: 'Equatorial Guinea'},
{value: 'AR', name: 'Argentina'},
{value: 'AM', name: 'Armenia'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Azerbaijan'},
{value: 'ET', name: 'Ethiopia'},
{value: 'AU', name: 'Australia'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesh'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgium'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivia'},
{value: 'BA', name: 'Bosnia And Herzegovina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvet Island'},
{value: 'BR', name: 'Brazil'},
{value: 'BN', name: 'Brunei Darussalam'},
{value: 'BG', name: 'Bulgaria'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cook Islands'},
{value: 'CR', name: 'Costa Rica'},
{value: 'CI', name: '<NAME>\'<NAME>'},
{value: 'DK', name: 'Denmark'},
{value: 'DE', name: 'Germany'},
{value: 'DG', name: '<NAME>'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominican Republic'},
{value: 'DJ', name: 'Djibouti'},
{value: 'EC', name: 'Ecuador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estonia'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falkland Islands (malvinas)'},
{value: 'FO', name: 'Faroe Islands'},
{value: 'FJ', name: 'Fiji'},
{value: 'FI', name: 'Finland'},
{value: 'FR', name: 'France'},
{value: 'GF', name: 'French Guiana'},
{value: 'PF', name: 'French Polynesia'},
{value: 'GA', name: 'Gabon'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgia'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Greece'},
{value: 'GL', name: 'Greenland'},
{value: 'GB', name: 'Create Britain'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: 'Heard Island And Mcdonald Islands'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hong Kong'},
{value: 'IN', name: 'India'},
{value: 'ID', name: 'Indonesia'},
{value: 'IQ', name: 'Iraq'},
{value: 'IR', name: 'Iran, Islamic Republic Of'},
{value: 'IE', name: 'Ireland'},
{value: 'IS', name: 'Iceland'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italy'},
{value: 'JM', name: 'Jamaica'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Yemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordan'},
{value: 'KY', name: 'Cayman Islands'},
{value: 'KH', name: 'Cambodia'},
{value: 'CM', name: 'Cameroon'},
{value: 'CA', name: 'Canada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: 'Cape Verde'},
{value: 'KZ', name: 'Kazakhstan'},
{value: 'QA', name: 'Qatar'},
{value: 'KE', name: 'Kenya'},
{value: 'KG', name: 'Kyrgyzstan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Cocos (keeling) Islands'},
{value: 'CO', name: 'Colombia'},
{value: 'KM', name: 'Comoros'},
{value: 'CG', name: 'Congo'},
{value: 'HR', name: 'Croatia'},
{value: 'CU', name: 'Cuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Lao People\'s Democratic Republic'},
{value: 'LS', name: 'Lesotho'},
{value: 'LV', name: 'Latvia'},
{value: 'LB', name: 'Lebanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyan Arab Jamahiriya'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Lithuania'},
{value: 'LU', name: 'Luxembourg'},
{value: 'MO', name: 'Macao'},
{value: 'MG', name: 'Madagascar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: 'Maldives'},
{value: 'ML', name: 'Mali'},
{value: 'MT', name: 'Malta'},
{value: 'MA', name: 'Morocco'},
{value: 'MH', name: 'Marshall Islands'},
{value: 'MQ', name: 'Martinique'},
{value: 'MR', name: 'Mauritania'},
{value: 'MU', name: 'Mauritius'},
{value: 'YT', name: 'Mayotte'},
{value: 'MK', name: 'Macedonia, The Former Yugoslav Republic Of'},
{value: 'MX', name: 'Mexico'},
{value: 'FM', name: 'Micronesia'},
{value: 'MD', name: 'Moldova'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolia'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mozambique'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'New Caledonia'},
{value: 'NZ', name: 'New Zealand'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Netherlands'},
{value: 'AN', name: 'Netherlands Antilles'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'North Korea'},
{value: 'MP', name: 'Northern Mariana Islands'},
{value: 'NF', name: 'Norfolk Island'},
{value: 'NO', name: 'Norway'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Austria'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palestinian Territory'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua New Guinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippines'},
{value: 'PN', name: 'Pitcairn'},
{value: 'PL', name: 'Poland'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'RÉunion'},
{value: 'RW', name: 'Rwanda'},
{value: 'RO', name: 'Romania'},
{value: 'RU', name: 'Russian Federation'},
{value: 'SB', name: 'Solomon Islands'},
{value: 'ZM', name: 'Zambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'Sao Tome And Principe'},
{value: 'SA', name: 'Saudi Arabia'},
{value: 'SE', name: 'Sweden'},
{value: 'CH', name: 'Switzerland'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychelles'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Zimbabwe'},
{value: 'SG', name: 'Singapore'},
{value: 'SK', name: 'Slovakia'},
{value: 'SI', name: 'Slovenia'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spain'},
{value: 'LK', name: 'Sri Lanka'},
{value: 'SH', name: '<NAME>'},
{value: 'KN', name: 'Saint Kitts And Nevis'},
{value: 'LC', name: 'Saint Lucia'},
{value: 'PM', name: 'Saint Pierre And Miquelon'},
{value: 'VC', name: 'Saint Vincent/Grenadines'},
{value: 'ZA', name: 'South Africa'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'South Korea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'Svalbard And Jan Mayen'},
{value: 'SZ', name: 'Swaziland'},
{value: 'SY', name: 'Syrian Arab Republic'},
{value: 'TJ', name: 'Tajikistan'},
{value: 'TW', name: 'Taiwan, Province Of China'},
{value: 'TZ', name: 'Tanzania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad And Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Chad'},
{value: 'CZ', name: 'Czech Republic'},
{value: 'TN', name: 'Tunisia'},
{value: 'TR', name: 'Turkey'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks And Caicos Islands'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Hungary'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Uzbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Holy See (vatican City State)'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'United Arab Emirates'},
{value: 'US', name: 'United States'},
{value: 'VN', name: 'Viet Nam'},
{value: 'WF', name: 'Wallis And Futuna'},
{value: 'CX', name: 'Christmas Island'},
{value: 'BY', name: 'Belarus'},
{value: 'EH', name: 'Western Sahara'},
{value: 'CF', name: 'Central African Republic'},
{value: 'CY', name: 'Cyprus'}
]
$scope.currentPage = $state.current.name;
$scope.donate = {}
$scope.record = {}
$scope.donate.donator = {};
$scope.donate.donator.address = {};
$scope.donate.paymentInterval = $scope.paymentIntervals[0]
$scope.donate.paymentReason = $scope.paymentReasons[0]
$scope.donate.donateAs = $scope.donateAsItems[0]
$scope.donate.donator.title = $scope.titles[0]
if ($scope.donate.paymentValue != undefined && $scope.donate.paymentValue < 0)
$scope.donate.paymentValue = Math.abs($scope.donate.paymentValue)
$scope.translateComboBoxes = -> (
_.map($scope.paymentIntervals, (paymentInterval, id) ->
$translate(paymentInterval.name).then((text) ->
paymentInterval.name = text
return
)
)
_.map($scope.paymentReasons, (paymentReason, id) ->
$translate(paymentReason.name).then((text) ->
paymentReason.name = text
return
)
)
_.map($scope.donateAsItems, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
_.map($scope.titles, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
currentLanguage = $translate.proposedLanguage() || $translate.use()
$scope.countries = countries[currentLanguage]
$scope.donate.language = currentLanguage
$scope.donate.donator.address.country = _.first(_.filter(countries.de, (c) ->
c.value == 'DE'
))
return
)
$scope.validateStep = ($event) -> (
if !$('.payment-form').isValid({'de', 'en'}, $.formUtils.defaultConfig(), true)
$event.preventDefault()
return false
return true
)
$scope.validateStep1 = ($event) -> (
if (! $scope.validateStep($event))
$event.preventDefault()
return
$event.preventDefault()
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/checkcard.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
$state.go('root.donate.step2', $stateParams, {reload: false});
return
return true
)
$scope.processForm = () -> (
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/process.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
# if successful, bind success message to message
$('#confirm-dialog').modal('show');
return
)
$scope.translateComboBoxes()
return
]
| true | window.donateController = ['$scope', '$stateParams', '$translate', '$state', '$http',
($scope, $stateParams, $translate, $state, $http) ->
#Payment Intervals
$scope.paymentIntervals = [
{id: 1, name: 'DONATE_INTERVAL_ONCE'},
{id: 2, name: 'DONATE_INTERVAL_MONTHLY'},
{id: 3, name: 'DONATE_INTERVAL_QUARTERLY'},
{id: 4, name: 'DONATE_INTERVAL_HALFYEAR'},
{id: 5, name: 'DONATE_INTERVAL_YEARLY'}
]
# Payment Reason
$scope.paymentReasons = [
{id: 1, name: 'PROJECTS_WORLD_WIDE'},
{id: 2, name: 'PROJECTS_FLORA'},
{id: 3, name: 'PROJECTS_WATER'},
{id: 4, name: 'PROJECTS_FAUNA'},
{id: 5, name: 'PROJECTS_DISASTER_PREVENTION'}
{id: 6, name: 'PROJECTS_CLIMATE_CHANGE'}
{id: 7, name: 'PROJECTS_NUTRITION'}
{id: 8, name: 'PROJECTS_COUNSELING'}
{id: 9, name: 'PROJECTS_EDUCATION'}
{id: 10, name: 'PROJECTS_RESEARCH'}
{id: 11, name: 'PROJECTS_REFUGEE_AID'}
{id: 12, name: 'PROJECTS_HEALTH'}
]
# Donate as
$scope.donateAsItems = [
{id: 1, name: 'DONATE_DONATE_AS_PRIVATE'},
{id: 2, name: 'DONATE_DONATE_AS_COMPANY'},
{id: 3, name: 'DONATE_DONATE_AS_CONGREGATION'},
{id: 4, name: 'DONATE_DONATE_AS_SCHOOL'}
]
# Title
$scope.titles = [
{id: 1, name: 'DONATE_DONATOR_TITLE_MR'},
{id: 2, name: 'DONATE_DONATOR_TITLE_MRS'},
{id: 3, name: 'DONATE_DONATOR_TITLE_MR_AND_MRS'}
]
countries =
'de': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Ägypten'},
{value: 'AX', name: 'Aland'},
{value: 'AL', name: 'Albanien'},
{value: 'DZ', name: 'Algerien'},
{value: 'AS', name: 'Amerikanisch-Samoa'},
{value: 'VI', name: 'Amerikanische Jungferninseln'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarktis'},
{value: 'AG', name: 'Antigua und Barbuda'},
{value: 'GQ', name: 'Äquatorialguinea'},
{value: 'AR', name: 'Argentinien'},
{value: 'AM', name: 'Armenien'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Aserbaidschan'},
{value: 'ET', name: 'Äthiopien'},
{value: 'AU', name: 'Australien'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesch'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgien'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivien'},
{value: 'BA', name: 'Bosnien und Herzegowina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvetinsel'},
{value: 'BR', name: 'Brasilien'},
{value: 'BN', name: 'Brunei'},
{value: 'BG', name: 'Bulgarien'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cookinseln'},
{value: 'CR', name: 'PI:NAME:<NAME>END_PI'},
{value: 'CI', name: 'CPI:NAME:<NAME>END_PI d\'IPI:NAME:<NAME>END_PIire'},
{value: 'DK', name: 'Dänemark'},
{value: 'DE', name: 'Deutschland'},
{value: 'DG', name: 'PI:NAME:<NAME>END_PI'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominikanische Republik'},
{value: 'DJ', name: 'DPI:NAME:<NAME>END_PI'},
{value: 'EC', name: 'EPI:NAME:<NAME>END_PIador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estland'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falklandinseln'},
{value: 'FO', name: 'PI:NAME:<NAME>END_PI'},
{value: 'FJ', name: 'PI:NAME:<NAME>END_PI'},
{value: 'FI', name: 'Finnland'},
{value: 'FR', name: 'Frankreich'},
{value: 'GF', name: 'Französisch-Guayana'},
{value: 'PF', name: 'Französisch-Polynesien'},
{value: 'GA', name: 'PI:NAME:<NAME>END_PIabun'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgien'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Griechenland'},
{value: 'GL', name: 'Grönland'},
{value: 'GB', name: 'Großbritannien'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-Bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: 'PI:NAME:<NAME>END_PI'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hongkong'},
{value: 'IN', name: 'Indien'},
{value: 'ID', name: 'Indonesien'},
{value: 'IQ', name: 'Irak'},
{value: 'IR', name: 'Iran'},
{value: 'IE', name: 'Irland'},
{value: 'IS', name: 'Island'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italien'},
{value: 'JM', name: 'Jamaika'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Jemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordanien'},
{value: 'KY', name: 'Kaimaninseln'},
{value: 'KH', name: 'Kambodscha'},
{value: 'CM', name: 'Kamerun'},
{value: 'CA', name: 'Kanada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: 'PI:NAME:<NAME>END_PI'},
{value: 'KZ', name: 'Kasachstan'},
{value: 'QA', name: 'Katar'},
{value: 'KE', name: 'Kenia'},
{value: 'KG', name: 'Kirgisistan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Kokosinseln'},
{value: 'CO', name: 'Kolumbien'},
{value: 'KM', name: 'Komoren'},
{value: 'CG', name: 'Kongo'},
{value: 'HR', name: 'Kroatien'},
{value: 'CU', name: 'Kuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Laos'},
{value: 'LS', name: 'PI:NAME:<NAME>END_PIo'},
{value: 'LV', name: 'Lettland'},
{value: 'LB', name: 'Libanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyen'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Litauen'},
{value: 'LU', name: 'Luxemburg'},
{value: 'MO', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MG', name: 'PI:NAME:<NAME>END_PIagaskar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: 'PI:NAME:<NAME>END_PI'},
{value: 'ML', name: 'PI:NAME:<NAME>END_PIali'},
{value: 'MT', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MA', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MH', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MQ', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MR', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MU', name: 'PI:NAME:<NAME>END_PI'},
{value: 'YT', name: 'PI:NAME:<NAME>END_PI'},
{value: 'MK', name: 'MPI:NAME:<NAME>END_PI'},
{value: 'MX', name: 'Mexiko'},
{value: 'FM', name: 'Mikronesien'},
{value: 'MD', name: 'Moldawien'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolei'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mosambik'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'Neukaledonien'},
{value: 'NZ', name: 'Neuseeland'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Niederlande'},
{value: 'AN', name: 'Niederländische Antillen'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'Nordkorea'},
{value: 'MP', name: 'Nördliche Marianen'},
{value: 'NF', name: 'Norfolkinsel'},
{value: 'NO', name: 'Norwegen'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Österreich'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palästina'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua-Neuguinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippinen'},
{value: 'PN', name: 'PitcairPI:NAME:<NAME>END_PI'},
{value: 'PL', name: 'Polen'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'Réunion'},
{value: 'RW', name: 'Ruanda'},
{value: 'RO', name: 'Rumänien'},
{value: 'RU', name: 'Russische Föderation'},
{value: 'SB', name: 'Salomonen'},
{value: 'ZM', name: 'Sambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'São Tomé und Príncipe'},
{value: 'SA', name: 'Saudi-Arabien'},
{value: 'SE', name: 'Schweden'},
{value: 'CH', name: 'Schweiz'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychellen'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Simbabwe'},
{value: 'SG', name: 'Singapur'},
{value: 'SK', name: 'Slowakei'},
{value: 'SI', name: 'Slowenien'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spanien'},
{value: 'LK', name: 'SPI:NAME:<NAME>END_PI LPI:NAME:<NAME>END_PIa'},
{value: 'SH', name: 'St. Helena'},
{value: 'KN', name: 'St. Kitts und Nevis'},
{value: 'LC', name: 'St. Lucia'},
{value: 'PM', name: 'St. Pierre und Miquelon'},
{value: 'VC', name: 'St. Vincent/Grenadinen (GB)'},
{value: 'ZA', name: 'Südafrika, Republik'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'Südkorea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'SPI:NAME:<NAME>END_PIard und PI:NAME:<NAME>END_PI'},
{value: 'SZ', name: 'Swasiland'},
{value: 'SY', name: 'Syrien'},
{value: 'TJ', name: 'Tadschikistan'},
{value: 'TW', name: 'Taiwan'},
{value: 'TZ', name: 'Tansania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-Leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad und Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Tschad'},
{value: 'CZ', name: 'Tschechische Republik'},
{value: 'TN', name: 'Tunesien'},
{value: 'TR', name: 'Türkei'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks- und Caicosinseln'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Ungarn'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Usbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Vatikanstadt'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'Vereinigte Arabische Emirate'},
{value: 'US', name: 'Vereinigte Staaten von Amerika'},
{value: 'VN', name: 'Vietnam'},
{value: 'WF', name: 'Wallis und Futuna'},
{value: 'CX', name: 'Weihnachtsinsel'},
{value: 'BY', name: 'Weißrussland'},
{value: 'EH', name: 'Westsahara'},
{value: 'CF', name: 'Zentralafrikanische Republik'},
{value: 'CY', name: 'ZPI:NAME:<NAME>END_PIn'}
]
'en': [
{value: 'AF', name: 'Afghanistan'},
{value: 'EG', name: 'Egypt'},
{value: 'AX', name: 'Åland Islands'},
{value: 'AL', name: 'Albania'},
{value: 'DZ', name: 'Algeria'},
{value: 'AS', name: 'American Samoa'},
{value: 'VI', name: 'Virgin Islands, U.s.'},
{value: 'AD', name: 'Andorra'},
{value: 'AO', name: 'Angola'},
{value: 'AI', name: 'Anguilla'},
{value: 'AQ', name: 'Antarctica'},
{value: 'AG', name: 'Antigua And Barbuda'},
{value: 'GQ', name: 'Equatorial Guinea'},
{value: 'AR', name: 'Argentina'},
{value: 'AM', name: 'Armenia'},
{value: 'AW', name: 'Aruba'},
{value: 'AC', name: 'Ascension'},
{value: 'AZ', name: 'Azerbaijan'},
{value: 'ET', name: 'Ethiopia'},
{value: 'AU', name: 'Australia'},
{value: 'BS', name: 'Bahamas'},
{value: 'BH', name: 'Bahrain'},
{value: 'BD', name: 'Bangladesh'},
{value: 'BB', name: 'Barbados'},
{value: 'BE', name: 'Belgium'},
{value: 'BZ', name: 'Belize'},
{value: 'BJ', name: 'Benin'},
{value: 'BM', name: 'Bermuda'},
{value: 'BT', name: 'Bhutan'},
{value: 'BO', name: 'Bolivia'},
{value: 'BA', name: 'Bosnia And Herzegovina'},
{value: 'BW', name: 'Botswana'},
{value: 'BV', name: 'Bouvet Island'},
{value: 'BR', name: 'Brazil'},
{value: 'BN', name: 'Brunei Darussalam'},
{value: 'BG', name: 'Bulgaria'},
{value: 'BF', name: 'Burkina Faso'},
{value: 'BI', name: 'Burundi'},
{value: 'CL', name: 'Chile'},
{value: 'CN', name: 'China'},
{value: 'CK', name: 'Cook Islands'},
{value: 'CR', name: 'Costa Rica'},
{value: 'CI', name: 'PI:NAME:<NAME>END_PI\'PI:NAME:<NAME>END_PI'},
{value: 'DK', name: 'Denmark'},
{value: 'DE', name: 'Germany'},
{value: 'DG', name: 'PI:NAME:<NAME>END_PI'},
{value: 'DM', name: 'Dominica'},
{value: 'DO', name: 'Dominican Republic'},
{value: 'DJ', name: 'Djibouti'},
{value: 'EC', name: 'Ecuador'},
{value: 'SV', name: 'El Salvador'},
{value: 'ER', name: 'Eritrea'},
{value: 'EE', name: 'Estonia'},
{value: 'EU', name: 'Europäische Union'},
{value: 'FK', name: 'Falkland Islands (malvinas)'},
{value: 'FO', name: 'Faroe Islands'},
{value: 'FJ', name: 'Fiji'},
{value: 'FI', name: 'Finland'},
{value: 'FR', name: 'France'},
{value: 'GF', name: 'French Guiana'},
{value: 'PF', name: 'French Polynesia'},
{value: 'GA', name: 'Gabon'},
{value: 'GM', name: 'Gambia'},
{value: 'GE', name: 'Georgia'},
{value: 'GH', name: 'Ghana'},
{value: 'GI', name: 'Gibraltar'},
{value: 'GD', name: 'Grenada'},
{value: 'GR', name: 'Greece'},
{value: 'GL', name: 'Greenland'},
{value: 'GB', name: 'Create Britain'},
{value: 'CP', name: 'Guadeloupe'},
{value: 'GU', name: 'Guam'},
{value: 'GT', name: 'Guatemala'},
{value: 'GG', name: 'Guernsey'},
{value: 'GN', name: 'Guinea'},
{value: 'GW', name: 'Guinea-bissau'},
{value: 'GY', name: 'Guyana'},
{value: 'HT', name: 'Haiti'},
{value: 'HM', name: 'Heard Island And Mcdonald Islands'},
{value: 'HN', name: 'Honduras'},
{value: 'HK', name: 'Hong Kong'},
{value: 'IN', name: 'India'},
{value: 'ID', name: 'Indonesia'},
{value: 'IQ', name: 'Iraq'},
{value: 'IR', name: 'Iran, Islamic Republic Of'},
{value: 'IE', name: 'Ireland'},
{value: 'IS', name: 'Iceland'},
{value: 'IL', name: 'Israel'},
{value: 'IT', name: 'Italy'},
{value: 'JM', name: 'Jamaica'},
{value: 'JP', name: 'Japan'},
{value: 'YE', name: 'Yemen'},
{value: 'JE', name: 'Jersey'},
{value: 'JO', name: 'Jordan'},
{value: 'KY', name: 'Cayman Islands'},
{value: 'KH', name: 'Cambodia'},
{value: 'CM', name: 'Cameroon'},
{value: 'CA', name: 'Canada'},
{value: 'IC', name: 'Kanarische Inseln'},
{value: 'CV', name: 'Cape Verde'},
{value: 'KZ', name: 'Kazakhstan'},
{value: 'QA', name: 'Qatar'},
{value: 'KE', name: 'Kenya'},
{value: 'KG', name: 'Kyrgyzstan'},
{value: 'KI', name: 'Kiribati'},
{value: 'CC', name: 'Cocos (keeling) Islands'},
{value: 'CO', name: 'Colombia'},
{value: 'KM', name: 'Comoros'},
{value: 'CG', name: 'Congo'},
{value: 'HR', name: 'Croatia'},
{value: 'CU', name: 'Cuba'},
{value: 'KW', name: 'Kuwait'},
{value: 'LA', name: 'Lao People\'s Democratic Republic'},
{value: 'LS', name: 'Lesotho'},
{value: 'LV', name: 'Latvia'},
{value: 'LB', name: 'Lebanon'},
{value: 'LR', name: 'Liberia'},
{value: 'LY', name: 'Libyan Arab Jamahiriya'},
{value: 'LI', name: 'Liechtenstein'},
{value: 'LT', name: 'Lithuania'},
{value: 'LU', name: 'Luxembourg'},
{value: 'MO', name: 'Macao'},
{value: 'MG', name: 'Madagascar'},
{value: 'MW', name: 'Malawi'},
{value: 'MY', name: 'Malaysia'},
{value: 'MV', name: 'Maldives'},
{value: 'ML', name: 'Mali'},
{value: 'MT', name: 'Malta'},
{value: 'MA', name: 'Morocco'},
{value: 'MH', name: 'Marshall Islands'},
{value: 'MQ', name: 'Martinique'},
{value: 'MR', name: 'Mauritania'},
{value: 'MU', name: 'Mauritius'},
{value: 'YT', name: 'Mayotte'},
{value: 'MK', name: 'Macedonia, The Former Yugoslav Republic Of'},
{value: 'MX', name: 'Mexico'},
{value: 'FM', name: 'Micronesia'},
{value: 'MD', name: 'Moldova'},
{value: 'MC', name: 'Monaco'},
{value: 'MN', name: 'Mongolia'},
{value: 'MS', name: 'Montserrat'},
{value: 'MZ', name: 'Mozambique'},
{value: 'MM', name: 'Myanmar'},
{value: 'NA', name: 'Namibia'},
{value: 'NR', name: 'Nauru'},
{value: 'NP', name: 'Nepal'},
{value: 'NC', name: 'New Caledonia'},
{value: 'NZ', name: 'New Zealand'},
{value: 'NT', name: 'Neutrale Zone'},
{value: 'NI', name: 'Nicaragua'},
{value: 'NL', name: 'Netherlands'},
{value: 'AN', name: 'Netherlands Antilles'},
{value: 'NE', name: 'Niger'},
{value: 'NG', name: 'Nigeria'},
{value: 'NU', name: 'Niue'},
{value: 'KP', name: 'North Korea'},
{value: 'MP', name: 'Northern Mariana Islands'},
{value: 'NF', name: 'Norfolk Island'},
{value: 'NO', name: 'Norway'},
{value: 'OM', name: 'Oman'},
{value: 'AT', name: 'Austria'},
{value: 'PK', name: 'Pakistan'},
{value: 'PS', name: 'Palestinian Territory'},
{value: 'PW', name: 'Palau'},
{value: 'PA', name: 'Panama'},
{value: 'PG', name: 'Papua New Guinea'},
{value: 'PY', name: 'Paraguay'},
{value: 'PE', name: 'Peru'},
{value: 'PH', name: 'Philippines'},
{value: 'PN', name: 'Pitcairn'},
{value: 'PL', name: 'Poland'},
{value: 'PT', name: 'Portugal'},
{value: 'PR', name: 'Puerto Rico'},
{value: 'RE', name: 'RÉunion'},
{value: 'RW', name: 'Rwanda'},
{value: 'RO', name: 'Romania'},
{value: 'RU', name: 'Russian Federation'},
{value: 'SB', name: 'Solomon Islands'},
{value: 'ZM', name: 'Zambia'},
{value: 'WS', name: 'Samoa'},
{value: 'SM', name: 'San Marino'},
{value: 'ST', name: 'Sao Tome And Principe'},
{value: 'SA', name: 'Saudi Arabia'},
{value: 'SE', name: 'Sweden'},
{value: 'CH', name: 'Switzerland'},
{value: 'SN', name: 'Senegal'},
{value: 'CS', name: 'Serbien und Montenegro'},
{value: 'SC', name: 'Seychelles'},
{value: 'SL', name: 'Sierra Leone'},
{value: 'ZW', name: 'Zimbabwe'},
{value: 'SG', name: 'Singapore'},
{value: 'SK', name: 'Slovakia'},
{value: 'SI', name: 'Slovenia'},
{value: 'SO', name: 'Somalia'},
{value: 'ES', name: 'Spain'},
{value: 'LK', name: 'Sri Lanka'},
{value: 'SH', name: 'PI:NAME:<NAME>END_PI'},
{value: 'KN', name: 'Saint Kitts And Nevis'},
{value: 'LC', name: 'Saint Lucia'},
{value: 'PM', name: 'Saint Pierre And Miquelon'},
{value: 'VC', name: 'Saint Vincent/Grenadines'},
{value: 'ZA', name: 'South Africa'},
{value: 'SD', name: 'Sudan'},
{value: 'KR', name: 'South Korea'},
{value: 'SR', name: 'Suriname'},
{value: 'SJ', name: 'Svalbard And Jan Mayen'},
{value: 'SZ', name: 'Swaziland'},
{value: 'SY', name: 'Syrian Arab Republic'},
{value: 'TJ', name: 'Tajikistan'},
{value: 'TW', name: 'Taiwan, Province Of China'},
{value: 'TZ', name: 'Tanzania'},
{value: 'TH', name: 'Thailand'},
{value: 'TL', name: 'Timor-leste'},
{value: 'TG', name: 'Togo'},
{value: 'TK', name: 'Tokelau'},
{value: 'TO', name: 'Tonga'},
{value: 'TT', name: 'Trinidad And Tobago'},
{value: 'TA', name: 'Tristan da Cunha'},
{value: 'TD', name: 'Chad'},
{value: 'CZ', name: 'Czech Republic'},
{value: 'TN', name: 'Tunisia'},
{value: 'TR', name: 'Turkey'},
{value: 'TM', name: 'Turkmenistan'},
{value: 'TC', name: 'Turks And Caicos Islands'},
{value: 'TV', name: 'Tuvalu'},
{value: 'UG', name: 'Uganda'},
{value: 'UA', name: 'Ukraine'},
{value: 'HU', name: 'Hungary'},
{value: 'UY', name: 'Uruguay'},
{value: 'UZ', name: 'Uzbekistan'},
{value: 'VU', name: 'Vanuatu'},
{value: 'VA', name: 'Holy See (vatican City State)'},
{value: 'VE', name: 'Venezuela'},
{value: 'AE', name: 'United Arab Emirates'},
{value: 'US', name: 'United States'},
{value: 'VN', name: 'Viet Nam'},
{value: 'WF', name: 'Wallis And Futuna'},
{value: 'CX', name: 'Christmas Island'},
{value: 'BY', name: 'Belarus'},
{value: 'EH', name: 'Western Sahara'},
{value: 'CF', name: 'Central African Republic'},
{value: 'CY', name: 'Cyprus'}
]
$scope.currentPage = $state.current.name;
$scope.donate = {}
$scope.record = {}
$scope.donate.donator = {};
$scope.donate.donator.address = {};
$scope.donate.paymentInterval = $scope.paymentIntervals[0]
$scope.donate.paymentReason = $scope.paymentReasons[0]
$scope.donate.donateAs = $scope.donateAsItems[0]
$scope.donate.donator.title = $scope.titles[0]
if ($scope.donate.paymentValue != undefined && $scope.donate.paymentValue < 0)
$scope.donate.paymentValue = Math.abs($scope.donate.paymentValue)
$scope.translateComboBoxes = -> (
_.map($scope.paymentIntervals, (paymentInterval, id) ->
$translate(paymentInterval.name).then((text) ->
paymentInterval.name = text
return
)
)
_.map($scope.paymentReasons, (paymentReason, id) ->
$translate(paymentReason.name).then((text) ->
paymentReason.name = text
return
)
)
_.map($scope.donateAsItems, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
_.map($scope.titles, (item, id) ->
$translate(item.name).then((text) ->
item.name = text
return
)
)
currentLanguage = $translate.proposedLanguage() || $translate.use()
$scope.countries = countries[currentLanguage]
$scope.donate.language = currentLanguage
$scope.donate.donator.address.country = _.first(_.filter(countries.de, (c) ->
c.value == 'DE'
))
return
)
$scope.validateStep = ($event) -> (
if !$('.payment-form').isValid({'de', 'en'}, $.formUtils.defaultConfig(), true)
$event.preventDefault()
return false
return true
)
$scope.validateStep1 = ($event) -> (
if (! $scope.validateStep($event))
$event.preventDefault()
return
$event.preventDefault()
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/checkcard.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
$state.go('root.donate.step2', $stateParams, {reload: false});
return
return true
)
$scope.processForm = () -> (
$('body').addClass('loading')
$http(
method: 'POST'
url: '/api/services/process.php'
data: $.param($scope.donate)
headers: 'Content-Type': 'application/x-www-form-urlencoded')
.success (data) ->
$('body').removeClass('loading')
if !data.success
# if not successful, bind errors to error variables
$('.payment-alert #show-msg').text(data.message)
$('.payment-alert').fadeIn()
else
# if successful, bind success message to message
$('#confirm-dialog').modal('show');
return
)
$scope.translateComboBoxes()
return
]
|
[
{
"context": "thenReturn(\"yay\")\n Then -> @testDouble(key: \"testytest\") == \"yay\"\n Then -> @testDouble(key: 42) == ",
"end": 1824,
"score": 0.8478986620903015,
"start": 1815,
"tag": "KEY",
"value": "testytest"
}
] | node_modules/testdouble/test/src/when-test.coffee | fillipegb/toksaude-prototipo | 0 | describe 'when', ->
Given -> @testDouble = td.function()
describe 'no-arg stubbing', ->
context 'foo', ->
Given -> td.when(@testDouble()).thenReturn("foo")
Then -> @testDouble() == "foo"
context 'bar', ->
Given -> td.when(@testDouble()).thenReturn("bar")
Then -> @testDouble() == "bar"
describe 'last-in-wins overwriting', ->
Given -> td.when(@testDouble("something")).thenReturn("gold")
Given -> td.when(@testDouble("something")).thenReturn("iron")
Then -> @testDouble("something") == "iron"
describe 'conditional stubbing', ->
Given -> td.when(@testDouble(1)).thenReturn("foo")
Given -> td.when(@testDouble(2)).thenReturn("bar")
Given -> td.when(@testDouble(lol: 'cheese')).thenReturn('nom')
Given -> td.when(@testDouble(lol: 'fungus')).thenReturn('eww')
Given -> td.when(@testDouble({lol: 'fungus'}, 2)).thenReturn('eww2')
Then -> @testDouble() == undefined
And -> @testDouble(1) == "foo"
And -> @testDouble(2) == "bar"
And -> @testDouble(lol: 'cheese') == "nom"
And -> @testDouble(lol: 'fungus') == "eww"
And -> @testDouble({lol: 'fungus'}, 2) == "eww2"
describe 'multiple test doubles', ->
Given -> @td1 = td.when(td.function()()).thenReturn("lol1")
Given -> @td2 = td.when(td.function()()).thenReturn("lol2")
Then -> @td1() == "lol1"
Then -> @td2() == "lol2"
describe 'using matchers', ->
Given -> td.when(@testDouble(88, td.matchers.isA(Number))).thenReturn("yay")
Then -> @testDouble(88, 5) == "yay"
Then -> @testDouble(44, 5) == undefined
Then -> @testDouble(88, "five") == undefined
describe 'using deep matchers', ->
context 'single level', ->
Given -> td.when(@testDouble(key: td.matchers.isA(String))).thenReturn("yay")
Then -> @testDouble(key: "testytest") == "yay"
Then -> @testDouble(key: 42) == undefined
Then -> @testDouble({}) == undefined
Then -> @testDouble("i am a string") == undefined
context 'deeply nested', ->
Given -> td.when(@testDouble(a: {b: td.matchers.isA(String)})).thenReturn("yay")
Then -> @testDouble(a: {b: "testytest"}) == "yay"
Then -> @testDouble(a: {b: 42}) == undefined
Then -> @testDouble(a: "testytest") == undefined
context 'array values', ->
Given -> td.when(@testDouble([5, td.matchers.isA(String)])).thenReturn("yay")
Then -> @testDouble([5, "testytest"]) == "yay"
Then -> @testDouble([5, 6]) == undefined
Then -> @testDouble([5]) == undefined
Then -> @testDouble([]) == undefined
context 'arguments with circular structures', ->
Given -> @arg =
foo: 'bar'
Given -> @arg.baz = @arg
Given -> td.when(@testDouble(@arg)).thenReturn("yay")
Then -> @testDouble(@arg) == "yay"
Then -> @testDouble('no') == undefined
describe 'stubbing sequential returns', ->
context 'a single stubbing', ->
Given -> td.when(@testDouble()).thenReturn(10,9)
When -> [@first, @second, @third] = [@testDouble(), @testDouble(), @testDouble()]
Then -> @first == 10
Then -> @second == 9
Then -> @third == 9 #<-- last one repeats
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('A')
Given -> @testDouble() #<-- returns A, td's callCount will be 1
Given -> td.when(@testDouble()).thenReturn('B', 'C')
Then -> @testDouble() == 'B'
describe 'stubbing actions with `thenDo` instead of `thenReturn`', ->
Given -> td.when(@testDouble(55)).thenDo(=> @result = 'yatta')
When -> @testDouble(55)
And -> @result == 'yatta'
describe 'stubbing actions with `thenDo` preserves function context', ->
Given -> td.when(@testDouble(55)).thenDo(-> this.result)
When -> @result = @testDouble.call({ result: 'yatta' }, 55)
Then -> @result == 'yatta'
describe 'stubbing actions with `thenThrow` instead of `thenReturn`', ->
Given -> @error = new Error('lol')
Given -> td.when(@testDouble(42)).thenThrow(@error)
When -> try @testDouble(42) catch e then @result = e
Then -> @error == @result
describe 'stubbing promises', ->
context 'with a native promise', ->
return unless typeof Promise == 'function'
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done()); undefined
Then -> @resolved == 'pants'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then(null, (@rejected) => done()); undefined
Then -> @rejected == 'oops'
context 'with an alternative promise constructor', ->
class FakePromise
constructor: (executor) ->
executor(((@resolved) =>), ((@rejected) =>))
then: (success, failure) ->
if @resolved?
success(@resolved + '!')
else
failure(@rejected + '?')
Given -> td.config({promiseConstructor: FakePromise})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done())
Then -> @resolved == 'pants!'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then null, (@rejected) => done()
Then -> @rejected == 'oops?'
context 'with no promise constructor', ->
Given -> @warnings = []
Given -> @errors = []
Given -> console.warn = (m) => @warnings.push(m)
Given -> console.error = (m) => @errors.push(m)
Given -> td.config({promiseConstructor: undefined})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
Then -> @warnings[0] == """
Warning: testdouble.js - td.when - no promise constructor is set, so this `thenResolve` or `thenReject` stubbing
will fail if it's satisfied by an invocation on the test double. You can tell
testdouble.js which promise constructor to use with `td.config`, like so:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'actually invoking it', ->
When -> try @testDouble(10) catch e then @error = e
Then -> @error.message == """
Error: testdouble.js - td.when - no promise constructor is set (perhaps this runtime lacks a native Promise
function?), which means this stubbing can't return a promise to your
subject under test, resulting in this error. To resolve the issue, set
a promise constructor with `td.config`, like this:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'stubbing error, no invocation found', ->
Given -> td.reset()
Given -> try
td.when().thenReturn('hi')
catch e
@error = e
Then -> @error.message == """
Error: testdouble.js - td.when - No test double invocation call detected for `when()`.
Usage:
when(myTestDouble('foo')).thenReturn('bar')
"""
describe 'config object', ->
describe 'ignoring extra arguments', ->
context 'for a no-arg stubbing', ->
Given -> td.when(@testDouble(), ignoreExtraArgs: true).thenReturn('pewpew')
When -> @result = @testDouble('so', 'many', 'args')
Then -> @result == 'pewpew'
context 'when an initial-arg-matters', ->
Given -> td.when(@testDouble('important'), ignoreExtraArgs: true).thenReturn('neat')
context 'satisfied without extra args', ->
Then -> @testDouble('important') == 'neat'
context 'satisfied with extra args', ->
Then -> @testDouble('important', 'not important') == 'neat'
context 'unsatisfied with no args', ->
Then -> @testDouble() == undefined
context 'unsatisfied with extra args', ->
Then -> @testDouble('unimportant', 'not important') == undefined
describe 'limiting times stubbing will work', ->
context 'a single stub', ->
Given -> td.when(@testDouble(), times: 2).thenReturn('pants')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['pants', 'pants', undefined])
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('NO')
Given -> td.when(@testDouble(), times: 1).thenReturn('YES')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['YES', 'NO', 'NO'])
describe 'nested whens', ->
Given -> @knob = td.function()
Given -> @door = td.function()
Given -> td.when(@knob('twist')).thenReturn
door: td.when(@door('push')).thenReturn('open')
When -> @result = @knob('twist').door('push')
Then -> @result == 'open'
| 210559 | describe 'when', ->
Given -> @testDouble = td.function()
describe 'no-arg stubbing', ->
context 'foo', ->
Given -> td.when(@testDouble()).thenReturn("foo")
Then -> @testDouble() == "foo"
context 'bar', ->
Given -> td.when(@testDouble()).thenReturn("bar")
Then -> @testDouble() == "bar"
describe 'last-in-wins overwriting', ->
Given -> td.when(@testDouble("something")).thenReturn("gold")
Given -> td.when(@testDouble("something")).thenReturn("iron")
Then -> @testDouble("something") == "iron"
describe 'conditional stubbing', ->
Given -> td.when(@testDouble(1)).thenReturn("foo")
Given -> td.when(@testDouble(2)).thenReturn("bar")
Given -> td.when(@testDouble(lol: 'cheese')).thenReturn('nom')
Given -> td.when(@testDouble(lol: 'fungus')).thenReturn('eww')
Given -> td.when(@testDouble({lol: 'fungus'}, 2)).thenReturn('eww2')
Then -> @testDouble() == undefined
And -> @testDouble(1) == "foo"
And -> @testDouble(2) == "bar"
And -> @testDouble(lol: 'cheese') == "nom"
And -> @testDouble(lol: 'fungus') == "eww"
And -> @testDouble({lol: 'fungus'}, 2) == "eww2"
describe 'multiple test doubles', ->
Given -> @td1 = td.when(td.function()()).thenReturn("lol1")
Given -> @td2 = td.when(td.function()()).thenReturn("lol2")
Then -> @td1() == "lol1"
Then -> @td2() == "lol2"
describe 'using matchers', ->
Given -> td.when(@testDouble(88, td.matchers.isA(Number))).thenReturn("yay")
Then -> @testDouble(88, 5) == "yay"
Then -> @testDouble(44, 5) == undefined
Then -> @testDouble(88, "five") == undefined
describe 'using deep matchers', ->
context 'single level', ->
Given -> td.when(@testDouble(key: td.matchers.isA(String))).thenReturn("yay")
Then -> @testDouble(key: "<KEY>") == "yay"
Then -> @testDouble(key: 42) == undefined
Then -> @testDouble({}) == undefined
Then -> @testDouble("i am a string") == undefined
context 'deeply nested', ->
Given -> td.when(@testDouble(a: {b: td.matchers.isA(String)})).thenReturn("yay")
Then -> @testDouble(a: {b: "testytest"}) == "yay"
Then -> @testDouble(a: {b: 42}) == undefined
Then -> @testDouble(a: "testytest") == undefined
context 'array values', ->
Given -> td.when(@testDouble([5, td.matchers.isA(String)])).thenReturn("yay")
Then -> @testDouble([5, "testytest"]) == "yay"
Then -> @testDouble([5, 6]) == undefined
Then -> @testDouble([5]) == undefined
Then -> @testDouble([]) == undefined
context 'arguments with circular structures', ->
Given -> @arg =
foo: 'bar'
Given -> @arg.baz = @arg
Given -> td.when(@testDouble(@arg)).thenReturn("yay")
Then -> @testDouble(@arg) == "yay"
Then -> @testDouble('no') == undefined
describe 'stubbing sequential returns', ->
context 'a single stubbing', ->
Given -> td.when(@testDouble()).thenReturn(10,9)
When -> [@first, @second, @third] = [@testDouble(), @testDouble(), @testDouble()]
Then -> @first == 10
Then -> @second == 9
Then -> @third == 9 #<-- last one repeats
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('A')
Given -> @testDouble() #<-- returns A, td's callCount will be 1
Given -> td.when(@testDouble()).thenReturn('B', 'C')
Then -> @testDouble() == 'B'
describe 'stubbing actions with `thenDo` instead of `thenReturn`', ->
Given -> td.when(@testDouble(55)).thenDo(=> @result = 'yatta')
When -> @testDouble(55)
And -> @result == 'yatta'
describe 'stubbing actions with `thenDo` preserves function context', ->
Given -> td.when(@testDouble(55)).thenDo(-> this.result)
When -> @result = @testDouble.call({ result: 'yatta' }, 55)
Then -> @result == 'yatta'
describe 'stubbing actions with `thenThrow` instead of `thenReturn`', ->
Given -> @error = new Error('lol')
Given -> td.when(@testDouble(42)).thenThrow(@error)
When -> try @testDouble(42) catch e then @result = e
Then -> @error == @result
describe 'stubbing promises', ->
context 'with a native promise', ->
return unless typeof Promise == 'function'
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done()); undefined
Then -> @resolved == 'pants'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then(null, (@rejected) => done()); undefined
Then -> @rejected == 'oops'
context 'with an alternative promise constructor', ->
class FakePromise
constructor: (executor) ->
executor(((@resolved) =>), ((@rejected) =>))
then: (success, failure) ->
if @resolved?
success(@resolved + '!')
else
failure(@rejected + '?')
Given -> td.config({promiseConstructor: FakePromise})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done())
Then -> @resolved == 'pants!'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then null, (@rejected) => done()
Then -> @rejected == 'oops?'
context 'with no promise constructor', ->
Given -> @warnings = []
Given -> @errors = []
Given -> console.warn = (m) => @warnings.push(m)
Given -> console.error = (m) => @errors.push(m)
Given -> td.config({promiseConstructor: undefined})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
Then -> @warnings[0] == """
Warning: testdouble.js - td.when - no promise constructor is set, so this `thenResolve` or `thenReject` stubbing
will fail if it's satisfied by an invocation on the test double. You can tell
testdouble.js which promise constructor to use with `td.config`, like so:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'actually invoking it', ->
When -> try @testDouble(10) catch e then @error = e
Then -> @error.message == """
Error: testdouble.js - td.when - no promise constructor is set (perhaps this runtime lacks a native Promise
function?), which means this stubbing can't return a promise to your
subject under test, resulting in this error. To resolve the issue, set
a promise constructor with `td.config`, like this:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'stubbing error, no invocation found', ->
Given -> td.reset()
Given -> try
td.when().thenReturn('hi')
catch e
@error = e
Then -> @error.message == """
Error: testdouble.js - td.when - No test double invocation call detected for `when()`.
Usage:
when(myTestDouble('foo')).thenReturn('bar')
"""
describe 'config object', ->
describe 'ignoring extra arguments', ->
context 'for a no-arg stubbing', ->
Given -> td.when(@testDouble(), ignoreExtraArgs: true).thenReturn('pewpew')
When -> @result = @testDouble('so', 'many', 'args')
Then -> @result == 'pewpew'
context 'when an initial-arg-matters', ->
Given -> td.when(@testDouble('important'), ignoreExtraArgs: true).thenReturn('neat')
context 'satisfied without extra args', ->
Then -> @testDouble('important') == 'neat'
context 'satisfied with extra args', ->
Then -> @testDouble('important', 'not important') == 'neat'
context 'unsatisfied with no args', ->
Then -> @testDouble() == undefined
context 'unsatisfied with extra args', ->
Then -> @testDouble('unimportant', 'not important') == undefined
describe 'limiting times stubbing will work', ->
context 'a single stub', ->
Given -> td.when(@testDouble(), times: 2).thenReturn('pants')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['pants', 'pants', undefined])
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('NO')
Given -> td.when(@testDouble(), times: 1).thenReturn('YES')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['YES', 'NO', 'NO'])
describe 'nested whens', ->
Given -> @knob = td.function()
Given -> @door = td.function()
Given -> td.when(@knob('twist')).thenReturn
door: td.when(@door('push')).thenReturn('open')
When -> @result = @knob('twist').door('push')
Then -> @result == 'open'
| true | describe 'when', ->
Given -> @testDouble = td.function()
describe 'no-arg stubbing', ->
context 'foo', ->
Given -> td.when(@testDouble()).thenReturn("foo")
Then -> @testDouble() == "foo"
context 'bar', ->
Given -> td.when(@testDouble()).thenReturn("bar")
Then -> @testDouble() == "bar"
describe 'last-in-wins overwriting', ->
Given -> td.when(@testDouble("something")).thenReturn("gold")
Given -> td.when(@testDouble("something")).thenReturn("iron")
Then -> @testDouble("something") == "iron"
describe 'conditional stubbing', ->
Given -> td.when(@testDouble(1)).thenReturn("foo")
Given -> td.when(@testDouble(2)).thenReturn("bar")
Given -> td.when(@testDouble(lol: 'cheese')).thenReturn('nom')
Given -> td.when(@testDouble(lol: 'fungus')).thenReturn('eww')
Given -> td.when(@testDouble({lol: 'fungus'}, 2)).thenReturn('eww2')
Then -> @testDouble() == undefined
And -> @testDouble(1) == "foo"
And -> @testDouble(2) == "bar"
And -> @testDouble(lol: 'cheese') == "nom"
And -> @testDouble(lol: 'fungus') == "eww"
And -> @testDouble({lol: 'fungus'}, 2) == "eww2"
describe 'multiple test doubles', ->
Given -> @td1 = td.when(td.function()()).thenReturn("lol1")
Given -> @td2 = td.when(td.function()()).thenReturn("lol2")
Then -> @td1() == "lol1"
Then -> @td2() == "lol2"
describe 'using matchers', ->
Given -> td.when(@testDouble(88, td.matchers.isA(Number))).thenReturn("yay")
Then -> @testDouble(88, 5) == "yay"
Then -> @testDouble(44, 5) == undefined
Then -> @testDouble(88, "five") == undefined
describe 'using deep matchers', ->
context 'single level', ->
Given -> td.when(@testDouble(key: td.matchers.isA(String))).thenReturn("yay")
Then -> @testDouble(key: "PI:KEY:<KEY>END_PI") == "yay"
Then -> @testDouble(key: 42) == undefined
Then -> @testDouble({}) == undefined
Then -> @testDouble("i am a string") == undefined
context 'deeply nested', ->
Given -> td.when(@testDouble(a: {b: td.matchers.isA(String)})).thenReturn("yay")
Then -> @testDouble(a: {b: "testytest"}) == "yay"
Then -> @testDouble(a: {b: 42}) == undefined
Then -> @testDouble(a: "testytest") == undefined
context 'array values', ->
Given -> td.when(@testDouble([5, td.matchers.isA(String)])).thenReturn("yay")
Then -> @testDouble([5, "testytest"]) == "yay"
Then -> @testDouble([5, 6]) == undefined
Then -> @testDouble([5]) == undefined
Then -> @testDouble([]) == undefined
context 'arguments with circular structures', ->
Given -> @arg =
foo: 'bar'
Given -> @arg.baz = @arg
Given -> td.when(@testDouble(@arg)).thenReturn("yay")
Then -> @testDouble(@arg) == "yay"
Then -> @testDouble('no') == undefined
describe 'stubbing sequential returns', ->
context 'a single stubbing', ->
Given -> td.when(@testDouble()).thenReturn(10,9)
When -> [@first, @second, @third] = [@testDouble(), @testDouble(), @testDouble()]
Then -> @first == 10
Then -> @second == 9
Then -> @third == 9 #<-- last one repeats
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('A')
Given -> @testDouble() #<-- returns A, td's callCount will be 1
Given -> td.when(@testDouble()).thenReturn('B', 'C')
Then -> @testDouble() == 'B'
describe 'stubbing actions with `thenDo` instead of `thenReturn`', ->
Given -> td.when(@testDouble(55)).thenDo(=> @result = 'yatta')
When -> @testDouble(55)
And -> @result == 'yatta'
describe 'stubbing actions with `thenDo` preserves function context', ->
Given -> td.when(@testDouble(55)).thenDo(-> this.result)
When -> @result = @testDouble.call({ result: 'yatta' }, 55)
Then -> @result == 'yatta'
describe 'stubbing actions with `thenThrow` instead of `thenReturn`', ->
Given -> @error = new Error('lol')
Given -> td.when(@testDouble(42)).thenThrow(@error)
When -> try @testDouble(42) catch e then @result = e
Then -> @error == @result
describe 'stubbing promises', ->
context 'with a native promise', ->
return unless typeof Promise == 'function'
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done()); undefined
Then -> @resolved == 'pants'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then(null, (@rejected) => done()); undefined
Then -> @rejected == 'oops'
context 'with an alternative promise constructor', ->
class FakePromise
constructor: (executor) ->
executor(((@resolved) =>), ((@rejected) =>))
then: (success, failure) ->
if @resolved?
success(@resolved + '!')
else
failure(@rejected + '?')
Given -> td.config({promiseConstructor: FakePromise})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
When (done) -> @testDouble(10).then((@resolved) => done())
Then -> @resolved == 'pants!'
describe 'td.when…thenReject', ->
Given -> td.when(@testDouble(10)).thenReject('oops')
When (done) -> @testDouble(10).then null, (@rejected) => done()
Then -> @rejected == 'oops?'
context 'with no promise constructor', ->
Given -> @warnings = []
Given -> @errors = []
Given -> console.warn = (m) => @warnings.push(m)
Given -> console.error = (m) => @errors.push(m)
Given -> td.config({promiseConstructor: undefined})
describe 'td.when…thenResolve', ->
Given -> td.when(@testDouble(10)).thenResolve('pants')
Then -> @warnings[0] == """
Warning: testdouble.js - td.when - no promise constructor is set, so this `thenResolve` or `thenReject` stubbing
will fail if it's satisfied by an invocation on the test double. You can tell
testdouble.js which promise constructor to use with `td.config`, like so:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'actually invoking it', ->
When -> try @testDouble(10) catch e then @error = e
Then -> @error.message == """
Error: testdouble.js - td.when - no promise constructor is set (perhaps this runtime lacks a native Promise
function?), which means this stubbing can't return a promise to your
subject under test, resulting in this error. To resolve the issue, set
a promise constructor with `td.config`, like this:
td.config({
promiseConstructor: require('bluebird')
})
"""
describe 'stubbing error, no invocation found', ->
Given -> td.reset()
Given -> try
td.when().thenReturn('hi')
catch e
@error = e
Then -> @error.message == """
Error: testdouble.js - td.when - No test double invocation call detected for `when()`.
Usage:
when(myTestDouble('foo')).thenReturn('bar')
"""
describe 'config object', ->
describe 'ignoring extra arguments', ->
context 'for a no-arg stubbing', ->
Given -> td.when(@testDouble(), ignoreExtraArgs: true).thenReturn('pewpew')
When -> @result = @testDouble('so', 'many', 'args')
Then -> @result == 'pewpew'
context 'when an initial-arg-matters', ->
Given -> td.when(@testDouble('important'), ignoreExtraArgs: true).thenReturn('neat')
context 'satisfied without extra args', ->
Then -> @testDouble('important') == 'neat'
context 'satisfied with extra args', ->
Then -> @testDouble('important', 'not important') == 'neat'
context 'unsatisfied with no args', ->
Then -> @testDouble() == undefined
context 'unsatisfied with extra args', ->
Then -> @testDouble('unimportant', 'not important') == undefined
describe 'limiting times stubbing will work', ->
context 'a single stub', ->
Given -> td.when(@testDouble(), times: 2).thenReturn('pants')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['pants', 'pants', undefined])
context 'two overlapping stubbings', ->
Given -> td.when(@testDouble()).thenReturn('NO')
Given -> td.when(@testDouble(), times: 1).thenReturn('YES')
When -> @result = [@testDouble(), @testDouble(), @testDouble()]
Then -> expect(@result).to.deep.equal(['YES', 'NO', 'NO'])
describe 'nested whens', ->
Given -> @knob = td.function()
Given -> @door = td.function()
Given -> td.when(@knob('twist')).thenReturn
door: td.when(@door('push')).thenReturn('open')
When -> @result = @knob('twist').door('push')
Then -> @result == 'open'
|
[
{
"context": "hungry for fruit\"\n Cookie.set(\"password\",\"hungry for fruit\")\n\n region = Tamarind.knownDatabas",
"end": 2481,
"score": 0.6482526063919067,
"start": 2478,
"tag": "PASSWORD",
"value": "gry"
},
{
"context": "nd.dynamoDBClient = null\n username = Cookie.ge... | Tamarind.coffee | Coconut-Data/tamarind | 0 | Backbone = require 'backbone'
global.$ = require 'jquery'
Backbone.$ = $
global.Cookie = require 'js-cookie'
global.moment = require 'moment'
global._ = require 'underscore'
global.PouchDB = require('pouchdb-core')
PouchDB
.plugin(require 'pouchdb-adapter-http')
.plugin(require 'pouchdb-adapter-idb')
.plugin(require 'pouchdb-mapreduce')
.plugin(require 'pouchdb-replication')
.plugin(require 'pouchdb-upsert')
.plugin(require 'pouchdb-changes-filter')
.plugin(require 'pouchdb-find')
{ CognitoIdentityClient } = require("@aws-sdk/client-cognito-identity")
{ fromCognitoIdentityPool } = require("@aws-sdk/credential-provider-cognito-identity")
{ DynamoDBClient } = require("@aws-sdk/client-dynamodb")
{ PutItemCommand, GetItemCommand, ScanCommand } = require("@aws-sdk/client-dynamodb")
{ marshall, unmarshall } = require("@aws-sdk/util-dynamodb")
Router = require './Router'
User = require './models/User'
global.Tamarind =
knownDatabaseServers:
Zanzibar: "https://zanzibar.cococloud.co"
Kigelia: "https://kigelia.cococloud.co"
Ceshhar: "https://ceshhar.cococloud.co"
Keep: "https://keep.cococloud.co"
Local: "http://localhost:5984"
MikeAWS:
region: "us-east-1"
IdentityPoolId: 'us-east-1:#INSERT HERE"
gooseberryEndpoint: "https://f9l1259lmb.execute-api.us-east-1.amazonaws.com/gooseberry"
Tamarind.serverCredentials = {}
for name, url of Tamarind.knownDatabaseServers
credentials = Cookie.get("#{name}-credentials")
Tamarind.serverCredentials[name] = credentials if credentials
## GLOBAL FUNCTIONS ##
#
Tamarind.canCreateDesignDoc = (database) =>
database or= Tamarind.database
database.put {_id:"_design/test"}
.then (result) =>
database.remove
_id: result.id
_rev: result.rev
Promise.resolve(true)
.catch (error) =>
if error.status is 403
Promise.resolve(false)
Tamarind.setupDatabase = (serverName, databaseOrGatewayName) =>
Tamarind.serverName = serverName
if Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId # DynamoDB
Tamarind.setupDynamoDBClient(serverName, databaseOrGatewayName)
else
Tamarind.setupCouchDBClient(serverName, databaseOrGatewayName)
Tamarind.setupDynamoDBClient = (serverName, databaseOrGatewayName) =>
Tamarind.database = null
unless Tamarind.dynamoDBClient?
if Cookie.get("password") is "hungry for fruit" or prompt("Password:").toLowerCase() is "hungry for fruit"
Cookie.set("password","hungry for fruit")
region = Tamarind.knownDatabaseServers[Tamarind.serverName].region
Tamarind.dynamoDBClient = new DynamoDBClient(
region: region
credentials: fromCognitoIdentityPool(
client: new CognitoIdentityClient({region})
identityPoolId: Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId
)
)
Tamarind.updateGateway(databaseOrGatewayName)
Tamarind.setupCouchDBClient = (serverName, databaseOrGatewayName) =>
console.info "Setting up #{serverName} #{databaseOrGatewayName}"
Tamarind.dynamoDBClient = null
username = Cookie.get("username")
password = Cookie.get("password")
unless username and password
Tamarind.targetUrl = document.location.hash.replace(/#/,"")
return router.navigate "server/#{Tamarind.serverName}", trigger:true
serverUrlWithCredentials = "#{Tamarind.knownDatabaseServers[serverName]}".replace(/:\/\//, "://#{username}:#{password}@")
Tamarind.user = new User()
if Tamarind.localDatabaseMirror?.remoteDatabase.name is "#{serverUrlWithCredentials}/#{databaseOrGatewayName}"
if await Tamarind.authenticate(Tamarind.localDatabaseMirror.remoteDatabase)
console.info "#{serverName} #{databaseOrGatewayName} already setup"
else
return
Tamarind.localDatabaseMirror = await Tamarind.getLocalMirrorForCouchDB(serverUrlWithCredentials, databaseOrGatewayName)
Tamarind.database = Tamarind.localDatabaseMirror.remoteDatabase
Tamarind.databaseName = databaseOrGatewayName
Tamarind.getLocalMirrorForCouchDB = (serverUrlWithCredentials, databaseName) =>
remoteDatabase = new PouchDB("#{serverUrlWithCredentials}/#{databaseName}")
localDatabaseMirror = new PouchDB("#{serverUrlWithCredentials.replace(/^.*@/,"").replace(/^.*\/\//,"")}/#{databaseName}")
localDatabaseMirror.remoteDatabase = remoteDatabase
remoteDatabase.localDatabaseMirror = localDatabaseMirror
return unless await Tamarind.authenticate(remoteDatabase)
if (await localDatabaseMirror.get("_local/availableFields").catch (error) => Promise.resolve false)
# Do this in the background 10 seconds later in case there have been updates
_.delay =>
Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 10000
else
await Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
# Get configuration stuff first
# calculated-fields
# search query params
# indexes
# Need to replicate these since they get created/edited on client then synced to other clients
console.log "Getting Tamarind specific configuration data for #{databaseName}"
remoteDatabase.allDocs
startkey: "tamarind-"
endkey: "tamarind-\uf000"
include_docs: false
.then (result) =>
console.log await remoteDatabase.replicate.to localDatabaseMirror,
doc_ids: _(result.rows).pluck "id"
last_seq = await localDatabaseMirror.get "_local/remote_last_seq"
.then (doc) => Promise.resolve doc.last_seq
.catch => Promise.resolve null
if last_seq
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
return Promise.resolve localDatabaseMirror
else
console.log "Setting up #{databaseName} for the first time"
console.log "Getting all of the #{databaseName} documents 1000 at a time"
await new Promise (resolve) =>
# Get all the docs in reverse order and put them in the mirror
# Use the last_seq to start handling changes after the initial grab of data
isZanzibarDatabase = remoteDatabase.name.match(/zanzibar\.cococloud\.co\/zanzibar/)
if isZanzibarDatabase
startkey = [{},""]
endkey = ["", ""]
else
startkey = "result-\uf000"
endkey = "result"
skip = 0
last_seq = (await remoteDatabase.changes(limit:0, descending:true)).last_seq
loop
console.log "#{startkey} -> #{endkey}"
result = if isZanzibarDatabase
await remoteDatabase.query "results",
descending: true
startkey: startkey
endkey: endkey
limit: 5000
skip: skip
include_docs: true
else
await remoteDatabase.allDocs
descending: true
startkey: startkey
endkey: endkey
limit: 1000
skip: skip
include_docs: true
if result.rows.length is 0
console.log "Finished initial bulk load of document for #{databaseName}"
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
break
localDatabaseMirror.bulkDocs (_(result.rows).pluck "doc"),
new_edits: false
.then (bulkResults) =>
problemPuts = bulkResults.filter (result) => not result.ok
if problemPuts.length isnt 0
alert "Problem saving local data: #{JSON.stringify problemPuts}"
startkey = result.rows[result.rows.length - 1].key
skip = 1
# Resolve after the first iteration so we can start working with data while the rest continues to download
resolve()
Promise.resolve(localDatabaseMirror)
Tamarind.updateAvailableFields = (remoteDatabase, localDatabaseMirror) =>
console.log "Updating available fields"
remoteDatabase.query "fields",
reduce: true
group: true
.catch (error) =>
console.error error
if error.reason is "missing"
alert "Need to add available fields index"
password = prompt "Enter an admin password to setup a local mirror"
adminRemoteDatabase = new PouchDB(remoteDatabase.name.replace(/\/.*@/, "//admin:#{password}@"))
await adminRemoteDatabase.put
_id: "_design/fields",
language: "coffeescript",
views:
fields:
map: """
(doc) ->
if doc.collection is 'result' and doc.question
for key in Object.keys(doc)
if key? and key isnt ''
emit [doc.question, key]
"""
reduce: "_count"
_.delay =>
remoteDatabase.query "fields",
reduce: true
, 500
alert "Fields index added - may take a few minutes before it is ready to be used."
_.delay =>
return Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 1000
.then (result) =>
fieldsAndFrequencyByQuestion = {}
for row in result.rows
fieldsAndFrequencyByQuestion[row.key[0]] or= []
fieldsAndFrequencyByQuestion[row.key[0]].push
field: row.key[1]
frequency: row.value
await localDatabaseMirror.upsert "_local/availableFields", =>
fieldsAndFrequencyByQuestion: fieldsAndFrequencyByQuestion
console.log "Fields Updated"
Tamarind.watchRemoteChangesAndSaveLocally = (remoteDatabase, localDatabaseMirror, last_seq) =>
localDatabaseMirror.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = last_seq
doc
throttledUpdateChangeSeq = _.throttle ((database,seq) =>
database.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = seq
doc
), 5000
remoteDatabase.changes
since: last_seq
live: true
include_docs: true
.on "error", (error) => console.error error
.on "change", (change) =>
if change.doc.collection? is "result"
#console.log "Updates to a result doc. seq:#{change.seq}"
await localDatabaseMirror.put change.doc,
force: true
throttledUpdateChangeSeq(localDatabaseMirror, change.seq)
Tamarind.updateCurrentGateway = =>
Tamarind.updateGateway(Tamarind.gateway.gatewayName)
Tamarind.updateGateway = (gatewayName) =>
result = await Tamarind.dynamoDBClient.send(
new GetItemCommand(
TableName: "Configurations"
Key:
gatewayName:
"S": gatewayName
)
)
Tamarind.gateway = unmarshall(result.Item)
Tamarind.updateQuestionSetForCurrentGateway = (questionSet, options) =>
await Tamarind.updateCurrentGateway()
Tamarind.gateway["Question Sets"][questionSet.label] = questionSet
if options?.delete is true
delete Tamarind.gateway["Question Sets"][questionSet.label]
Tamarind.dynamoDBClient.send(
new PutItemCommand(
TableName: "Configurations"
Item: marshall(Tamarind.gateway)
)
)
Tamarind.authenticate = (database) ->
unless await Tamarind.user.authenticate(database)
alert "User authentication failed. Logout and try again."
console.info "User authentication failed"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
unless Tamarind.user.has "Tamarind Access"
alert "User: #{Tamarind.user.username} does not have TamarindAccess. Logout and try again."
console.info "User: #{Tamarind.user.username} does not have TamarindAccess"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
return true
global.router = new Router()
Backbone.history.start()
| 195098 | Backbone = require 'backbone'
global.$ = require 'jquery'
Backbone.$ = $
global.Cookie = require 'js-cookie'
global.moment = require 'moment'
global._ = require 'underscore'
global.PouchDB = require('pouchdb-core')
PouchDB
.plugin(require 'pouchdb-adapter-http')
.plugin(require 'pouchdb-adapter-idb')
.plugin(require 'pouchdb-mapreduce')
.plugin(require 'pouchdb-replication')
.plugin(require 'pouchdb-upsert')
.plugin(require 'pouchdb-changes-filter')
.plugin(require 'pouchdb-find')
{ CognitoIdentityClient } = require("@aws-sdk/client-cognito-identity")
{ fromCognitoIdentityPool } = require("@aws-sdk/credential-provider-cognito-identity")
{ DynamoDBClient } = require("@aws-sdk/client-dynamodb")
{ PutItemCommand, GetItemCommand, ScanCommand } = require("@aws-sdk/client-dynamodb")
{ marshall, unmarshall } = require("@aws-sdk/util-dynamodb")
Router = require './Router'
User = require './models/User'
global.Tamarind =
knownDatabaseServers:
Zanzibar: "https://zanzibar.cococloud.co"
Kigelia: "https://kigelia.cococloud.co"
Ceshhar: "https://ceshhar.cococloud.co"
Keep: "https://keep.cococloud.co"
Local: "http://localhost:5984"
MikeAWS:
region: "us-east-1"
IdentityPoolId: 'us-east-1:#INSERT HERE"
gooseberryEndpoint: "https://f9l1259lmb.execute-api.us-east-1.amazonaws.com/gooseberry"
Tamarind.serverCredentials = {}
for name, url of Tamarind.knownDatabaseServers
credentials = Cookie.get("#{name}-credentials")
Tamarind.serverCredentials[name] = credentials if credentials
## GLOBAL FUNCTIONS ##
#
Tamarind.canCreateDesignDoc = (database) =>
database or= Tamarind.database
database.put {_id:"_design/test"}
.then (result) =>
database.remove
_id: result.id
_rev: result.rev
Promise.resolve(true)
.catch (error) =>
if error.status is 403
Promise.resolve(false)
Tamarind.setupDatabase = (serverName, databaseOrGatewayName) =>
Tamarind.serverName = serverName
if Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId # DynamoDB
Tamarind.setupDynamoDBClient(serverName, databaseOrGatewayName)
else
Tamarind.setupCouchDBClient(serverName, databaseOrGatewayName)
Tamarind.setupDynamoDBClient = (serverName, databaseOrGatewayName) =>
Tamarind.database = null
unless Tamarind.dynamoDBClient?
if Cookie.get("password") is "hungry for fruit" or prompt("Password:").toLowerCase() is "hungry for fruit"
Cookie.set("password","hun<PASSWORD> for fruit")
region = Tamarind.knownDatabaseServers[Tamarind.serverName].region
Tamarind.dynamoDBClient = new DynamoDBClient(
region: region
credentials: fromCognitoIdentityPool(
client: new CognitoIdentityClient({region})
identityPoolId: Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId
)
)
Tamarind.updateGateway(databaseOrGatewayName)
Tamarind.setupCouchDBClient = (serverName, databaseOrGatewayName) =>
console.info "Setting up #{serverName} #{databaseOrGatewayName}"
Tamarind.dynamoDBClient = null
username = Cookie.get("username")
password = Cookie.get("password")
unless username and password
Tamarind.targetUrl = document.location.hash.replace(/#/,"")
return router.navigate "server/#{Tamarind.serverName}", trigger:true
serverUrlWithCredentials = "#{Tamarind.knownDatabaseServers[serverName]}".replace(/:\/\//, "://#{username}:#{password}@")
Tamarind.user = new User()
if Tamarind.localDatabaseMirror?.remoteDatabase.name is "#{serverUrlWithCredentials}/#{databaseOrGatewayName}"
if await Tamarind.authenticate(Tamarind.localDatabaseMirror.remoteDatabase)
console.info "#{serverName} #{databaseOrGatewayName} already setup"
else
return
Tamarind.localDatabaseMirror = await Tamarind.getLocalMirrorForCouchDB(serverUrlWithCredentials, databaseOrGatewayName)
Tamarind.database = Tamarind.localDatabaseMirror.remoteDatabase
Tamarind.databaseName = databaseOrGatewayName
Tamarind.getLocalMirrorForCouchDB = (serverUrlWithCredentials, databaseName) =>
remoteDatabase = new PouchDB("#{serverUrlWithCredentials}/#{databaseName}")
localDatabaseMirror = new PouchDB("#{serverUrlWithCredentials.replace(/^.*@/,"").replace(/^.*\/\//,"")}/#{databaseName}")
localDatabaseMirror.remoteDatabase = remoteDatabase
remoteDatabase.localDatabaseMirror = localDatabaseMirror
return unless await Tamarind.authenticate(remoteDatabase)
if (await localDatabaseMirror.get("_local/availableFields").catch (error) => Promise.resolve false)
# Do this in the background 10 seconds later in case there have been updates
_.delay =>
Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 10000
else
await Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
# Get configuration stuff first
# calculated-fields
# search query params
# indexes
# Need to replicate these since they get created/edited on client then synced to other clients
console.log "Getting Tamarind specific configuration data for #{databaseName}"
remoteDatabase.allDocs
startkey: "<KEY>
endkey: "<KEY>"
include_docs: false
.then (result) =>
console.log await remoteDatabase.replicate.to localDatabaseMirror,
doc_ids: _(result.rows).pluck "id"
last_seq = await localDatabaseMirror.get "_local/remote_last_seq"
.then (doc) => Promise.resolve doc.last_seq
.catch => Promise.resolve null
if last_seq
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
return Promise.resolve localDatabaseMirror
else
console.log "Setting up #{databaseName} for the first time"
console.log "Getting all of the #{databaseName} documents 1000 at a time"
await new Promise (resolve) =>
# Get all the docs in reverse order and put them in the mirror
# Use the last_seq to start handling changes after the initial grab of data
isZanzibarDatabase = remoteDatabase.name.match(/zanzibar\.cococloud\.co\/zanzibar/)
if isZanzibarDatabase
startkey = [{},""]
endkey = ["", ""]
else
startkey = "<KEY>"
endkey = "<KEY>"
skip = 0
last_seq = (await remoteDatabase.changes(limit:0, descending:true)).last_seq
loop
console.log "#{startkey} -> #{endkey}"
result = if isZanzibarDatabase
await remoteDatabase.query "results",
descending: true
startkey: startkey
endkey: endkey
limit: 5000
skip: skip
include_docs: true
else
await remoteDatabase.allDocs
descending: true
startkey: startkey
endkey: endkey
limit: 1000
skip: skip
include_docs: true
if result.rows.length is 0
console.log "Finished initial bulk load of document for #{databaseName}"
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
break
localDatabaseMirror.bulkDocs (_(result.rows).pluck "doc"),
new_edits: false
.then (bulkResults) =>
problemPuts = bulkResults.filter (result) => not result.ok
if problemPuts.length isnt 0
alert "Problem saving local data: #{JSON.stringify problemPuts}"
startkey = result.rows[result.rows.length - 1].key
skip = 1
# Resolve after the first iteration so we can start working with data while the rest continues to download
resolve()
Promise.resolve(localDatabaseMirror)
Tamarind.updateAvailableFields = (remoteDatabase, localDatabaseMirror) =>
console.log "Updating available fields"
remoteDatabase.query "fields",
reduce: true
group: true
.catch (error) =>
console.error error
if error.reason is "missing"
alert "Need to add available fields index"
password = prompt "Enter an admin password to setup a local mirror"
adminRemoteDatabase = new PouchDB(remoteDatabase.name.replace(/\/.*@/, "//admin:#{password}@"))
await adminRemoteDatabase.put
_id: "_design/fields",
language: "coffeescript",
views:
fields:
map: """
(doc) ->
if doc.collection is 'result' and doc.question
for key in Object.keys(doc)
if key? and key isnt ''
emit [doc.question, key]
"""
reduce: "_count"
_.delay =>
remoteDatabase.query "fields",
reduce: true
, 500
alert "Fields index added - may take a few minutes before it is ready to be used."
_.delay =>
return Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 1000
.then (result) =>
fieldsAndFrequencyByQuestion = {}
for row in result.rows
fieldsAndFrequencyByQuestion[row.key[0]] or= []
fieldsAndFrequencyByQuestion[row.key[0]].push
field: row.key[1]
frequency: row.value
await localDatabaseMirror.upsert "_local/availableFields", =>
fieldsAndFrequencyByQuestion: fieldsAndFrequencyByQuestion
console.log "Fields Updated"
Tamarind.watchRemoteChangesAndSaveLocally = (remoteDatabase, localDatabaseMirror, last_seq) =>
localDatabaseMirror.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = last_seq
doc
throttledUpdateChangeSeq = _.throttle ((database,seq) =>
database.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = seq
doc
), 5000
remoteDatabase.changes
since: last_seq
live: true
include_docs: true
.on "error", (error) => console.error error
.on "change", (change) =>
if change.doc.collection? is "result"
#console.log "Updates to a result doc. seq:#{change.seq}"
await localDatabaseMirror.put change.doc,
force: true
throttledUpdateChangeSeq(localDatabaseMirror, change.seq)
Tamarind.updateCurrentGateway = =>
Tamarind.updateGateway(Tamarind.gateway.gatewayName)
Tamarind.updateGateway = (gatewayName) =>
result = await Tamarind.dynamoDBClient.send(
new GetItemCommand(
TableName: "Configurations"
Key:
gatewayName:
"S": gatewayName
)
)
Tamarind.gateway = unmarshall(result.Item)
Tamarind.updateQuestionSetForCurrentGateway = (questionSet, options) =>
await Tamarind.updateCurrentGateway()
Tamarind.gateway["Question Sets"][questionSet.label] = questionSet
if options?.delete is true
delete Tamarind.gateway["Question Sets"][questionSet.label]
Tamarind.dynamoDBClient.send(
new PutItemCommand(
TableName: "Configurations"
Item: marshall(Tamarind.gateway)
)
)
Tamarind.authenticate = (database) ->
unless await Tamarind.user.authenticate(database)
alert "User authentication failed. Logout and try again."
console.info "User authentication failed"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
unless Tamarind.user.has "Tamarind Access"
alert "User: #{Tamarind.user.username} does not have TamarindAccess. Logout and try again."
console.info "User: #{Tamarind.user.username} does not have TamarindAccess"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
return true
global.router = new Router()
Backbone.history.start()
| true | Backbone = require 'backbone'
global.$ = require 'jquery'
Backbone.$ = $
global.Cookie = require 'js-cookie'
global.moment = require 'moment'
global._ = require 'underscore'
global.PouchDB = require('pouchdb-core')
PouchDB
.plugin(require 'pouchdb-adapter-http')
.plugin(require 'pouchdb-adapter-idb')
.plugin(require 'pouchdb-mapreduce')
.plugin(require 'pouchdb-replication')
.plugin(require 'pouchdb-upsert')
.plugin(require 'pouchdb-changes-filter')
.plugin(require 'pouchdb-find')
{ CognitoIdentityClient } = require("@aws-sdk/client-cognito-identity")
{ fromCognitoIdentityPool } = require("@aws-sdk/credential-provider-cognito-identity")
{ DynamoDBClient } = require("@aws-sdk/client-dynamodb")
{ PutItemCommand, GetItemCommand, ScanCommand } = require("@aws-sdk/client-dynamodb")
{ marshall, unmarshall } = require("@aws-sdk/util-dynamodb")
Router = require './Router'
User = require './models/User'
global.Tamarind =
knownDatabaseServers:
Zanzibar: "https://zanzibar.cococloud.co"
Kigelia: "https://kigelia.cococloud.co"
Ceshhar: "https://ceshhar.cococloud.co"
Keep: "https://keep.cococloud.co"
Local: "http://localhost:5984"
MikeAWS:
region: "us-east-1"
IdentityPoolId: 'us-east-1:#INSERT HERE"
gooseberryEndpoint: "https://f9l1259lmb.execute-api.us-east-1.amazonaws.com/gooseberry"
Tamarind.serverCredentials = {}
for name, url of Tamarind.knownDatabaseServers
credentials = Cookie.get("#{name}-credentials")
Tamarind.serverCredentials[name] = credentials if credentials
## GLOBAL FUNCTIONS ##
#
Tamarind.canCreateDesignDoc = (database) =>
database or= Tamarind.database
database.put {_id:"_design/test"}
.then (result) =>
database.remove
_id: result.id
_rev: result.rev
Promise.resolve(true)
.catch (error) =>
if error.status is 403
Promise.resolve(false)
Tamarind.setupDatabase = (serverName, databaseOrGatewayName) =>
Tamarind.serverName = serverName
if Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId # DynamoDB
Tamarind.setupDynamoDBClient(serverName, databaseOrGatewayName)
else
Tamarind.setupCouchDBClient(serverName, databaseOrGatewayName)
Tamarind.setupDynamoDBClient = (serverName, databaseOrGatewayName) =>
Tamarind.database = null
unless Tamarind.dynamoDBClient?
if Cookie.get("password") is "hungry for fruit" or prompt("Password:").toLowerCase() is "hungry for fruit"
Cookie.set("password","hunPI:PASSWORD:<PASSWORD>END_PI for fruit")
region = Tamarind.knownDatabaseServers[Tamarind.serverName].region
Tamarind.dynamoDBClient = new DynamoDBClient(
region: region
credentials: fromCognitoIdentityPool(
client: new CognitoIdentityClient({region})
identityPoolId: Tamarind.knownDatabaseServers[Tamarind.serverName].IdentityPoolId
)
)
Tamarind.updateGateway(databaseOrGatewayName)
Tamarind.setupCouchDBClient = (serverName, databaseOrGatewayName) =>
console.info "Setting up #{serverName} #{databaseOrGatewayName}"
Tamarind.dynamoDBClient = null
username = Cookie.get("username")
password = Cookie.get("password")
unless username and password
Tamarind.targetUrl = document.location.hash.replace(/#/,"")
return router.navigate "server/#{Tamarind.serverName}", trigger:true
serverUrlWithCredentials = "#{Tamarind.knownDatabaseServers[serverName]}".replace(/:\/\//, "://#{username}:#{password}@")
Tamarind.user = new User()
if Tamarind.localDatabaseMirror?.remoteDatabase.name is "#{serverUrlWithCredentials}/#{databaseOrGatewayName}"
if await Tamarind.authenticate(Tamarind.localDatabaseMirror.remoteDatabase)
console.info "#{serverName} #{databaseOrGatewayName} already setup"
else
return
Tamarind.localDatabaseMirror = await Tamarind.getLocalMirrorForCouchDB(serverUrlWithCredentials, databaseOrGatewayName)
Tamarind.database = Tamarind.localDatabaseMirror.remoteDatabase
Tamarind.databaseName = databaseOrGatewayName
Tamarind.getLocalMirrorForCouchDB = (serverUrlWithCredentials, databaseName) =>
remoteDatabase = new PouchDB("#{serverUrlWithCredentials}/#{databaseName}")
localDatabaseMirror = new PouchDB("#{serverUrlWithCredentials.replace(/^.*@/,"").replace(/^.*\/\//,"")}/#{databaseName}")
localDatabaseMirror.remoteDatabase = remoteDatabase
remoteDatabase.localDatabaseMirror = localDatabaseMirror
return unless await Tamarind.authenticate(remoteDatabase)
if (await localDatabaseMirror.get("_local/availableFields").catch (error) => Promise.resolve false)
# Do this in the background 10 seconds later in case there have been updates
_.delay =>
Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 10000
else
await Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
# Get configuration stuff first
# calculated-fields
# search query params
# indexes
# Need to replicate these since they get created/edited on client then synced to other clients
console.log "Getting Tamarind specific configuration data for #{databaseName}"
remoteDatabase.allDocs
startkey: "PI:KEY:<KEY>END_PI
endkey: "PI:KEY:<KEY>END_PI"
include_docs: false
.then (result) =>
console.log await remoteDatabase.replicate.to localDatabaseMirror,
doc_ids: _(result.rows).pluck "id"
last_seq = await localDatabaseMirror.get "_local/remote_last_seq"
.then (doc) => Promise.resolve doc.last_seq
.catch => Promise.resolve null
if last_seq
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
return Promise.resolve localDatabaseMirror
else
console.log "Setting up #{databaseName} for the first time"
console.log "Getting all of the #{databaseName} documents 1000 at a time"
await new Promise (resolve) =>
# Get all the docs in reverse order and put them in the mirror
# Use the last_seq to start handling changes after the initial grab of data
isZanzibarDatabase = remoteDatabase.name.match(/zanzibar\.cococloud\.co\/zanzibar/)
if isZanzibarDatabase
startkey = [{},""]
endkey = ["", ""]
else
startkey = "PI:KEY:<KEY>END_PI"
endkey = "PI:KEY:<KEY>END_PI"
skip = 0
last_seq = (await remoteDatabase.changes(limit:0, descending:true)).last_seq
loop
console.log "#{startkey} -> #{endkey}"
result = if isZanzibarDatabase
await remoteDatabase.query "results",
descending: true
startkey: startkey
endkey: endkey
limit: 5000
skip: skip
include_docs: true
else
await remoteDatabase.allDocs
descending: true
startkey: startkey
endkey: endkey
limit: 1000
skip: skip
include_docs: true
if result.rows.length is 0
console.log "Finished initial bulk load of document for #{databaseName}"
Tamarind.watchRemoteChangesAndSaveLocally(remoteDatabase, localDatabaseMirror, last_seq)
break
localDatabaseMirror.bulkDocs (_(result.rows).pluck "doc"),
new_edits: false
.then (bulkResults) =>
problemPuts = bulkResults.filter (result) => not result.ok
if problemPuts.length isnt 0
alert "Problem saving local data: #{JSON.stringify problemPuts}"
startkey = result.rows[result.rows.length - 1].key
skip = 1
# Resolve after the first iteration so we can start working with data while the rest continues to download
resolve()
Promise.resolve(localDatabaseMirror)
Tamarind.updateAvailableFields = (remoteDatabase, localDatabaseMirror) =>
console.log "Updating available fields"
remoteDatabase.query "fields",
reduce: true
group: true
.catch (error) =>
console.error error
if error.reason is "missing"
alert "Need to add available fields index"
password = prompt "Enter an admin password to setup a local mirror"
adminRemoteDatabase = new PouchDB(remoteDatabase.name.replace(/\/.*@/, "//admin:#{password}@"))
await adminRemoteDatabase.put
_id: "_design/fields",
language: "coffeescript",
views:
fields:
map: """
(doc) ->
if doc.collection is 'result' and doc.question
for key in Object.keys(doc)
if key? and key isnt ''
emit [doc.question, key]
"""
reduce: "_count"
_.delay =>
remoteDatabase.query "fields",
reduce: true
, 500
alert "Fields index added - may take a few minutes before it is ready to be used."
_.delay =>
return Tamarind.updateAvailableFields(remoteDatabase, localDatabaseMirror)
, 1000
.then (result) =>
fieldsAndFrequencyByQuestion = {}
for row in result.rows
fieldsAndFrequencyByQuestion[row.key[0]] or= []
fieldsAndFrequencyByQuestion[row.key[0]].push
field: row.key[1]
frequency: row.value
await localDatabaseMirror.upsert "_local/availableFields", =>
fieldsAndFrequencyByQuestion: fieldsAndFrequencyByQuestion
console.log "Fields Updated"
Tamarind.watchRemoteChangesAndSaveLocally = (remoteDatabase, localDatabaseMirror, last_seq) =>
localDatabaseMirror.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = last_seq
doc
throttledUpdateChangeSeq = _.throttle ((database,seq) =>
database.upsert "_local/remote_last_seq", (doc) =>
doc.last_seq = seq
doc
), 5000
remoteDatabase.changes
since: last_seq
live: true
include_docs: true
.on "error", (error) => console.error error
.on "change", (change) =>
if change.doc.collection? is "result"
#console.log "Updates to a result doc. seq:#{change.seq}"
await localDatabaseMirror.put change.doc,
force: true
throttledUpdateChangeSeq(localDatabaseMirror, change.seq)
Tamarind.updateCurrentGateway = =>
Tamarind.updateGateway(Tamarind.gateway.gatewayName)
Tamarind.updateGateway = (gatewayName) =>
result = await Tamarind.dynamoDBClient.send(
new GetItemCommand(
TableName: "Configurations"
Key:
gatewayName:
"S": gatewayName
)
)
Tamarind.gateway = unmarshall(result.Item)
Tamarind.updateQuestionSetForCurrentGateway = (questionSet, options) =>
await Tamarind.updateCurrentGateway()
Tamarind.gateway["Question Sets"][questionSet.label] = questionSet
if options?.delete is true
delete Tamarind.gateway["Question Sets"][questionSet.label]
Tamarind.dynamoDBClient.send(
new PutItemCommand(
TableName: "Configurations"
Item: marshall(Tamarind.gateway)
)
)
Tamarind.authenticate = (database) ->
unless await Tamarind.user.authenticate(database)
alert "User authentication failed. Logout and try again."
console.info "User authentication failed"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
unless Tamarind.user.has "Tamarind Access"
alert "User: #{Tamarind.user.username} does not have TamarindAccess. Logout and try again."
console.info "User: #{Tamarind.user.username} does not have TamarindAccess"
Tamarind.localDatabaseMirror = null
router.navigate "server/#{Tamarind.serverName}", trigger:true
return false
return true
global.router = new Router()
Backbone.history.start()
|
[
{
"context": "AndValidate(\n { type: 'email', value: 'tom@creative-workflow.berlin' }\n )\n\n it 'fails with invalid in",
"end": 611,
"score": 0.9999253749847412,
"start": 583,
"tag": "EMAIL",
"value": "tom@creative-workflow.berlin"
},
{
"context": "ateElem... | spec/rules_builtin.spec.coffee | creative-workflow/jquery.input.validator | 0 | describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
generateAndValidate = (element) ->
validator.validateOne(
helper.generateElement(element)
)
describe "validateOne", ->
describe "rules", ->
describe "email", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'email' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'email', value: 'tom@creative-workflow.berlin' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'email', value: 'invalid.email' }
)
describe "tel", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'tel' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'tel', value: '+49 (30) / 443322' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'tel', value: 'invalid.phone' }
)
describe "number", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12' }
)
describe "max", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number', max: '12' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '13' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '13', max: '12' }
)
describe "min", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', min: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '11' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '11', min: '12' }
)
# some browser passing empty string when invalid input for type number
# it 'fails with invalid input', ->
#
describe "required", ->
it 'succeeds without attribute', ->
helper.expectValid generateAndValidate(
{ type: 'text' }
)
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', required: true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', required: true}
)
describe "maxlength", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '3', maxlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', maxlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'abcd', maxlength: '3' }
)
describe "minlength", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', minlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', minlength: '3' }
)
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abcd', minlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'av', minlength: '3' }
)
describe "pattern", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', pattern:"^\\d*$" }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '123', pattern:"^\\d*$" }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12a', pattern:"^\\d*$" }
)
describe "hasClass", ->
it 'succeeds with valid class', ->
helper.expectValid generateAndValidate(
{ type: 'text', class: 'class', 'data-rule-has-class': 'class' }
)
it 'fails with invalid class', ->
helper.expectInValid generateAndValidate(
{ type: 'text', 'data-rule-has-class': 'class' }
)
describe "decimal", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', 'data-rule-decimal': true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '12.2', 'data-rule-decimal': true}
)
helper.expectValid generateAndValidate(
{ type: 'text', value: '12', 'data-rule-decimal': true}
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12g', 'data-rule-decimal': true}
)
describe "equal", ->
it 'fails with unequal input', ->
p1 = helper.generateElement(
{type: 'password', value: 42, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: 41, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectInValid(
equalValidator.validateOne(p2, div)
)
it 'succeeds with equal input', ->
p1 = helper.generateElement(
{type: 'password', value: 42, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: 42, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectValid(
equalValidator.validateOne(p2, div)
)
| 35106 | describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
generateAndValidate = (element) ->
validator.validateOne(
helper.generateElement(element)
)
describe "validateOne", ->
describe "rules", ->
describe "email", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'email' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'email', value: '<EMAIL>' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'email', value: 'invalid.email' }
)
describe "tel", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'tel' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'tel', value: '+49 (30) / 443322' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'tel', value: 'invalid.phone' }
)
describe "number", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12' }
)
describe "max", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number', max: '12' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '13' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '13', max: '12' }
)
describe "min", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', min: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '11' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '11', min: '12' }
)
# some browser passing empty string when invalid input for type number
# it 'fails with invalid input', ->
#
describe "required", ->
it 'succeeds without attribute', ->
helper.expectValid generateAndValidate(
{ type: 'text' }
)
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', required: true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', required: true}
)
describe "maxlength", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '3', maxlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', maxlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'abcd', maxlength: '3' }
)
describe "minlength", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', minlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', minlength: '3' }
)
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abcd', minlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'av', minlength: '3' }
)
describe "pattern", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', pattern:"^\\d*$" }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '123', pattern:"^\\d*$" }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12a', pattern:"^\\d*$" }
)
describe "hasClass", ->
it 'succeeds with valid class', ->
helper.expectValid generateAndValidate(
{ type: 'text', class: 'class', 'data-rule-has-class': 'class' }
)
it 'fails with invalid class', ->
helper.expectInValid generateAndValidate(
{ type: 'text', 'data-rule-has-class': 'class' }
)
describe "decimal", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', 'data-rule-decimal': true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '12.2', 'data-rule-decimal': true}
)
helper.expectValid generateAndValidate(
{ type: 'text', value: '12', 'data-rule-decimal': true}
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12g', 'data-rule-decimal': true}
)
describe "equal", ->
it 'fails with unequal input', ->
p1 = helper.generateElement(
{type: 'password', value: 42, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: 41, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectInValid(
equalValidator.validateOne(p2, div)
)
it 'succeeds with equal input', ->
p1 = helper.generateElement(
{type: 'password', value: <PASSWORD>2, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: <PASSWORD>2, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectValid(
equalValidator.validateOne(p2, div)
)
| true | describe 'jquery.input.validator', ->
$ = jQuery
helper = jasmine.helper
validator = $('body').iValidator()
generateAndValidate = (element) ->
validator.validateOne(
helper.generateElement(element)
)
describe "validateOne", ->
describe "rules", ->
describe "email", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'email' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'email', value: 'PI:EMAIL:<EMAIL>END_PI' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'email', value: 'invalid.email' }
)
describe "tel", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'tel' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'tel', value: '+49 (30) / 443322' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'tel', value: 'invalid.phone' }
)
describe "number", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12' }
)
describe "max", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'number', max: '12' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', max: '13' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '13', max: '12' }
)
describe "min", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', min: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '12' }
)
helper.expectValid generateAndValidate(
{ type: 'number', value: '12', min: '11' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'number', value: '11', min: '12' }
)
# some browser passing empty string when invalid input for type number
# it 'fails with invalid input', ->
#
describe "required", ->
it 'succeeds without attribute', ->
helper.expectValid generateAndValidate(
{ type: 'text' }
)
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', required: true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', required: true}
)
describe "maxlength", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '3', maxlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', maxlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'abcd', maxlength: '3' }
)
describe "minlength", ->
it 'fails with empty input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', minlength: '3' }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abc', minlength: '3' }
)
helper.expectValid generateAndValidate(
{ type: 'text', value: 'abcd', minlength: '3' }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: 'av', minlength: '3' }
)
describe "pattern", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', pattern:"^\\d*$" }
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '123', pattern:"^\\d*$" }
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12a', pattern:"^\\d*$" }
)
describe "hasClass", ->
it 'succeeds with valid class', ->
helper.expectValid generateAndValidate(
{ type: 'text', class: 'class', 'data-rule-has-class': 'class' }
)
it 'fails with invalid class', ->
helper.expectInValid generateAndValidate(
{ type: 'text', 'data-rule-has-class': 'class' }
)
describe "decimal", ->
it 'succeeds with empty input', ->
helper.expectValid generateAndValidate(
{ type: 'text', 'data-rule-decimal': true}
)
it 'succeeds with valid input', ->
helper.expectValid generateAndValidate(
{ type: 'text', value: '12.2', 'data-rule-decimal': true}
)
helper.expectValid generateAndValidate(
{ type: 'text', value: '12', 'data-rule-decimal': true}
)
it 'fails with invalid input', ->
helper.expectInValid generateAndValidate(
{ type: 'text', value: '12g', 'data-rule-decimal': true}
)
describe "equal", ->
it 'fails with unequal input', ->
p1 = helper.generateElement(
{type: 'password', value: 42, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: 41, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectInValid(
equalValidator.validateOne(p2, div)
)
it 'succeeds with equal input', ->
p1 = helper.generateElement(
{type: 'password', value: PI:PASSWORD:<PASSWORD>END_PI2, required: true, class: 'password1'}
)
p2 = helper.generateElement(
{type: 'password', value: PI:PASSWORD:<PASSWORD>END_PI2, required: true, class: 'password2', 'data-rule-is-equal-to':'.password1'}
)
div = $('<div\>').append($('<div\>').append(p1).append(p2))
equalValidator = new InputValidator(div, {})
helper.expectValid(
equalValidator.validateOne(p2, div)
)
|
[
{
"context": "= i18nService.get 'homeAbout'\n\n WARNING_KEY = 'warningSeen'\n warningSeen = () -> \n window.localStora",
"end": 581,
"score": 0.9941695928573608,
"start": 570,
"tag": "KEY",
"value": "warningSeen"
}
] | source/js/controllers/home_controller.coffee | jusso-dev/jila-mobile | 6 | class Controller
constructor: ($scope, $rootScope, i18nService) ->
$rootScope.$emit 'navigationConfig',
labelForTitle: i18nService.get 'homeTitle'
backAction: null
$scope.labelForDictionary = i18nService.get 'homeDictionary'
$scope.labelForCategories = i18nService.get 'homeCategories'
$scope.labelForLearn = i18nService.get 'homeLearn'
$scope.labelForCommon = i18nService.get 'homeCommon'
$scope.labelForWordOfTheDay = i18nService.get 'homeWordOfTheDay'
$scope.labelForAbout = i18nService.get 'homeAbout'
WARNING_KEY = 'warningSeen'
warningSeen = () ->
window.localStorage[WARNING_KEY] = true
return
showWarningMessage = () ->
warningTitle = i18nService.get 'homeWarningTitle'
warningButton = i18nService.get 'acknowledgeButton'
warningMessage = i18nService.get 'homeWarningMessage'
if navigator.notification
navigator.notification.alert warningMessage, warningSeen, warningTitle, warningButton
else
alert warningMessage
warningSeen()
showWarningMessage() unless window.localStorage[WARNING_KEY]
angular.module('app').controller 'homeController', ['$scope', '$rootScope', 'i18nService', Controller] | 73415 | class Controller
constructor: ($scope, $rootScope, i18nService) ->
$rootScope.$emit 'navigationConfig',
labelForTitle: i18nService.get 'homeTitle'
backAction: null
$scope.labelForDictionary = i18nService.get 'homeDictionary'
$scope.labelForCategories = i18nService.get 'homeCategories'
$scope.labelForLearn = i18nService.get 'homeLearn'
$scope.labelForCommon = i18nService.get 'homeCommon'
$scope.labelForWordOfTheDay = i18nService.get 'homeWordOfTheDay'
$scope.labelForAbout = i18nService.get 'homeAbout'
WARNING_KEY = '<KEY>'
warningSeen = () ->
window.localStorage[WARNING_KEY] = true
return
showWarningMessage = () ->
warningTitle = i18nService.get 'homeWarningTitle'
warningButton = i18nService.get 'acknowledgeButton'
warningMessage = i18nService.get 'homeWarningMessage'
if navigator.notification
navigator.notification.alert warningMessage, warningSeen, warningTitle, warningButton
else
alert warningMessage
warningSeen()
showWarningMessage() unless window.localStorage[WARNING_KEY]
angular.module('app').controller 'homeController', ['$scope', '$rootScope', 'i18nService', Controller] | true | class Controller
constructor: ($scope, $rootScope, i18nService) ->
$rootScope.$emit 'navigationConfig',
labelForTitle: i18nService.get 'homeTitle'
backAction: null
$scope.labelForDictionary = i18nService.get 'homeDictionary'
$scope.labelForCategories = i18nService.get 'homeCategories'
$scope.labelForLearn = i18nService.get 'homeLearn'
$scope.labelForCommon = i18nService.get 'homeCommon'
$scope.labelForWordOfTheDay = i18nService.get 'homeWordOfTheDay'
$scope.labelForAbout = i18nService.get 'homeAbout'
WARNING_KEY = 'PI:KEY:<KEY>END_PI'
warningSeen = () ->
window.localStorage[WARNING_KEY] = true
return
showWarningMessage = () ->
warningTitle = i18nService.get 'homeWarningTitle'
warningButton = i18nService.get 'acknowledgeButton'
warningMessage = i18nService.get 'homeWarningMessage'
if navigator.notification
navigator.notification.alert warningMessage, warningSeen, warningTitle, warningButton
else
alert warningMessage
warningSeen()
showWarningMessage() unless window.localStorage[WARNING_KEY]
angular.module('app').controller 'homeController', ['$scope', '$rootScope', 'i18nService', Controller] |
[
{
"context": "s']?.replace '{{title}}', title\n\n @name = name\n @title = title || name\n @state",
"end": 4086,
"score": 0.4641013741493225,
"start": 4082,
"tag": "NAME",
"value": "name"
}
] | app/ngapp/docflow/ui/actions.coffee | delightsoft/DSCommon | 1 | module = angular.module 'docflow.ui.actions', ['docflow.config']
module.constant 'docflowActionInProgressShowAfterDelayTime', 2000
module.constant 'docflowActionDoneHideDelayTime', 3000
module.directive 'docflowActionsContainer',
['$docflowActions', '$compile', '$animate',
(($docflowActions, $compile, $animate) ->
return {
restrict: 'A'
scope: true
controller: ['$scope', (($scope) ->
@contentTransclude = null
@contentElement = null
return)]
link: (($scope, element, attrs, ctrl) ->
messageScope = null
currentElement = null
options = $scope.$eval attrs.docflowActionsContainer
container =
errorOnly: !!options?.errorOnly
setAction: ((action) ->
$scope.action = action
return)
$docflowActions.add container
$scope.$watch 'action.message', ((message) ->
if messageScope
$animate.leave(currentElement)
currentElement = null
messageScope.$destroy()
messageScope = null
if message
messageScope = $scope.$new()
ctrl.contentTransclude messageScope, ((clone) ->
currentElement = clone
currentElement.html message
$compile(currentElement.contents())(messageScope)
$animate.enter(currentElement, null, ctrl.contentElement);
return)
return)
$scope.$on '$destroy', (->
$docflowActions.remove container
return)
return)
}
)]
module.directive 'docflowActionsContainerContent',
['$docflowActions', '$compile',
(($docflowActions, $compile) ->
return {
restrict: 'EA'
require: '^docflowActionsContainer'
transclude: 'element'
link: (($scope, element, attrs, container, $transclude) ->
container.contentTransclude = $transclude
container.contentElement = element
return)
}
)]
module.directive 'docflowActionsAutohide',
['$docflowActions', 'docflowActionDoneHideDelayTime', '$timeout',
(($docflowActions, docflowActionDoneHideDelayTime, $timeout) ->
return {
restrict: 'EA'
scope: true
link: (($scope, element, attrs) ->
$scope.action.showClose = false
$timeout (->
$scope.action?.hide()
return), docflowActionDoneHideDelayTime
return)
}
)]
module.factory '$docflowActions',
['$docflowConfig', '$docflowUtils', 'docflowActionInProgressShowAfterDelayTime', 'docflowActionDoneHideDelayTime', '$rootScope', '$timeout',
(($docflowConfig, $docflowUtils, docflowActionInProgressShowAfterDelayTime, docflowActionDoneHideDelayTime, $rootScope, $timeout) ->
currentAction = null
currentContainer = null
containers = []
selectContainer = ((action) ->
if currentAction != action and currentContainer
currentContainer.setAction null
currentContainer = null
currentAction = action
if containers.length > 0
container = containers[0]
if action.state != 'failed'
for cont in containers
if not cont.errorOnly
container = cont
break
if currentContainer != container
if currentContainer
currentContainer.setAction null
(currentContainer = container).setAction action
return)
preserveActionResultOverUIStateTransitionCount = 0
return {
containers: containers
Action: (class Action
constructor: ((docId, name, promise) ->
if not docId
throw Error 'id argument is missing'
if not name
throw Error 'name argument is missing'
if not promise
throw Error 'promise argument is missing'
sid = $docflowUtils.splitFullId docId
title = $docflowConfig.docs[sid.docType]?.actions?[name]?.title
title = name if not title
message = $docflowConfig.messages['actionProgress']?.replace '{{title}}', title
@name = name
@title = title || name
@state = 'progress'
@message = null
@promise = promise
@showClose = false
if message
@forceShowMessage = forceShowMessage = (=>
if @state == 'progress'
@message = message
return)
$timeout forceShowMessage, docflowActionInProgressShowAfterDelayTime
promise.then(
((doneMessage) =>
@state = 'done'
if @name == 'list' # it's a special built-in action
@message = doneMessage
else if doneMessage
@showClose = true
@message = doneMessage
else
$timeout (=>
@hide()
return), docflowActionDoneHideDelayTime
@message = $docflowConfig.messages['actionDone']?.replace '{{title}}', @title
return),
((failedMessage) =>
@state = 'failed'
@showClose = true
@message = if failedMessage
@message = failedMessage
else
@message = $docflowConfig.messages['actionFailed']?.replace '{{title}}', @title
return)
)
return)
hide: (->
if currentAction == @
currentContainer?.setAction(null)
return))
setPreserveActionResultOverUIStateTransition: (->
preserveActionResultOverUIStateTransitionCount = 4 # Hack: It's because for some reasons ui-router create initialized editor form TWICE.
return)
add: ((container) ->
containers.unshift container
if currentAction and currentContainer
currentContainer.setAction null
currentContainer = null
if preserveActionResultOverUIStateTransitionCount > 0 and currentAction
if --preserveActionResultOverUIStateTransitionCount == 0
currentContainer = container
container.setAction currentAction
return)
remove: ((container) ->
if (p = containers.indexOf container) >= 0
containers.splice p, 1
if currentContainer == container
currentContainer = null
if currentAction.state != 'failed'
selectContainer currentAction
return)
send: ((action) ->
selectContainer action
action.promise.then((-> selectContainer(action)), (-> selectContainer(action)))
return)
}
)]
| 62237 | module = angular.module 'docflow.ui.actions', ['docflow.config']
module.constant 'docflowActionInProgressShowAfterDelayTime', 2000
module.constant 'docflowActionDoneHideDelayTime', 3000
module.directive 'docflowActionsContainer',
['$docflowActions', '$compile', '$animate',
(($docflowActions, $compile, $animate) ->
return {
restrict: 'A'
scope: true
controller: ['$scope', (($scope) ->
@contentTransclude = null
@contentElement = null
return)]
link: (($scope, element, attrs, ctrl) ->
messageScope = null
currentElement = null
options = $scope.$eval attrs.docflowActionsContainer
container =
errorOnly: !!options?.errorOnly
setAction: ((action) ->
$scope.action = action
return)
$docflowActions.add container
$scope.$watch 'action.message', ((message) ->
if messageScope
$animate.leave(currentElement)
currentElement = null
messageScope.$destroy()
messageScope = null
if message
messageScope = $scope.$new()
ctrl.contentTransclude messageScope, ((clone) ->
currentElement = clone
currentElement.html message
$compile(currentElement.contents())(messageScope)
$animate.enter(currentElement, null, ctrl.contentElement);
return)
return)
$scope.$on '$destroy', (->
$docflowActions.remove container
return)
return)
}
)]
module.directive 'docflowActionsContainerContent',
['$docflowActions', '$compile',
(($docflowActions, $compile) ->
return {
restrict: 'EA'
require: '^docflowActionsContainer'
transclude: 'element'
link: (($scope, element, attrs, container, $transclude) ->
container.contentTransclude = $transclude
container.contentElement = element
return)
}
)]
module.directive 'docflowActionsAutohide',
['$docflowActions', 'docflowActionDoneHideDelayTime', '$timeout',
(($docflowActions, docflowActionDoneHideDelayTime, $timeout) ->
return {
restrict: 'EA'
scope: true
link: (($scope, element, attrs) ->
$scope.action.showClose = false
$timeout (->
$scope.action?.hide()
return), docflowActionDoneHideDelayTime
return)
}
)]
module.factory '$docflowActions',
['$docflowConfig', '$docflowUtils', 'docflowActionInProgressShowAfterDelayTime', 'docflowActionDoneHideDelayTime', '$rootScope', '$timeout',
(($docflowConfig, $docflowUtils, docflowActionInProgressShowAfterDelayTime, docflowActionDoneHideDelayTime, $rootScope, $timeout) ->
currentAction = null
currentContainer = null
containers = []
selectContainer = ((action) ->
if currentAction != action and currentContainer
currentContainer.setAction null
currentContainer = null
currentAction = action
if containers.length > 0
container = containers[0]
if action.state != 'failed'
for cont in containers
if not cont.errorOnly
container = cont
break
if currentContainer != container
if currentContainer
currentContainer.setAction null
(currentContainer = container).setAction action
return)
preserveActionResultOverUIStateTransitionCount = 0
return {
containers: containers
Action: (class Action
constructor: ((docId, name, promise) ->
if not docId
throw Error 'id argument is missing'
if not name
throw Error 'name argument is missing'
if not promise
throw Error 'promise argument is missing'
sid = $docflowUtils.splitFullId docId
title = $docflowConfig.docs[sid.docType]?.actions?[name]?.title
title = name if not title
message = $docflowConfig.messages['actionProgress']?.replace '{{title}}', title
@name = <NAME>
@title = title || name
@state = 'progress'
@message = null
@promise = promise
@showClose = false
if message
@forceShowMessage = forceShowMessage = (=>
if @state == 'progress'
@message = message
return)
$timeout forceShowMessage, docflowActionInProgressShowAfterDelayTime
promise.then(
((doneMessage) =>
@state = 'done'
if @name == 'list' # it's a special built-in action
@message = doneMessage
else if doneMessage
@showClose = true
@message = doneMessage
else
$timeout (=>
@hide()
return), docflowActionDoneHideDelayTime
@message = $docflowConfig.messages['actionDone']?.replace '{{title}}', @title
return),
((failedMessage) =>
@state = 'failed'
@showClose = true
@message = if failedMessage
@message = failedMessage
else
@message = $docflowConfig.messages['actionFailed']?.replace '{{title}}', @title
return)
)
return)
hide: (->
if currentAction == @
currentContainer?.setAction(null)
return))
setPreserveActionResultOverUIStateTransition: (->
preserveActionResultOverUIStateTransitionCount = 4 # Hack: It's because for some reasons ui-router create initialized editor form TWICE.
return)
add: ((container) ->
containers.unshift container
if currentAction and currentContainer
currentContainer.setAction null
currentContainer = null
if preserveActionResultOverUIStateTransitionCount > 0 and currentAction
if --preserveActionResultOverUIStateTransitionCount == 0
currentContainer = container
container.setAction currentAction
return)
remove: ((container) ->
if (p = containers.indexOf container) >= 0
containers.splice p, 1
if currentContainer == container
currentContainer = null
if currentAction.state != 'failed'
selectContainer currentAction
return)
send: ((action) ->
selectContainer action
action.promise.then((-> selectContainer(action)), (-> selectContainer(action)))
return)
}
)]
| true | module = angular.module 'docflow.ui.actions', ['docflow.config']
module.constant 'docflowActionInProgressShowAfterDelayTime', 2000
module.constant 'docflowActionDoneHideDelayTime', 3000
module.directive 'docflowActionsContainer',
['$docflowActions', '$compile', '$animate',
(($docflowActions, $compile, $animate) ->
return {
restrict: 'A'
scope: true
controller: ['$scope', (($scope) ->
@contentTransclude = null
@contentElement = null
return)]
link: (($scope, element, attrs, ctrl) ->
messageScope = null
currentElement = null
options = $scope.$eval attrs.docflowActionsContainer
container =
errorOnly: !!options?.errorOnly
setAction: ((action) ->
$scope.action = action
return)
$docflowActions.add container
$scope.$watch 'action.message', ((message) ->
if messageScope
$animate.leave(currentElement)
currentElement = null
messageScope.$destroy()
messageScope = null
if message
messageScope = $scope.$new()
ctrl.contentTransclude messageScope, ((clone) ->
currentElement = clone
currentElement.html message
$compile(currentElement.contents())(messageScope)
$animate.enter(currentElement, null, ctrl.contentElement);
return)
return)
$scope.$on '$destroy', (->
$docflowActions.remove container
return)
return)
}
)]
module.directive 'docflowActionsContainerContent',
['$docflowActions', '$compile',
(($docflowActions, $compile) ->
return {
restrict: 'EA'
require: '^docflowActionsContainer'
transclude: 'element'
link: (($scope, element, attrs, container, $transclude) ->
container.contentTransclude = $transclude
container.contentElement = element
return)
}
)]
module.directive 'docflowActionsAutohide',
['$docflowActions', 'docflowActionDoneHideDelayTime', '$timeout',
(($docflowActions, docflowActionDoneHideDelayTime, $timeout) ->
return {
restrict: 'EA'
scope: true
link: (($scope, element, attrs) ->
$scope.action.showClose = false
$timeout (->
$scope.action?.hide()
return), docflowActionDoneHideDelayTime
return)
}
)]
module.factory '$docflowActions',
['$docflowConfig', '$docflowUtils', 'docflowActionInProgressShowAfterDelayTime', 'docflowActionDoneHideDelayTime', '$rootScope', '$timeout',
(($docflowConfig, $docflowUtils, docflowActionInProgressShowAfterDelayTime, docflowActionDoneHideDelayTime, $rootScope, $timeout) ->
currentAction = null
currentContainer = null
containers = []
selectContainer = ((action) ->
if currentAction != action and currentContainer
currentContainer.setAction null
currentContainer = null
currentAction = action
if containers.length > 0
container = containers[0]
if action.state != 'failed'
for cont in containers
if not cont.errorOnly
container = cont
break
if currentContainer != container
if currentContainer
currentContainer.setAction null
(currentContainer = container).setAction action
return)
preserveActionResultOverUIStateTransitionCount = 0
return {
containers: containers
Action: (class Action
constructor: ((docId, name, promise) ->
if not docId
throw Error 'id argument is missing'
if not name
throw Error 'name argument is missing'
if not promise
throw Error 'promise argument is missing'
sid = $docflowUtils.splitFullId docId
title = $docflowConfig.docs[sid.docType]?.actions?[name]?.title
title = name if not title
message = $docflowConfig.messages['actionProgress']?.replace '{{title}}', title
@name = PI:NAME:<NAME>END_PI
@title = title || name
@state = 'progress'
@message = null
@promise = promise
@showClose = false
if message
@forceShowMessage = forceShowMessage = (=>
if @state == 'progress'
@message = message
return)
$timeout forceShowMessage, docflowActionInProgressShowAfterDelayTime
promise.then(
((doneMessage) =>
@state = 'done'
if @name == 'list' # it's a special built-in action
@message = doneMessage
else if doneMessage
@showClose = true
@message = doneMessage
else
$timeout (=>
@hide()
return), docflowActionDoneHideDelayTime
@message = $docflowConfig.messages['actionDone']?.replace '{{title}}', @title
return),
((failedMessage) =>
@state = 'failed'
@showClose = true
@message = if failedMessage
@message = failedMessage
else
@message = $docflowConfig.messages['actionFailed']?.replace '{{title}}', @title
return)
)
return)
hide: (->
if currentAction == @
currentContainer?.setAction(null)
return))
setPreserveActionResultOverUIStateTransition: (->
preserveActionResultOverUIStateTransitionCount = 4 # Hack: It's because for some reasons ui-router create initialized editor form TWICE.
return)
add: ((container) ->
containers.unshift container
if currentAction and currentContainer
currentContainer.setAction null
currentContainer = null
if preserveActionResultOverUIStateTransitionCount > 0 and currentAction
if --preserveActionResultOverUIStateTransitionCount == 0
currentContainer = container
container.setAction currentAction
return)
remove: ((container) ->
if (p = containers.indexOf container) >= 0
containers.splice p, 1
if currentContainer == container
currentContainer = null
if currentAction.state != 'failed'
selectContainer currentAction
return)
send: ((action) ->
selectContainer action
action.promise.then((-> selectContainer(action)), (-> selectContainer(action)))
return)
}
)]
|
[
{
"context": "e connection\n request.get(\"/auth/temp?username=bot&password=bot\")\n .end (err, res) ->\n if er",
"end": 1584,
"score": 0.872797966003418,
"start": 1581,
"tag": "USERNAME",
"value": "bot"
},
{
"context": " request.get(\"/auth/temp?username=bot&password=b... | lobby/test/int/sockets/user-socket-int-test.coffee | towerstorm/game | 11 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require 'assert'
helpers = require '../helpers'
_ = require 'lodash'
socketIO = require('socket.io').listen(14001)
socketIO.set('log level', 1);
GlobalSocket = require('../../../sockets/global-socket.coffee')
globalSocket = new GlobalSocket(socketIO)
UserSocket = require('../../../sockets/user-socket.coffee')
userSocket = new UserSocket(socketIO)
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
tdb = require('database')
User = tdb.models.User
db = tdb.db
cookie = require('cookie')
cookieParser = require('cookie-parser')
connect = require('connect')
#request = require('request');
socketIO.on 'connect', (socket) ->
console.log("Person connected")
socketUrl = 'http://0.0.0.0:14001/sockets/user'
options = {
transports: ['websocket']
'force new connection': true
}
cookies = ""
userInfo = null
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "User Socket integration test", ->
beforeEach (done)->
#Create a temp user for this person and use there cookies in the connection
request.get("/auth/temp?username=bot&password=bot")
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
done()
it "It should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should send new user details when user changes happen", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
User.findById userInfo.id, (err, user) ->
user.set('elo', 1000)
user.save()
socket.on 'user.details', (details) ->
if details.elo == 1000
done()
it "Should not crash if the user does not exist for whatever reason", (done) ->
User.delete userInfo.id, (err, details) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if the users session has been deleted", (done) ->
parsedCookie = cookie.parse(cookies)
sessionId = cookieParser.signedCookie(parsedCookie['express.sid'], '908j0q3wr89j(Unhdaq9ra9s8)(J09jsdfjaqawr')
tdb.sessionStore.destroy sessionId, (err, dead) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if there is a db connection error with User.changes", (done) ->
done() #Don't know how to test this yet as I have no idea what could cause this to fail. Will see when errors log out.
| 172897 | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require 'assert'
helpers = require '../helpers'
_ = require 'lodash'
socketIO = require('socket.io').listen(14001)
socketIO.set('log level', 1);
GlobalSocket = require('../../../sockets/global-socket.coffee')
globalSocket = new GlobalSocket(socketIO)
UserSocket = require('../../../sockets/user-socket.coffee')
userSocket = new UserSocket(socketIO)
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
tdb = require('database')
User = tdb.models.User
db = tdb.db
cookie = require('cookie')
cookieParser = require('cookie-parser')
connect = require('connect')
#request = require('request');
socketIO.on 'connect', (socket) ->
console.log("Person connected")
socketUrl = 'http://0.0.0.0:14001/sockets/user'
options = {
transports: ['websocket']
'force new connection': true
}
cookies = ""
userInfo = null
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "User Socket integration test", ->
beforeEach (done)->
#Create a temp user for this person and use there cookies in the connection
request.get("/auth/temp?username=bot&password=<PASSWORD>")
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
done()
it "It should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should send new user details when user changes happen", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
User.findById userInfo.id, (err, user) ->
user.set('elo', 1000)
user.save()
socket.on 'user.details', (details) ->
if details.elo == 1000
done()
it "Should not crash if the user does not exist for whatever reason", (done) ->
User.delete userInfo.id, (err, details) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if the users session has been deleted", (done) ->
parsedCookie = cookie.parse(cookies)
sessionId = cookieParser.signedCookie(parsedCookie['express.sid'], '908j0q3wr89j(Unhdaq9ra9s8)(J09jsdfjaqawr')
tdb.sessionStore.destroy sessionId, (err, dead) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if there is a db connection error with User.changes", (done) ->
done() #Don't know how to test this yet as I have no idea what could cause this to fail. Will see when errors log out.
| true | app = require('../../../lib/app.coffee')
request = require("supertest")(app)
assert = require 'assert'
helpers = require '../helpers'
_ = require 'lodash'
socketIO = require('socket.io').listen(14001)
socketIO.set('log level', 1);
GlobalSocket = require('../../../sockets/global-socket.coffee')
globalSocket = new GlobalSocket(socketIO)
UserSocket = require('../../../sockets/user-socket.coffee')
userSocket = new UserSocket(socketIO)
cio = require('socket.io-client')
xhr = require('socket.io-client/node_modules/xmlhttprequest');
xhrOriginal = require('xmlhttprequest');
tdb = require('database')
User = tdb.models.User
db = tdb.db
cookie = require('cookie')
cookieParser = require('cookie-parser')
connect = require('connect')
#request = require('request');
socketIO.on 'connect', (socket) ->
console.log("Person connected")
socketUrl = 'http://0.0.0.0:14001/sockets/user'
options = {
transports: ['websocket']
'force new connection': true
}
cookies = ""
userInfo = null
overrideXmlHttpRequest = () ->
xhr.XMLHttpRequest = ->
@XMLHttpRequest = xhrOriginal.XMLHttpRequest;
xhrOriginal.XMLHttpRequest.apply(@, arguments);
this.setDisableHeaderCheck(true);
openOriginal = this.open;
this.open = (method, url, async, user, password) ->
openOriginal.apply(this, arguments);
this.setRequestHeader('cookie', cookies);
return @
overrideXmlHttpRequest()
describe "User Socket integration test", ->
beforeEach (done)->
#Create a temp user for this person and use there cookies in the connection
request.get("/auth/temp?username=bot&password=PI:PASSWORD:<PASSWORD>END_PI")
.end (err, res) ->
if err then return done(err)
userInfo = JSON.parse(res.text)
cookies = res.headers['set-cookie'].pop().split(';')[0]
done()
it "It should allow users to connect", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'error', (err) ->
done(new Error("Failed to connect, error is: " + err.message))
socket.on 'connect', ->
done()
it "Should send new user details when user changes happen", (done) ->
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
User.findById userInfo.id, (err, user) ->
user.set('elo', 1000)
user.save()
socket.on 'user.details', (details) ->
if details.elo == 1000
done()
it "Should not crash if the user does not exist for whatever reason", (done) ->
User.delete userInfo.id, (err, details) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if the users session has been deleted", (done) ->
parsedCookie = cookie.parse(cookies)
sessionId = cookieParser.signedCookie(parsedCookie['express.sid'], '908j0q3wr89j(Unhdaq9ra9s8)(J09jsdfjaqawr')
tdb.sessionStore.destroy sessionId, (err, dead) ->
if err then return done(err)
socket = cio.connect(socketUrl, options)
socket.on 'connect', ->
_.defer ->
done()
, 2000
it "Should not crash if there is a db connection error with User.changes", (done) ->
done() #Don't know how to test this yet as I have no idea what could cause this to fail. Will see when errors log out.
|
[
{
"context": "t is \"jira|github\")\n#\n# Commands:\n# \n# Author:\n# stuartf\n\nmodule.exports = (robot) ->\n cache = []\n\n # In",
"end": 515,
"score": 0.9996033310890198,
"start": 508,
"tag": "USERNAME",
"value": "stuartf"
},
{
"context": "= process.env.HUBOT_JIRA_USERNAME\n ... | src/scripts/jira-issues.coffee | fourkitchens/hubot-scripts | 1 | # Description:
# Looks up jira issues when they're mentioned in chat
#
# Will ignore users set in HUBOT_JIRA_IGNORE_USERS (by default, JIRA and GitHub).
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_URL (format: "https://jira-domain.com:9090")
# HUBOT_JIRA_IGNORECASE (optional; default is "true")
# HUBOT_JIRA_USERNAME (optional)
# HUBOT_JIRA_PASSWORD (optional)
# HUBOT_JIRA_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
#
# Commands:
#
# Author:
# stuartf
module.exports = (robot) ->
cache = []
# In case someone upgrades form the previous version, we'll default to the
# previous behavior.
jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}"
jiraUsername = process.env.HUBOT_JIRA_USERNAME
jiraPassword = process.env.HUBOT_JIRA_PASSWORD
if jiraUsername != undefined && jiraUsername.length > 0
auth = "#{jiraUsername}:#{jiraPassword}"
jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS
if jiraIgnoreUsers == undefined
jiraIgnoreUsers = "jira|github"
robot.http(jiraUrl + "/rest/api/2/project")
.auth(auth)
.get() (err, res, body) ->
json = JSON.parse(body)
jiraPrefixes = ( entry.key for entry in json )
reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y
jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g"
ic = process.env.HUBOT_JIRA_IGNORECASE
if ic == undefined || ic == "true"
jiraPattern += "i"
robot.hear eval(jiraPattern), (msg) ->
return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi"))
for i in msg.match
issue = i.toUpperCase()
now = new Date().getTime()
if cache.length > 0
cache.shift() until cache.length is 0 or cache[0].expires >= now
if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0
cache.push({issue: issue, expires: now + 120000})
robot.http(jiraUrl + "/rest/api/2/issue/" + issue)
.auth(auth)
.get() (err, res, body) ->
try
json = JSON.parse(body)
key = json.key
message = "[" + key + "] " + json.fields.summary
message += '\nStatus: '+json.fields.status.name
if (json.fields.assignee and json.fields.assignee.displayName)
message += ', assigned to ' + json.fields.assignee.displayName
else
message += ', unassigned'
message += ", rep. by "+json.fields.reporter.displayName
if json.fields.fixVersions and json.fields.fixVersions.length > 0
message += ', fixVersion: '+json.fields.fixVersions[0].name
else
message += ', fixVersion: NONE'
msg.send message
urlRegex = new RegExp(jiraUrl + "[^\\s]*" + key)
if not msg.message.text.match(urlRegex)
msg.send jiraUrl + "/browse/" + key
catch error
try
msg.send "[*ERROR*] " + json.errorMessages[0]
catch reallyError
msg.send "[*ERROR*] " + reallyError
| 154057 | # Description:
# Looks up jira issues when they're mentioned in chat
#
# Will ignore users set in HUBOT_JIRA_IGNORE_USERS (by default, JIRA and GitHub).
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_URL (format: "https://jira-domain.com:9090")
# HUBOT_JIRA_IGNORECASE (optional; default is "true")
# HUBOT_JIRA_USERNAME (optional)
# HUBOT_JIRA_PASSWORD (optional)
# HUBOT_JIRA_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
#
# Commands:
#
# Author:
# stuartf
module.exports = (robot) ->
cache = []
# In case someone upgrades form the previous version, we'll default to the
# previous behavior.
jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}"
jiraUsername = process.env.HUBOT_JIRA_USERNAME
jiraPassword = <PASSWORD>
if jiraUsername != undefined && jiraUsername.length > 0
auth = "#{jiraUsername}:#{jiraPassword}"
jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS
if jiraIgnoreUsers == undefined
jiraIgnoreUsers = "jira|github"
robot.http(jiraUrl + "/rest/api/2/project")
.auth(auth)
.get() (err, res, body) ->
json = JSON.parse(body)
jiraPrefixes = ( entry.key for entry in json )
reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y
jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g"
ic = process.env.HUBOT_JIRA_IGNORECASE
if ic == undefined || ic == "true"
jiraPattern += "i"
robot.hear eval(jiraPattern), (msg) ->
return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi"))
for i in msg.match
issue = i.toUpperCase()
now = new Date().getTime()
if cache.length > 0
cache.shift() until cache.length is 0 or cache[0].expires >= now
if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0
cache.push({issue: issue, expires: now + 120000})
robot.http(jiraUrl + "/rest/api/2/issue/" + issue)
.auth(auth)
.get() (err, res, body) ->
try
json = JSON.parse(body)
key = json.key
message = "[" + key + "] " + json.fields.summary
message += '\nStatus: '+json.fields.status.name
if (json.fields.assignee and json.fields.assignee.displayName)
message += ', assigned to ' + json.fields.assignee.displayName
else
message += ', unassigned'
message += ", rep. by "+json.fields.reporter.displayName
if json.fields.fixVersions and json.fields.fixVersions.length > 0
message += ', fixVersion: '+json.fields.fixVersions[0].name
else
message += ', fixVersion: NONE'
msg.send message
urlRegex = new RegExp(jiraUrl + "[^\\s]*" + key)
if not msg.message.text.match(urlRegex)
msg.send jiraUrl + "/browse/" + key
catch error
try
msg.send "[*ERROR*] " + json.errorMessages[0]
catch reallyError
msg.send "[*ERROR*] " + reallyError
| true | # Description:
# Looks up jira issues when they're mentioned in chat
#
# Will ignore users set in HUBOT_JIRA_IGNORE_USERS (by default, JIRA and GitHub).
#
# Dependencies:
# None
#
# Configuration:
# HUBOT_JIRA_URL (format: "https://jira-domain.com:9090")
# HUBOT_JIRA_IGNORECASE (optional; default is "true")
# HUBOT_JIRA_USERNAME (optional)
# HUBOT_JIRA_PASSWORD (optional)
# HUBOT_JIRA_IGNORE_USERS (optional, format: "user1|user2", default is "jira|github")
#
# Commands:
#
# Author:
# stuartf
module.exports = (robot) ->
cache = []
# In case someone upgrades form the previous version, we'll default to the
# previous behavior.
jiraUrl = process.env.HUBOT_JIRA_URL || "https://#{process.env.HUBOT_JIRA_DOMAIN}"
jiraUsername = process.env.HUBOT_JIRA_USERNAME
jiraPassword = PI:PASSWORD:<PASSWORD>END_PI
if jiraUsername != undefined && jiraUsername.length > 0
auth = "#{jiraUsername}:#{jiraPassword}"
jiraIgnoreUsers = process.env.HUBOT_JIRA_ISSUES_IGNORE_USERS
if jiraIgnoreUsers == undefined
jiraIgnoreUsers = "jira|github"
robot.http(jiraUrl + "/rest/api/2/project")
.auth(auth)
.get() (err, res, body) ->
json = JSON.parse(body)
jiraPrefixes = ( entry.key for entry in json )
reducedPrefixes = jiraPrefixes.reduce (x,y) -> x + "-|" + y
jiraPattern = "/\\b(" + reducedPrefixes + "-)(\\d+)\\b/g"
ic = process.env.HUBOT_JIRA_IGNORECASE
if ic == undefined || ic == "true"
jiraPattern += "i"
robot.hear eval(jiraPattern), (msg) ->
return if msg.message.user.name.match(new RegExp(jiraIgnoreUsers, "gi"))
for i in msg.match
issue = i.toUpperCase()
now = new Date().getTime()
if cache.length > 0
cache.shift() until cache.length is 0 or cache[0].expires >= now
if cache.length == 0 or (item for item in cache when item.issue is issue).length == 0
cache.push({issue: issue, expires: now + 120000})
robot.http(jiraUrl + "/rest/api/2/issue/" + issue)
.auth(auth)
.get() (err, res, body) ->
try
json = JSON.parse(body)
key = json.key
message = "[" + key + "] " + json.fields.summary
message += '\nStatus: '+json.fields.status.name
if (json.fields.assignee and json.fields.assignee.displayName)
message += ', assigned to ' + json.fields.assignee.displayName
else
message += ', unassigned'
message += ", rep. by "+json.fields.reporter.displayName
if json.fields.fixVersions and json.fields.fixVersions.length > 0
message += ', fixVersion: '+json.fields.fixVersions[0].name
else
message += ', fixVersion: NONE'
msg.send message
urlRegex = new RegExp(jiraUrl + "[^\\s]*" + key)
if not msg.message.text.match(urlRegex)
msg.send jiraUrl + "/browse/" + key
catch error
try
msg.send "[*ERROR*] " + json.errorMessages[0]
catch reallyError
msg.send "[*ERROR*] " + reallyError
|
[
{
"context": " autoUpdatedAt: false\n\n mailgun:\n user: 'postmaster@sandbox9ed13e55b9bb4706ad96ab32dafb424b.mailgun.org'\n password: '029c4266ce20c2724188c094a111f123'",
"end": 402,
"score": 0.9997643828392029,
"start": 340,
"tag": "EMAIL",
"value": "postmaster@sandbox9ed13e55b9... | config/env/development.coffee | webzepter/cleveroad_test_task | 2 | mongoAdapter = require 'sails-mongo'
module.exports =
db:
adapters:
mongo: mongoAdapter
connections:
default:
adapter: 'mongo'
url: 'mongodb://localhost:27017/node-tt'
defaults:
migrate: 'alter'
autoPK: true
autoCreatedAt: false
autoUpdatedAt: false
mailgun:
user: 'postmaster@sandbox9ed13e55b9bb4706ad96ab32dafb424b.mailgun.org'
password: '029c4266ce20c2724188c094a111f123'
| 81514 | mongoAdapter = require 'sails-mongo'
module.exports =
db:
adapters:
mongo: mongoAdapter
connections:
default:
adapter: 'mongo'
url: 'mongodb://localhost:27017/node-tt'
defaults:
migrate: 'alter'
autoPK: true
autoCreatedAt: false
autoUpdatedAt: false
mailgun:
user: '<EMAIL>'
password: '<PASSWORD>'
| true | mongoAdapter = require 'sails-mongo'
module.exports =
db:
adapters:
mongo: mongoAdapter
connections:
default:
adapter: 'mongo'
url: 'mongodb://localhost:27017/node-tt'
defaults:
migrate: 'alter'
autoPK: true
autoCreatedAt: false
autoUpdatedAt: false
mailgun:
user: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
|
[
{
"context": "\n view = null\n\n successForm = {\n firstName: 'A'\n lastName: 'B'\n email: 'C@D.com'\n phone",
"end": 174,
"score": 0.9997541308403015,
"start": 173,
"tag": "NAME",
"value": "A"
},
{
"context": "successForm = {\n firstName: 'A'\n lastName: 'B'\n ... | test/app/views/teachers/RequestQuoteView.spec.coffee | toivomattila/codecombat | 5 | RequestQuoteView = require 'views/teachers/RequestQuoteView'
forms = require 'core/forms'
describe 'RequestQuoteView', ->
view = null
successForm = {
firstName: 'A'
lastName: 'B'
email: 'C@D.com'
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
numStudentsTotal: '10,000+'
purchaserRole: 'Approve Funds'
educationLevel: ['Middle']
}
isSubmitRequest = (r) -> _.string.startsWith(r.url, '/db/trial.request') and r.method is 'POST'
describe 'when an anonymous user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(true)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'First'
lastName: 'Last'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows request received', ->
expect(view.$('#request-form').hasClass('hide')).toBe(true)
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
describe 'does NOT have an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: '[]'
})
_.defer done # Let SuperModel finish
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('#request-form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'on successful form submit', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id: 'a'}, successForm))
})
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new trial request', ->
expect(@submitRequest).toBeTruthy()
expect(@submitRequest.method).toBe('POST')
attrs = JSON.parse(@submitRequest.params)
expect(attrs.properties?.siteOrigin).toBe('demo request')
it 'sets the user\'s role to the one they chose', ->
request = _.last(jasmine.Ajax.requests.filter((r) -> _.string.startsWith(r.url, '/db/user')))
expect(request).toBeTruthy()
expect(request.method).toBe('PUT')
expect(JSON.parse(request.params).role).toBe('teacher')
it 'shows a signup form', ->
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
expect(view.$('#request-form').hasClass('hide')).toBe(true)
describe 'signup form', ->
beforeEach ->
return if window.features.chinaUx
application.facebookHandler.fakeAPI()
application.gplusHandler.fakeAPI()
it 'fills the username field with the given first and last names', ->
expect(view.$('input[name="name"]').val()).toBe('A B')
it 'includes a facebook button which will sign them in immediately', ->
return pending() if window.features.chinUx
view.$('#facebook-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?facebookID=abcd&facebookAccessToken=1234')
it 'includes a gplus button which will sign them in immediately', ->
return pending() if window.features.chinaUx
view.$('#gplus-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?gplusID=abcd&gplusAccessToken=1234')
it 'can sign them up with username and password', ->
form = view.$('#signup-form')
forms.objectToForm(form, {
password1: 'asdf'
password2: 'asdf'
name: 'some name'
})
form.submit()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user/1234')
describe 'tries to submit a request with an existing user\'s email', ->
beforeEach ->
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 409
responseText: '{}'
})
it 'shows an error that the email already exists', ->
expect(view.$('#email-form-group').hasClass('has-error')).toBe(true)
expect(view.$('#email-form-group .error-help-block').length).toBe(1)
describe 'submits the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submits the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(true)
describe 'submits form with district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
describe 'when a signed in user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(false)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'First'
lastName: 'Last'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows form with data from the most recent request', ->
expect(view.$('input[name="firstName"]').val()).toBe('First')
describe 'has role "student"', ->
beforeEach (done) ->
me.clear()
me.set('role', 'student')
me.set('name', 'Some User')
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({ status: 200, responseText: '[]'})
_.defer done # Let SuperModel finish
it 'shows a conversion warning', ->
expect(view.$('#conversion-warning').length).toBe(1)
it 'requires confirmation to submit the form', ->
form = view.$('#request-form')
forms.objectToForm(form, successForm)
spyOn(view, 'openModalView')
form.submit()
expect(view.openModalView).toHaveBeenCalled()
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeFalsy()
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeTruthy()
| 122013 | RequestQuoteView = require 'views/teachers/RequestQuoteView'
forms = require 'core/forms'
describe 'RequestQuoteView', ->
view = null
successForm = {
firstName: '<NAME>'
lastName: '<NAME>'
email: '<EMAIL>'
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
numStudentsTotal: '10,000+'
purchaserRole: 'Approve Funds'
educationLevel: ['Middle']
}
isSubmitRequest = (r) -> _.string.startsWith(r.url, '/db/trial.request') and r.method is 'POST'
describe 'when an anonymous user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(true)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: '<NAME>'
lastName: '<NAME>'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows request received', ->
expect(view.$('#request-form').hasClass('hide')).toBe(true)
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
describe 'does NOT have an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: '[]'
})
_.defer done # Let SuperModel finish
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('#request-form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'on successful form submit', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id: 'a'}, successForm))
})
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new trial request', ->
expect(@submitRequest).toBeTruthy()
expect(@submitRequest.method).toBe('POST')
attrs = JSON.parse(@submitRequest.params)
expect(attrs.properties?.siteOrigin).toBe('demo request')
it 'sets the user\'s role to the one they chose', ->
request = _.last(jasmine.Ajax.requests.filter((r) -> _.string.startsWith(r.url, '/db/user')))
expect(request).toBeTruthy()
expect(request.method).toBe('PUT')
expect(JSON.parse(request.params).role).toBe('teacher')
it 'shows a signup form', ->
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
expect(view.$('#request-form').hasClass('hide')).toBe(true)
describe 'signup form', ->
beforeEach ->
return if window.features.chinaUx
application.facebookHandler.fakeAPI()
application.gplusHandler.fakeAPI()
it 'fills the username field with the given first and last names', ->
expect(view.$('input[name="name"]').val()).toBe('A B')
it 'includes a facebook button which will sign them in immediately', ->
return pending() if window.features.chinUx
view.$('#facebook-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?facebookID=abcd&facebookAccessToken=<PASSWORD>')
it 'includes a gplus button which will sign them in immediately', ->
return pending() if window.features.chinaUx
view.$('#gplus-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?gplusID=abcd&gplusAccessToken=<PASSWORD>')
it 'can sign them up with username and password', ->
form = view.$('#signup-form')
forms.objectToForm(form, {
password1: '<PASSWORD>'
password2: '<PASSWORD>'
name: 'some name'
})
form.submit()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user/1234')
describe 'tries to submit a request with an existing user\'s email', ->
beforeEach ->
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 409
responseText: '{}'
})
it 'shows an error that the email already exists', ->
expect(view.$('#email-form-group').hasClass('has-error')).toBe(true)
expect(view.$('#email-form-group .error-help-block').length).toBe(1)
describe 'submits the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submits the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(true)
describe 'submits form with district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
describe 'when a signed in user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(false)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: '<NAME>'
lastName: '<NAME>'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows form with data from the most recent request', ->
expect(view.$('input[name="firstName"]').val()).toBe('First')
describe 'has role "student"', ->
beforeEach (done) ->
me.clear()
me.set('role', 'student')
me.set('name', 'Some User')
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({ status: 200, responseText: '[]'})
_.defer done # Let SuperModel finish
it 'shows a conversion warning', ->
expect(view.$('#conversion-warning').length).toBe(1)
it 'requires confirmation to submit the form', ->
form = view.$('#request-form')
forms.objectToForm(form, successForm)
spyOn(view, 'openModalView')
form.submit()
expect(view.openModalView).toHaveBeenCalled()
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeFalsy()
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeTruthy()
| true | RequestQuoteView = require 'views/teachers/RequestQuoteView'
forms = require 'core/forms'
describe 'RequestQuoteView', ->
view = null
successForm = {
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
phoneNumber: '555-555-5555'
role: 'Teacher'
organization: 'School'
district: 'District'
city: 'Springfield'
state: 'AA'
country: 'asdf'
numStudents: '1-10'
numStudentsTotal: '10,000+'
purchaserRole: 'Approve Funds'
educationLevel: ['Middle']
}
isSubmitRequest = (r) -> _.string.startsWith(r.url, '/db/trial.request') and r.method is 'POST'
describe 'when an anonymous user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(true)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows request received', ->
expect(view.$('#request-form').hasClass('hide')).toBe(true)
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
describe 'does NOT have an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: '[]'
})
_.defer done # Let SuperModel finish
describe 'when the form is unchanged', ->
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
describe 'when the form has changed but is not submitted', ->
beforeEach ->
view.$el.find('#request-form').trigger('change')
it 'prevents navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeTruthy()
describe 'on successful form submit', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 201
responseText: JSON.stringify(_.extend({_id: 'a'}, successForm))
})
it 'does not prevent navigating away', ->
expect(_.result(view, 'onLeaveMessage')).toBeFalsy()
it 'creates a new trial request', ->
expect(@submitRequest).toBeTruthy()
expect(@submitRequest.method).toBe('POST')
attrs = JSON.parse(@submitRequest.params)
expect(attrs.properties?.siteOrigin).toBe('demo request')
it 'sets the user\'s role to the one they chose', ->
request = _.last(jasmine.Ajax.requests.filter((r) -> _.string.startsWith(r.url, '/db/user')))
expect(request).toBeTruthy()
expect(request.method).toBe('PUT')
expect(JSON.parse(request.params).role).toBe('teacher')
it 'shows a signup form', ->
expect(view.$('#form-submit-success').hasClass('hide')).toBe(false)
expect(view.$('#request-form').hasClass('hide')).toBe(true)
describe 'signup form', ->
beforeEach ->
return if window.features.chinaUx
application.facebookHandler.fakeAPI()
application.gplusHandler.fakeAPI()
it 'fills the username field with the given first and last names', ->
expect(view.$('input[name="name"]').val()).toBe('A B')
it 'includes a facebook button which will sign them in immediately', ->
return pending() if window.features.chinUx
view.$('#facebook-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?facebookID=abcd&facebookAccessToken=PI:PASSWORD:<PASSWORD>END_PI')
it 'includes a gplus button which will sign them in immediately', ->
return pending() if window.features.chinaUx
view.$('#gplus-signup-btn').click()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user?gplusID=abcd&gplusAccessToken=PI:PASSWORD:<PASSWORD>END_PI')
it 'can sign them up with username and password', ->
form = view.$('#signup-form')
forms.objectToForm(form, {
password1: 'PI:PASSWORD:<PASSWORD>END_PI'
password2: 'PI:PASSWORD:<PASSWORD>END_PI'
name: 'some name'
})
form.submit()
request = jasmine.Ajax.requests.mostRecent()
expect(request.method).toBe('PUT')
expect(request.url).toBe('/db/user/1234')
describe 'tries to submit a request with an existing user\'s email', ->
beforeEach ->
forms.objectToForm(view.$el, successForm)
view.$('#request-form').submit()
@submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
@submitRequest.respondWith({
status: 409
responseText: '{}'
})
it 'shows an error that the email already exists', ->
expect(view.$('#email-form-group').hasClass('has-error')).toBe(true)
expect(view.$('#email-form-group .error-help-block').length).toBe(1)
describe 'submits the form without school', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include school setting', ->
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.organization).toBeUndefined()
expect(attrs.properties?.district).toEqual('District')
describe 'submits the form without district', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['district'])
forms.objectToForm(form, formData)
form.submit()
it 'displays a validation error on district and not school', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(true)
describe 'submits form with district set to n/a', ->
beforeEach ->
view.$el.find('#request-form').trigger('change') # to confirm navigating away isn't prevented
form = view.$('#request-form')
formData = _.omit(successForm, ['organization'])
formData.district = 'N/A'
forms.objectToForm(form, formData)
form.submit()
it 'submits a trial request, which does not include district setting', ->
expect(view.$('#organization-control').closest('.form-group').hasClass('has-error')).toEqual(false)
expect(view.$('#district-control').closest('.form-group').hasClass('has-error')).toEqual(false)
request = jasmine.Ajax.requests.mostRecent()
expect(request.url).toBe('/db/trial.request')
expect(request.method).toBe('POST')
attrs = JSON.parse(request.params)
expect(attrs.properties?.district).toBeUndefined()
describe 'when a signed in user', ->
beforeEach (done) ->
me.clear()
me.set('_id', '1234')
me._revertAttributes = {}
spyOn(me, 'isAnonymous').and.returnValue(false)
view = new RequestQuoteView()
view.render()
jasmine.demoEl(view.$el)
_.defer done # Let SuperModel finish
describe 'has an existing trial request', ->
beforeEach (done) ->
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({
status: 200
responseText: JSON.stringify([{
_id: '1'
properties: {
firstName: 'PI:NAME:<NAME>END_PI'
lastName: 'PI:NAME:<NAME>END_PI'
}
}])
})
view.supermodel.once('loaded-all', done)
it 'shows form with data from the most recent request', ->
expect(view.$('input[name="firstName"]').val()).toBe('First')
describe 'has role "student"', ->
beforeEach (done) ->
me.clear()
me.set('role', 'student')
me.set('name', 'Some User')
request = jasmine.Ajax.requests.mostRecent()
request.respondWith({ status: 200, responseText: '[]'})
_.defer done # Let SuperModel finish
it 'shows a conversion warning', ->
expect(view.$('#conversion-warning').length).toBe(1)
it 'requires confirmation to submit the form', ->
form = view.$('#request-form')
forms.objectToForm(form, successForm)
spyOn(view, 'openModalView')
form.submit()
expect(view.openModalView).toHaveBeenCalled()
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeFalsy()
confirmModal = view.openModalView.calls.argsFor(0)[0]
confirmModal.trigger 'confirm'
submitRequest = _.last(jasmine.Ajax.requests.filter(isSubmitRequest))
expect(submitRequest).toBeTruthy()
|
[
{
"context": "#\n# Copyright (c) 2020 Alexander Sporn. All rights reserved.\n#\n\nconfig = require './conf",
"end": 38,
"score": 0.9998772144317627,
"start": 23,
"tag": "NAME",
"value": "Alexander Sporn"
}
] | index.coffee | alexsporn/enocean-mqtt | 0 | #
# Copyright (c) 2020 Alexander Sporn. All rights reserved.
#
config = require './config.json'
mqtt = require 'mqtt'
Enocean = require './Enocean'
enocean = new Enocean(port: config.port)
client = mqtt.connect(config.mqtt, username: config.mqtt_username, password: config.mqtt_password, keepalive: 3600)
enocean.on 'pressed', (sender, button) =>
console.log "enocean/#{sender}" + " - " + JSON.stringify {type: button}
client.publish "enocean/#{sender}", JSON.stringify {type: button}
client.on 'connect', (packet) ->
if packet.returnCode is 0
console.log "Connected to #{config.mqtt}"
else
console.log "Connack error #{packet.returnCode}"
process.exit 1
client.on 'reconnect', ->
console.log "Reconnecting"
client.on 'close', ->
console.log "Connection closed"
client.on 'error', (e) ->
console.log "Error #{e}"
process.exit 1 | 126399 | #
# Copyright (c) 2020 <NAME>. All rights reserved.
#
config = require './config.json'
mqtt = require 'mqtt'
Enocean = require './Enocean'
enocean = new Enocean(port: config.port)
client = mqtt.connect(config.mqtt, username: config.mqtt_username, password: config.mqtt_password, keepalive: 3600)
enocean.on 'pressed', (sender, button) =>
console.log "enocean/#{sender}" + " - " + JSON.stringify {type: button}
client.publish "enocean/#{sender}", JSON.stringify {type: button}
client.on 'connect', (packet) ->
if packet.returnCode is 0
console.log "Connected to #{config.mqtt}"
else
console.log "Connack error #{packet.returnCode}"
process.exit 1
client.on 'reconnect', ->
console.log "Reconnecting"
client.on 'close', ->
console.log "Connection closed"
client.on 'error', (e) ->
console.log "Error #{e}"
process.exit 1 | true | #
# Copyright (c) 2020 PI:NAME:<NAME>END_PI. All rights reserved.
#
config = require './config.json'
mqtt = require 'mqtt'
Enocean = require './Enocean'
enocean = new Enocean(port: config.port)
client = mqtt.connect(config.mqtt, username: config.mqtt_username, password: config.mqtt_password, keepalive: 3600)
enocean.on 'pressed', (sender, button) =>
console.log "enocean/#{sender}" + " - " + JSON.stringify {type: button}
client.publish "enocean/#{sender}", JSON.stringify {type: button}
client.on 'connect', (packet) ->
if packet.returnCode is 0
console.log "Connected to #{config.mqtt}"
else
console.log "Connack error #{packet.returnCode}"
process.exit 1
client.on 'reconnect', ->
console.log "Reconnecting"
client.on 'close', ->
console.log "Connection closed"
client.on 'error', (e) ->
console.log "Error #{e}"
process.exit 1 |
[
{
"context": "Add data\n rows = [\n [5,'Bob',new Date()], # row by array\n [6, ",
"end": 2785,
"score": 0.9998759031295776,
"start": 2782,
"tag": "NAME",
"value": "Bob"
},
{
"context": ",new Date()], # row by array\n [6, 'Barbar... | server/excel/excel.coffee | kmcroft13/box-format-user-report | 0 | Excel = require( 'exceljs' )
# GREEN: FF92D050
# ORANGE: FFF8CBAD
# YELLOW: FFFFE699
# BLUE: FFB4C6E7
Meteor.methods(
createReport: (customerName) ->
check(customerName, Match.Any)
csvWb = new Excel.Workbook()
atlasReportData = new Array()
csvWb.csv.readFile("../../../../../server/excel/uploadedReports/workbook1.csv")
.then( (worksheet) ->
# use workbook or worksheet
worksheet.eachRow( (row, rowNumber) ->
csvRowValues = []
csvRowValues.push(row.values[1])
csvRowValues.push(row.values[3])
csvRowValues.push(row.values[5])
atlasReportData.push(csvRowValues)
)
# create workbook by api
workbook = new Excel.Workbook()
workbook.creator = ''
workbook.lastModifiedBy = ''
workbook.created = new Date()
workbook.modified = new Date()
# create a sheet
ws = workbook.addWorksheet("Existing Users")
#set columns
#access an individual columns by key, letter and 1-based column number
ws.columns = [
{ header: 'Email Domain', key: 'domain', width: 30 },
{ header: 'User Email', key: 'email', width: 30 },
{ header: 'User ID', key: 'uid', width: 15 },
{ header: 'Name', key: 'name', width: 30 },
{ header: 'Account Type', key: 'acctType', width: 25 },
{ header: 'Enterprise ID', key: 'eid', width: 18 },
{ header: 'Registration Date', key: 'regDate', width: 20 },
{ header: 'Last Activity Date', key: 'lastAct', width: 20 },
{ header: 'Disabled by Box Date', key: 'disabledDate', width: 25 },
{ header: 'Days Active', key: 'daysActive', width: 18 },
{ header: 'Space Used (MB)', key: 'space', width: 20 },
{ header: 'Migration Status', key: 'status', width: 30 }
]
# style header row
headerRow = ws.getRow(1)
headerRow.eachCell( (cell, colNumber) ->
cell.font = {
size: 14,
italic: true,
bold: true
}
cell.alignment = { vertical: 'middle', horizontal: 'center' }
cell.border = {
bottom: {style:'medium'}
}
cell.fill = {
type: 'pattern',
pattern:'solid',
fgColor:{argb:'FFD9D9D9'}
}
)
ws.addRows(atlasReportData)
###
#Add data
rows = [
[5,'Bob',new Date()], # row by array
[6, 'Barbara', new Date()]
];
###
# create xlsx file
workbook.xlsx.writeFile("../../../../../server/excel/generatedReports/" + customerName + " User Report.xlsx").then( ->
console.log(customerName + " User Report.xlsx has been written to file")
)
)
)
| 142461 | Excel = require( 'exceljs' )
# GREEN: FF92D050
# ORANGE: FFF8CBAD
# YELLOW: FFFFE699
# BLUE: FFB4C6E7
Meteor.methods(
createReport: (customerName) ->
check(customerName, Match.Any)
csvWb = new Excel.Workbook()
atlasReportData = new Array()
csvWb.csv.readFile("../../../../../server/excel/uploadedReports/workbook1.csv")
.then( (worksheet) ->
# use workbook or worksheet
worksheet.eachRow( (row, rowNumber) ->
csvRowValues = []
csvRowValues.push(row.values[1])
csvRowValues.push(row.values[3])
csvRowValues.push(row.values[5])
atlasReportData.push(csvRowValues)
)
# create workbook by api
workbook = new Excel.Workbook()
workbook.creator = ''
workbook.lastModifiedBy = ''
workbook.created = new Date()
workbook.modified = new Date()
# create a sheet
ws = workbook.addWorksheet("Existing Users")
#set columns
#access an individual columns by key, letter and 1-based column number
ws.columns = [
{ header: 'Email Domain', key: 'domain', width: 30 },
{ header: 'User Email', key: 'email', width: 30 },
{ header: 'User ID', key: 'uid', width: 15 },
{ header: 'Name', key: 'name', width: 30 },
{ header: 'Account Type', key: 'acctType', width: 25 },
{ header: 'Enterprise ID', key: 'eid', width: 18 },
{ header: 'Registration Date', key: 'regDate', width: 20 },
{ header: 'Last Activity Date', key: 'lastAct', width: 20 },
{ header: 'Disabled by Box Date', key: 'disabledDate', width: 25 },
{ header: 'Days Active', key: 'daysActive', width: 18 },
{ header: 'Space Used (MB)', key: 'space', width: 20 },
{ header: 'Migration Status', key: 'status', width: 30 }
]
# style header row
headerRow = ws.getRow(1)
headerRow.eachCell( (cell, colNumber) ->
cell.font = {
size: 14,
italic: true,
bold: true
}
cell.alignment = { vertical: 'middle', horizontal: 'center' }
cell.border = {
bottom: {style:'medium'}
}
cell.fill = {
type: 'pattern',
pattern:'solid',
fgColor:{argb:'FFD9D9D9'}
}
)
ws.addRows(atlasReportData)
###
#Add data
rows = [
[5,'<NAME>',new Date()], # row by array
[6, '<NAME>', new Date()]
];
###
# create xlsx file
workbook.xlsx.writeFile("../../../../../server/excel/generatedReports/" + customerName + " User Report.xlsx").then( ->
console.log(customerName + " User Report.xlsx has been written to file")
)
)
)
| true | Excel = require( 'exceljs' )
# GREEN: FF92D050
# ORANGE: FFF8CBAD
# YELLOW: FFFFE699
# BLUE: FFB4C6E7
Meteor.methods(
createReport: (customerName) ->
check(customerName, Match.Any)
csvWb = new Excel.Workbook()
atlasReportData = new Array()
csvWb.csv.readFile("../../../../../server/excel/uploadedReports/workbook1.csv")
.then( (worksheet) ->
# use workbook or worksheet
worksheet.eachRow( (row, rowNumber) ->
csvRowValues = []
csvRowValues.push(row.values[1])
csvRowValues.push(row.values[3])
csvRowValues.push(row.values[5])
atlasReportData.push(csvRowValues)
)
# create workbook by api
workbook = new Excel.Workbook()
workbook.creator = ''
workbook.lastModifiedBy = ''
workbook.created = new Date()
workbook.modified = new Date()
# create a sheet
ws = workbook.addWorksheet("Existing Users")
#set columns
#access an individual columns by key, letter and 1-based column number
ws.columns = [
{ header: 'Email Domain', key: 'domain', width: 30 },
{ header: 'User Email', key: 'email', width: 30 },
{ header: 'User ID', key: 'uid', width: 15 },
{ header: 'Name', key: 'name', width: 30 },
{ header: 'Account Type', key: 'acctType', width: 25 },
{ header: 'Enterprise ID', key: 'eid', width: 18 },
{ header: 'Registration Date', key: 'regDate', width: 20 },
{ header: 'Last Activity Date', key: 'lastAct', width: 20 },
{ header: 'Disabled by Box Date', key: 'disabledDate', width: 25 },
{ header: 'Days Active', key: 'daysActive', width: 18 },
{ header: 'Space Used (MB)', key: 'space', width: 20 },
{ header: 'Migration Status', key: 'status', width: 30 }
]
# style header row
headerRow = ws.getRow(1)
headerRow.eachCell( (cell, colNumber) ->
cell.font = {
size: 14,
italic: true,
bold: true
}
cell.alignment = { vertical: 'middle', horizontal: 'center' }
cell.border = {
bottom: {style:'medium'}
}
cell.fill = {
type: 'pattern',
pattern:'solid',
fgColor:{argb:'FFD9D9D9'}
}
)
ws.addRows(atlasReportData)
###
#Add data
rows = [
[5,'PI:NAME:<NAME>END_PI',new Date()], # row by array
[6, 'PI:NAME:<NAME>END_PI', new Date()]
];
###
# create xlsx file
workbook.xlsx.writeFile("../../../../../server/excel/generatedReports/" + customerName + " User Report.xlsx").then( ->
console.log(customerName + " User Report.xlsx has been written to file")
)
)
)
|
[
{
"context": "\"localhost\"\n port: port\n username: 'foo@biz.biz'\n password: 'bar'\n\n describe 'authentic",
"end": 2125,
"score": 0.999921977519989,
"start": 2114,
"tag": "EMAIL",
"value": "foo@biz.biz"
},
{
"context": " username: 'foo@biz.biz'\n ... | test/services/exchange-service-spec.coffee | octoblu/bourse | 0 | {afterEach, beforeEach, context, describe, it} = global
{expect} = require 'chai'
_ = require 'lodash'
fs = require 'fs'
path = require 'path'
shmock = require 'shmock'
enableDestroy = require 'server-destroy'
base64 = require '../helpers/base64'
Exchange = require '../../src/services/exchange-service'
slurpFile = (filename) => _.trim fs.readFileSync path.join(__dirname, filename), encoding: 'utf8'
CHALLENGE = slurpFile '../fixtures/challenge.b64'
NEGOTIATE = slurpFile '../fixtures/negotiate.b64'
CREATE_ITEM_RESPONSE = slurpFile '../fixtures/createItemResponse.xml'
CREATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/createItemErrorResponse.xml'
DELETE_ITEM_RESPONSE = slurpFile '../fixtures/deleteItemResponse.xml'
DELETE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/deleteItemErrorResponse.xml'
GET_CALENDAR_RANGE_ERROR_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeErrorResponse.xml'
GET_CALENDAR_RANGE_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeResponse.xml'
GET_CALENDAR_ITEM_ALTERNATE_RESPONSE = slurpFile '../fixtures/getItemCalendarAlternateResponse.xml'
FORWARD_ITEM_RESPONSE = slurpFile '../fixtures/forwardItemResponse.xml'
FORWARD_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/forwardItemErrorResponse.xml'
USER_SETTINGS_RESPONSE = slurpFile '../fixtures/userSettingsResponse.xml'
UPDATE_ITEM_RESPONSE = slurpFile '../fixtures/updateItemResponse.xml'
UPDATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/updateItemErrorResponse.xml'
NEGOTIATE_CUSTOM_HOSTNAME = slurpFile '../fixtures/negotiate-custom-hostname.b64'
describe 'Exchange', ->
beforeEach ->
@server = shmock()
enableDestroy @server
afterEach (done) ->
@server.destroy done
describe 'when the authHostname is inferred', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: 'foo@biz.biz'
password: 'bar'
describe 'authenticate', ->
describe 'when the server uses Basic Auth', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': 'Basic Realm=""'}
@server
.post '/EWS/Exchange.asmx'
.set 'Authorization', "Basic #{base64 'foo@biz.biz:bar'}"
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 401
@sut.authenticate (error, @authenticated) => done error
it 'should yield false', ->
expect(@authenticated).to.be.false
describe 'when there is a server error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 500
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is a user error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 429
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is an error during authorization', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 500, '', {'WWW-Authenticate': CHALLENGE}
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe '->getCalendarItemsInRange', ->
context 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut._getItemsByItemIds = ({itemIds}, callback) => callback null, itemIds
@sut.getCalendarItemsInRange {start, end}, (@error, @meetings) =>
done()
it 'should have 2 meetings', ->
expect(_.size(@meetings)).to.equal 2
describe 'when everything is not cool', ->
beforeEach (done) ->
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_ERROR_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut.getCalendarItemsInRange {start, end}, (@error) =>
done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getCalendarItemsInRange.isDone).to.be.true
it 'should yield an error', ->
expect(@error).to.exist
expect(@error.code).to.deep.equal 422, @error.message
expect(@error.message).to.deep.equal 'EndDate is earlier than StartDate'
describe 'whoami', ->
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 200, USER_SETTINGS_RESPONSE
@sut.whoami (error, @user) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield a user', ->
expect(@user).to.deep.equal {
name: 'Foo Hampton'
}
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 401
@sut.whoami (@error, @user) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield no use', ->
expect(@user).not.to.exist
it 'should yield an error with code 401', ->
expect(@error).to.exist
expect(@error.code).to.equal 401
describe 'createItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['blah@whatever.net', 'imdone@whocares.net', 'null']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '2016-09-09T01:00:00Z'
location: 'Pokémon Go Home'
extendedProperties:
something: 'happened'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_RESPONSE
@sut.createItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a createItem request to the exchange server', ->
expect(@createItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item returns an error', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['blah@whatever.net', 'imdone@whocares.net']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '1999-09-09T01:00:00Z'
location: 'Pokémon Go Home'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: EndDate is earlier than StartDate'
describe 'deleteItem', ->
describe 'when deleting an item is successful', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'deleteItemChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@deleteItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_RESPONSE
@sut.deleteItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should call deleteItem', ->
expect(@deleteItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'deleteItemId'
changeKey: 'deleteItemChangeKeyNew'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when deleting an item returns an error', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'malformed'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'getItem', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_ITEM_ALTERNATE_RESPONSE
@sut.getItemByItemId 'item-id', (error, @item) => done error
it 'should parse the item', ->
expect(@item.urls).to.include {url: 'https://aaron.has.clothing/meet/123456', hostname: 'aaron.has.clothing'}
describe 'updateItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'AChangeKey'
subject: 'Feed the Trolls'
attendees: ['no@sleep.net', 'til@brooklyn.net']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_RESPONSE
@sut.updateItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'wrong-wrong'
subject: 'Feed the Trolls'
attendees: ['no@sleep.net', 'til@brooklyn.net']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_ERROR_RESPONSE
@sut.updateItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'when the authHostname is given', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: 'foo@biz.biz'
password: 'bar'
authHostname: 'biz.bikes'
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE_CUSTOM_HOSTNAME
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 201
@sut.whoami done
it 'should make a negotiate request to the exchange server with the given authHostname', ->
expect(@negotiate.isDone).to.be.true
describe 'forwardItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
email: 'newguy@whatevs.co'
itemId: 'some-item-id'
changeKey: 'some-change-key'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@forwardItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_RESPONSE
@sut.forwardItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a forwardItem request to the exchange server', ->
expect(@forwardItem.isDone).to.be.true
it 'should return an empty object', ->
expect(@response).to.deep.equal {}
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'wrong-wrong'
email: 'i@broke.it'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_ERROR_RESPONSE
@sut.forwardItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
| 36956 | {afterEach, beforeEach, context, describe, it} = global
{expect} = require 'chai'
_ = require 'lodash'
fs = require 'fs'
path = require 'path'
shmock = require 'shmock'
enableDestroy = require 'server-destroy'
base64 = require '../helpers/base64'
Exchange = require '../../src/services/exchange-service'
slurpFile = (filename) => _.trim fs.readFileSync path.join(__dirname, filename), encoding: 'utf8'
CHALLENGE = slurpFile '../fixtures/challenge.b64'
NEGOTIATE = slurpFile '../fixtures/negotiate.b64'
CREATE_ITEM_RESPONSE = slurpFile '../fixtures/createItemResponse.xml'
CREATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/createItemErrorResponse.xml'
DELETE_ITEM_RESPONSE = slurpFile '../fixtures/deleteItemResponse.xml'
DELETE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/deleteItemErrorResponse.xml'
GET_CALENDAR_RANGE_ERROR_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeErrorResponse.xml'
GET_CALENDAR_RANGE_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeResponse.xml'
GET_CALENDAR_ITEM_ALTERNATE_RESPONSE = slurpFile '../fixtures/getItemCalendarAlternateResponse.xml'
FORWARD_ITEM_RESPONSE = slurpFile '../fixtures/forwardItemResponse.xml'
FORWARD_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/forwardItemErrorResponse.xml'
USER_SETTINGS_RESPONSE = slurpFile '../fixtures/userSettingsResponse.xml'
UPDATE_ITEM_RESPONSE = slurpFile '../fixtures/updateItemResponse.xml'
UPDATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/updateItemErrorResponse.xml'
NEGOTIATE_CUSTOM_HOSTNAME = slurpFile '../fixtures/negotiate-custom-hostname.b64'
describe 'Exchange', ->
beforeEach ->
@server = shmock()
enableDestroy @server
afterEach (done) ->
@server.destroy done
describe 'when the authHostname is inferred', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: '<EMAIL>'
password: '<PASSWORD>'
describe 'authenticate', ->
describe 'when the server uses Basic Auth', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': 'Basic Realm=""'}
@server
.post '/EWS/Exchange.asmx'
.set 'Authorization', "Basic #{base64 '<EMAIL>:bar'}"
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 401
@sut.authenticate (error, @authenticated) => done error
it 'should yield false', ->
expect(@authenticated).to.be.false
describe 'when there is a server error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 500
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is a user error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 429
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is an error during authorization', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 500, '', {'WWW-Authenticate': CHALLENGE}
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe '->getCalendarItemsInRange', ->
context 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut._getItemsByItemIds = ({itemIds}, callback) => callback null, itemIds
@sut.getCalendarItemsInRange {start, end}, (@error, @meetings) =>
done()
it 'should have 2 meetings', ->
expect(_.size(@meetings)).to.equal 2
describe 'when everything is not cool', ->
beforeEach (done) ->
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_ERROR_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut.getCalendarItemsInRange {start, end}, (@error) =>
done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getCalendarItemsInRange.isDone).to.be.true
it 'should yield an error', ->
expect(@error).to.exist
expect(@error.code).to.deep.equal 422, @error.message
expect(@error.message).to.deep.equal 'EndDate is earlier than StartDate'
describe 'whoami', ->
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 200, USER_SETTINGS_RESPONSE
@sut.whoami (error, @user) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield a user', ->
expect(@user).to.deep.equal {
name: '<NAME>'
}
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 401
@sut.whoami (@error, @user) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield no use', ->
expect(@user).not.to.exist
it 'should yield an error with code 401', ->
expect(@error).to.exist
expect(@error.code).to.equal 401
describe 'createItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['<EMAIL>', '<EMAIL>', 'null']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '2016-09-09T01:00:00Z'
location: 'Pokémon Go Home'
extendedProperties:
something: 'happened'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_RESPONSE
@sut.createItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a createItem request to the exchange server', ->
expect(@createItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item returns an error', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['<EMAIL>', '<EMAIL>']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '1999-09-09T01:00:00Z'
location: 'Pokémon Go Home'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: EndDate is earlier than StartDate'
describe 'deleteItem', ->
describe 'when deleting an item is successful', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'deleteItemChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@deleteItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_RESPONSE
@sut.deleteItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should call deleteItem', ->
expect(@deleteItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'deleteItemId'
changeKey: '<KEY>KeyNew'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when deleting an item returns an error', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'malformed'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'getItem', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_ITEM_ALTERNATE_RESPONSE
@sut.getItemByItemId 'item-id', (error, @item) => done error
it 'should parse the item', ->
expect(@item.urls).to.include {url: 'https://aaron.has.clothing/meet/123456', hostname: 'aaron.has.clothing'}
describe 'updateItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'AChangeKey'
subject: 'Feed the Trolls'
attendees: ['<EMAIL>', '<EMAIL>']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_RESPONSE
@sut.updateItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'wrong-<KEY>'
subject: 'Feed the Trolls'
attendees: ['<EMAIL>', '<EMAIL>']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_ERROR_RESPONSE
@sut.updateItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'when the authHostname is given', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: '<EMAIL>'
password: '<PASSWORD>'
authHostname: 'biz.bikes'
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE_CUSTOM_HOSTNAME
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 201
@sut.whoami done
it 'should make a negotiate request to the exchange server with the given authHostname', ->
expect(@negotiate.isDone).to.be.true
describe 'forwardItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
email: '<EMAIL>'
itemId: 'some-item-id'
changeKey: 'some-change-key'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@forwardItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_RESPONSE
@sut.forwardItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a forwardItem request to the exchange server', ->
expect(@forwardItem.isDone).to.be.true
it 'should return an empty object', ->
expect(@response).to.deep.equal {}
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: '<KEY>'
email: '<EMAIL>'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_ERROR_RESPONSE
@sut.forwardItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
| true | {afterEach, beforeEach, context, describe, it} = global
{expect} = require 'chai'
_ = require 'lodash'
fs = require 'fs'
path = require 'path'
shmock = require 'shmock'
enableDestroy = require 'server-destroy'
base64 = require '../helpers/base64'
Exchange = require '../../src/services/exchange-service'
slurpFile = (filename) => _.trim fs.readFileSync path.join(__dirname, filename), encoding: 'utf8'
CHALLENGE = slurpFile '../fixtures/challenge.b64'
NEGOTIATE = slurpFile '../fixtures/negotiate.b64'
CREATE_ITEM_RESPONSE = slurpFile '../fixtures/createItemResponse.xml'
CREATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/createItemErrorResponse.xml'
DELETE_ITEM_RESPONSE = slurpFile '../fixtures/deleteItemResponse.xml'
DELETE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/deleteItemErrorResponse.xml'
GET_CALENDAR_RANGE_ERROR_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeErrorResponse.xml'
GET_CALENDAR_RANGE_RESPONSE = slurpFile '../fixtures/getCalendarItemsInRangeResponse.xml'
GET_CALENDAR_ITEM_ALTERNATE_RESPONSE = slurpFile '../fixtures/getItemCalendarAlternateResponse.xml'
FORWARD_ITEM_RESPONSE = slurpFile '../fixtures/forwardItemResponse.xml'
FORWARD_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/forwardItemErrorResponse.xml'
USER_SETTINGS_RESPONSE = slurpFile '../fixtures/userSettingsResponse.xml'
UPDATE_ITEM_RESPONSE = slurpFile '../fixtures/updateItemResponse.xml'
UPDATE_ITEM_ERROR_RESPONSE = slurpFile '../fixtures/updateItemErrorResponse.xml'
NEGOTIATE_CUSTOM_HOSTNAME = slurpFile '../fixtures/negotiate-custom-hostname.b64'
describe 'Exchange', ->
beforeEach ->
@server = shmock()
enableDestroy @server
afterEach (done) ->
@server.destroy done
describe 'when the authHostname is inferred', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
describe 'authenticate', ->
describe 'when the server uses Basic Auth', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': 'Basic Realm=""'}
@server
.post '/EWS/Exchange.asmx'
.set 'Authorization', "Basic #{base64 'PI:EMAIL:<EMAIL>END_PI:bar'}"
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200
@sut.authenticate (error, @authenticated) => done error
it 'should yield true', ->
expect(@authenticated).to.be.true
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 401
@sut.authenticate (error, @authenticated) => done error
it 'should yield false', ->
expect(@authenticated).to.be.false
describe 'when there is a server error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 500
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is a user error', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 429
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe 'when there is an error during authorization', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 500, '', {'WWW-Authenticate': CHALLENGE}
@sut.authenticate (@error, @authenticated) => done()
it 'should yield an error', ->
expect(@error).to.exist
it 'should yield no authenticated', ->
expect(@authenticated).not.to.exist
describe '->getCalendarItemsInRange', ->
context 'when the credentials are valid', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut._getItemsByItemIds = ({itemIds}, callback) => callback null, itemIds
@sut.getCalendarItemsInRange {start, end}, (@error, @meetings) =>
done()
it 'should have 2 meetings', ->
expect(_.size(@meetings)).to.equal 2
describe 'when everything is not cool', ->
beforeEach (done) ->
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getCalendarItemsInRange = @server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_RANGE_ERROR_RESPONSE
start = '2016-12-28'
end = '1999-12-31'
@sut.getCalendarItemsInRange {start, end}, (@error) =>
done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getCalendarItemsInRange.isDone).to.be.true
it 'should yield an error', ->
expect(@error).to.exist
expect(@error.code).to.deep.equal 422, @error.message
expect(@error.message).to.deep.equal 'EndDate is earlier than StartDate'
describe 'whoami', ->
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 200, USER_SETTINGS_RESPONSE
@sut.whoami (error, @user) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield a user', ->
expect(@user).to.deep.equal {
name: 'PI:NAME:<NAME>END_PI'
}
describe 'when the credentials are invalid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 401
@sut.whoami (@error, @user) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a get user request to the exchange server', ->
expect(@getUser.isDone).to.be.true
it 'should yield no use', ->
expect(@user).not.to.exist
it 'should yield an error with code 401', ->
expect(@error).to.exist
expect(@error.code).to.equal 401
describe 'createItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI', 'null']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '2016-09-09T01:00:00Z'
location: 'Pokémon Go Home'
extendedProperties:
something: 'happened'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_RESPONSE
@sut.createItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a createItem request to the exchange server', ->
expect(@createItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item returns an error', ->
beforeEach (done) ->
options =
timeZone: 'Star Date Time'
sendTo: 'SendToWhatever'
subject: 'Feed the Trolls'
body: 'A great way to meet and flourish'
attendees: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
reminder: '2016-09-08T23:00:00-01:00'
start: '2016-09-09T00:29:00Z'
end: '1999-09-09T01:00:00Z'
location: 'Pokémon Go Home'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, CREATE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: EndDate is earlier than StartDate'
describe 'deleteItem', ->
describe 'when deleting an item is successful', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'deleteItemChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@deleteItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_RESPONSE
@sut.deleteItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should call deleteItem', ->
expect(@deleteItem.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'deleteItemId'
changeKey: 'PI:KEY:<KEY>END_PIKeyNew'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when deleting an item returns an error', ->
beforeEach (done) ->
options =
itemId: 'deleteItemId'
changeKey: 'malformed'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@createItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, DELETE_ITEM_ERROR_RESPONSE
@sut.createItem options, (@error, @response) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'getItem', ->
beforeEach (done) ->
@server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@server
.post '/EWS/Exchange.asmx'
.reply 200, GET_CALENDAR_ITEM_ALTERNATE_RESPONSE
@sut.getItemByItemId 'item-id', (error, @item) => done error
it 'should parse the item', ->
expect(@item.urls).to.include {url: 'https://aaron.has.clothing/meet/123456', hostname: 'aaron.has.clothing'}
describe 'updateItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'AChangeKey'
subject: 'Feed the Trolls'
attendees: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_RESPONSE
@sut.updateItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a calendar event', ->
expect(@response).to.deep.equal
itemId: 'AnId'
changeKey: 'AChangeKey'
recurrenceId: 'recurrence-id'
UID: 'the-uid'
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'wrong-PI:KEY:<KEY>END_PI'
subject: 'Feed the Trolls'
attendees: ['PI:EMAIL:<EMAIL>END_PI', 'PI:EMAIL:<EMAIL>END_PI']
start: '2016-09-10T00:29:00Z'
end: '2016-09-10T01:00:00Z'
location: 'Mexico?'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, UPDATE_ITEM_ERROR_RESPONSE
@sut.updateItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
describe 'when the authHostname is given', ->
beforeEach ->
{port} = @server.address()
@sut = new Exchange
protocol: 'http'
hostname: "localhost"
port: port
username: 'PI:EMAIL:<EMAIL>END_PI'
password: 'PI:PASSWORD:<PASSWORD>END_PI'
authHostname: 'biz.bikes'
describe 'when the credentials are valid', ->
beforeEach (done) ->
@negotiate = @server
.get '/autodiscover/autodiscover.svc'
.set 'Authorization', NEGOTIATE_CUSTOM_HOSTNAME
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@getUser = @server
.post '/autodiscover/autodiscover.svc'
.reply 201
@sut.whoami done
it 'should make a negotiate request to the exchange server with the given authHostname', ->
expect(@negotiate.isDone).to.be.true
describe 'forwardItem', ->
describe 'when creating an item is successful', ->
beforeEach (done) ->
options =
email: 'PI:EMAIL:<EMAIL>END_PI'
itemId: 'some-item-id'
changeKey: 'some-change-key'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@forwardItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_RESPONSE
@sut.forwardItem options, (error, @response) => done error
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should make a forwardItem request to the exchange server', ->
expect(@forwardItem.isDone).to.be.true
it 'should return an empty object', ->
expect(@response).to.deep.equal {}
describe 'when creating an item fails', ->
beforeEach (done) ->
options =
itemId: 'AnId'
changeKey: 'PI:KEY:<KEY>END_PI'
email: 'PI:EMAIL:<EMAIL>END_PI'
@negotiate = @server
.get '/EWS/Exchange.asmx'
.set 'Authorization', NEGOTIATE
.reply 401, '', {'WWW-Authenticate': CHALLENGE}
@updateItem = @server
.post '/EWS/Exchange.asmx'
.reply 200, FORWARD_ITEM_ERROR_RESPONSE
@sut.forwardItem options, (@error, @item) => done()
it 'should make a negotiate request to the exchange server', ->
expect(@negotiate.isDone).to.be.true
it 'should return a 422 error', ->
expect(@error).to.exist
expect(@error.code).to.equal 422
expect(@error.message).to.equal 'Unprocessable Entity: The change key is invalid.'
|
[
{
"context": "Quo Module\n\n@namespace Quo\n@class Element\n\n@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi\n###\n\"use strict\"\n\n\n",
"end": 84,
"score": 0.9998387098312378,
"start": 63,
"tag": "NAME",
"value": "Javier Jimenez Villar"
},
{
"context": "uo\n@class Elem... | source/quo.element.coffee | lguzzon/QuoJS | 558 | ###
ELEMENT Quo Module
@namespace Quo
@class Element
@author Javier Jimenez Villar <javi@tapquo.com> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value?
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
| 160270 | ###
ELEMENT Quo Module
@namespace Quo
@class Element
@author <NAME> <<EMAIL>> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value?
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
| true | ###
ELEMENT Quo Module
@namespace Quo
@class Element
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> || @soyjavi
###
"use strict"
do ($$ = Quo) ->
###
Get/Set attribute to a given instance element
@method attr
@param {string} Name of attribute
@param {string} [OPTIONAL] Value of attribute
###
$$.fn.attr = (name, value) ->
if @length > 0 and $$.toType(name) is "string"
if value?
@each -> @setAttribute name, value
else
@[0].getAttribute name
###
Remove attribute to a given instance element
@method removeAttr
@param {string} Name of attribute
###
$$.fn.removeAttr = (name) ->
if @length > 0 and $$.toType(name) is "string"
@each -> @removeAttribute name
###
Get/Set data attribute to a given instance element
@method data
@param {string} Name of data attribute
@param {string} [OPTIONAL] Value of data atribbute
###
$$.fn.data = (name, value) ->
@attr "data-#{name}", value
###
Remove data attribute to a given instance element
@method removeAttr
@param {string} Name of data attribute
###
$$.fn.removeData = (name) ->
@removeAttr "data-#{name}"
###
Remove data attribute to a given instance element
@method val
@param {string} Name of data attribute
###
$$.fn.val = (value) ->
if value?
@each -> @value = value.toString()
else
if @length > 0 then @[0].value else null
###
Shows a given instance element
@method show
###
$$.fn.show = ->
@style "display", "block"
###
Hides a given instance element
@method hide
###
$$.fn.hide = ->
@style "display", "none"
###
Trigger that event on an element
@method focus
###
$$.fn.focus = ->
do @[0].focus
###
Trigger that event on an element
@method blur
###
$$.fn.blur = ->
do @[0].blur
###
Get a offset of a given instance element
@method offset
###
$$.fn.offset = ->
if @length > 0
bounding = @[0].getBoundingClientRect()
offset =
left : bounding.left + window.pageXOffset
top : bounding.top + window.pageYOffset
width : bounding.width
height: bounding.height
offset
|
[
{
"context": "ut name=\"authenticity_token\" type=\"hidden\" value=\"r/4R6o85mAPcpp6nFjya/v9VjI/0314YxgVxkYM2vPk=\">--></div>\n\t\t\t\t\t<input name=\"file\" type=\"file\">\n ",
"end": 4113,
"score": 0.8348143696784973,
"start": 4068,
"tag": "KEY",
"value": "r/4R6o85mAPcpp6nFjya/v9VjI/0314Y... | app/assets/javascripts/swell_media/plugins/jquery.assetup.js.coffee | gkparishphilp/swell_media | 0 | #= require ./jquery.fileupload
#= require ./jquery.iframe-transport
assetup_counter = 0;
jQuery.assetdirect = (args) ->
args = {} if args == undefined
#window.console and console.log 'assetdirect', args
if args['progressBar']
$(args['progressBar']).removeClass('_'+per+'-per') for per in [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
$(args['progressBar']).removeClass('_complete')
$form = $('<form enctype="multipart/form-data" id="file_upload" method="post"><input name="file" type="file"></form>')
$form.fileupload
autoUpload: true
method: 'POST'
action: ''
add: (event, data) ->
$.ajax
dataType: 'json'
url: args['newUrl']
cache: false
success: (response) ->
#console.log(JSON.stringify(response))
data.url = response.action
data.formData = response.request
$form.data 'asset', response
$form.fileupload 'send', data
return
error: (response, status) ->
#window.console and console.log('there was an error')
return
return
progress: (e, data) ->
#Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10)
#window.console and console.log('progress', progress, e, data, args['progressBar'], args)
if args['progressOutput']
$(args['progressOutput']).html (if progress >= 10 and progress < 10 then ' ' else '') + progress + '%'
if args['progressBar']
increment = Math.floor(progress / 5) * 5
#window.console and console.log "increment", increment
$(args['progressBar']).addClass('_'+increment+'-per')
return
send: (e, data) ->
#window.console and console.log('send', e, data)
return
done: (e, data) ->
#window.console and console.log('done', e, data, data.result)
$result = $(data.result)
request =
dataType: 'json'
url: $form.data('asset').callback.url
method: 'GET'
data: $.extend($form.data('asset').callback.data,
key: $result.find('Key').text()
bucket: $result.find('Bucket').text())
success: (callback_response, textStatus, jqXHR) ->
#window.console and console.log('callback success', callback_response, textStatus, jqXHR)
if args['progressBar']
$(args['progressBar']).addClass('_complete')
if args['urlInput']
$(args['urlInput']).val( callback_response['url'] ).change()
if args['for']
$(args['for']).val( callback_response['url'] ).change()
if args['idInput']
$(args['idInput']).val( callback_response['id'] ).change()
if args['backgroundPreview']
$(args['backgroundPreview']).css('background-image', 'url(\'' + callback_response['url'] + '\')').addClass( '_fileupload_preview' )
if args['imgPreview']
$(args['imgPreview']).attr('src', callback_response['url']).addClass '_fileupload_preview'
if args['callback']
args['callback']( callback_response )
return
#window.console and console.log(request)
$.ajax request
return
fail: (e, data) ->
#window.console and console.log('fail', e, data, data.result)
return
success: (e, data) ->
#window.console and console.log('success', e, data, data.result)
return
$form.find('input').click()
return
jQuery.fn.assetup = (args) ->
args = {} if args == undefined
$(this).each ()->
$this = $(this)
$for = $($this.data('for'))
acceptFileTypes = args['accept-file-types'] || $this.data('accept-file-types') || /(\.|\/)(gif|jpe?g|png)$/i
maxFileSize = args['max-file-size'] || $this.data('max-file-size') || 5000000
asset = args['asset'] || $this.data('asset') || {}
params = args['params'] || $this.data('params') || {}
params.asset = asset
form_id = "new_asset_"+(assetup_counter++)
$('body').append("""
<form accept-charset="UTF-8" action="/asset_manager?response=url&#{$.param(params)}" class="new_asset" enctype="multipart/form-data" id="#{form_id}" method="post" style="display:none;">
<div style="display:none"><input name="utf8" type="hidden" value="✓"><!--<input name="authenticity_token" type="hidden" value="r/4R6o85mAPcpp6nFjya/v9VjI/0314YxgVxkYM2vPk=">--></div>
<input name="file" type="file">
<input name="commit" type="submit" value="Upload">
</form>
""")
$form = $('#'+form_id)
$upload = $form.find('[type=file]')
$form.fileupload(
maxFileSize: maxFileSize,
acceptFileTypes: acceptFileTypes,
progress: (e, data) ->
# Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10);
#window.console and console.log progress, e, data if window.console
done: (e, data) ->
#window.console and console.log data.result if window.console
$for.each ()->
if $(this).is('img')
$(this).attr('src',data.result)
else
$(this).val(data.result).change()
$form.remove()
)
$upload.change = (e)->
$form.submit()
$upload.click()
$(document).ready ->
$(document).on(
'click'
'[data-toggle=assetup]',
(e)->
e.preventDefault()
$(this).assetup()
)
$(document).on(
'click'
'.asset-direct',
(e)->
e.preventDefault()
e.stopPropagation()
#window.console && console.log 'data', $(this).data()
$.assetdirect( $.extend($(this).data()||{},{ newUrl: $(this).attr('href'), progressOutput: $('.progress_output',this), for: $(this).attr('for') }) )
) | 100605 | #= require ./jquery.fileupload
#= require ./jquery.iframe-transport
assetup_counter = 0;
jQuery.assetdirect = (args) ->
args = {} if args == undefined
#window.console and console.log 'assetdirect', args
if args['progressBar']
$(args['progressBar']).removeClass('_'+per+'-per') for per in [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
$(args['progressBar']).removeClass('_complete')
$form = $('<form enctype="multipart/form-data" id="file_upload" method="post"><input name="file" type="file"></form>')
$form.fileupload
autoUpload: true
method: 'POST'
action: ''
add: (event, data) ->
$.ajax
dataType: 'json'
url: args['newUrl']
cache: false
success: (response) ->
#console.log(JSON.stringify(response))
data.url = response.action
data.formData = response.request
$form.data 'asset', response
$form.fileupload 'send', data
return
error: (response, status) ->
#window.console and console.log('there was an error')
return
return
progress: (e, data) ->
#Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10)
#window.console and console.log('progress', progress, e, data, args['progressBar'], args)
if args['progressOutput']
$(args['progressOutput']).html (if progress >= 10 and progress < 10 then ' ' else '') + progress + '%'
if args['progressBar']
increment = Math.floor(progress / 5) * 5
#window.console and console.log "increment", increment
$(args['progressBar']).addClass('_'+increment+'-per')
return
send: (e, data) ->
#window.console and console.log('send', e, data)
return
done: (e, data) ->
#window.console and console.log('done', e, data, data.result)
$result = $(data.result)
request =
dataType: 'json'
url: $form.data('asset').callback.url
method: 'GET'
data: $.extend($form.data('asset').callback.data,
key: $result.find('Key').text()
bucket: $result.find('Bucket').text())
success: (callback_response, textStatus, jqXHR) ->
#window.console and console.log('callback success', callback_response, textStatus, jqXHR)
if args['progressBar']
$(args['progressBar']).addClass('_complete')
if args['urlInput']
$(args['urlInput']).val( callback_response['url'] ).change()
if args['for']
$(args['for']).val( callback_response['url'] ).change()
if args['idInput']
$(args['idInput']).val( callback_response['id'] ).change()
if args['backgroundPreview']
$(args['backgroundPreview']).css('background-image', 'url(\'' + callback_response['url'] + '\')').addClass( '_fileupload_preview' )
if args['imgPreview']
$(args['imgPreview']).attr('src', callback_response['url']).addClass '_fileupload_preview'
if args['callback']
args['callback']( callback_response )
return
#window.console and console.log(request)
$.ajax request
return
fail: (e, data) ->
#window.console and console.log('fail', e, data, data.result)
return
success: (e, data) ->
#window.console and console.log('success', e, data, data.result)
return
$form.find('input').click()
return
jQuery.fn.assetup = (args) ->
args = {} if args == undefined
$(this).each ()->
$this = $(this)
$for = $($this.data('for'))
acceptFileTypes = args['accept-file-types'] || $this.data('accept-file-types') || /(\.|\/)(gif|jpe?g|png)$/i
maxFileSize = args['max-file-size'] || $this.data('max-file-size') || 5000000
asset = args['asset'] || $this.data('asset') || {}
params = args['params'] || $this.data('params') || {}
params.asset = asset
form_id = "new_asset_"+(assetup_counter++)
$('body').append("""
<form accept-charset="UTF-8" action="/asset_manager?response=url&#{$.param(params)}" class="new_asset" enctype="multipart/form-data" id="#{form_id}" method="post" style="display:none;">
<div style="display:none"><input name="utf8" type="hidden" value="✓"><!--<input name="authenticity_token" type="hidden" value="<KEY>>--></div>
<input name="file" type="file">
<input name="commit" type="submit" value="Upload">
</form>
""")
$form = $('#'+form_id)
$upload = $form.find('[type=file]')
$form.fileupload(
maxFileSize: maxFileSize,
acceptFileTypes: acceptFileTypes,
progress: (e, data) ->
# Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10);
#window.console and console.log progress, e, data if window.console
done: (e, data) ->
#window.console and console.log data.result if window.console
$for.each ()->
if $(this).is('img')
$(this).attr('src',data.result)
else
$(this).val(data.result).change()
$form.remove()
)
$upload.change = (e)->
$form.submit()
$upload.click()
$(document).ready ->
$(document).on(
'click'
'[data-toggle=assetup]',
(e)->
e.preventDefault()
$(this).assetup()
)
$(document).on(
'click'
'.asset-direct',
(e)->
e.preventDefault()
e.stopPropagation()
#window.console && console.log 'data', $(this).data()
$.assetdirect( $.extend($(this).data()||{},{ newUrl: $(this).attr('href'), progressOutput: $('.progress_output',this), for: $(this).attr('for') }) )
) | true | #= require ./jquery.fileupload
#= require ./jquery.iframe-transport
assetup_counter = 0;
jQuery.assetdirect = (args) ->
args = {} if args == undefined
#window.console and console.log 'assetdirect', args
if args['progressBar']
$(args['progressBar']).removeClass('_'+per+'-per') for per in [0,5,10,15,20,25,30,35,40,45,50,55,60,65,70,75,80,85,90,95,100]
$(args['progressBar']).removeClass('_complete')
$form = $('<form enctype="multipart/form-data" id="file_upload" method="post"><input name="file" type="file"></form>')
$form.fileupload
autoUpload: true
method: 'POST'
action: ''
add: (event, data) ->
$.ajax
dataType: 'json'
url: args['newUrl']
cache: false
success: (response) ->
#console.log(JSON.stringify(response))
data.url = response.action
data.formData = response.request
$form.data 'asset', response
$form.fileupload 'send', data
return
error: (response, status) ->
#window.console and console.log('there was an error')
return
return
progress: (e, data) ->
#Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10)
#window.console and console.log('progress', progress, e, data, args['progressBar'], args)
if args['progressOutput']
$(args['progressOutput']).html (if progress >= 10 and progress < 10 then ' ' else '') + progress + '%'
if args['progressBar']
increment = Math.floor(progress / 5) * 5
#window.console and console.log "increment", increment
$(args['progressBar']).addClass('_'+increment+'-per')
return
send: (e, data) ->
#window.console and console.log('send', e, data)
return
done: (e, data) ->
#window.console and console.log('done', e, data, data.result)
$result = $(data.result)
request =
dataType: 'json'
url: $form.data('asset').callback.url
method: 'GET'
data: $.extend($form.data('asset').callback.data,
key: $result.find('Key').text()
bucket: $result.find('Bucket').text())
success: (callback_response, textStatus, jqXHR) ->
#window.console and console.log('callback success', callback_response, textStatus, jqXHR)
if args['progressBar']
$(args['progressBar']).addClass('_complete')
if args['urlInput']
$(args['urlInput']).val( callback_response['url'] ).change()
if args['for']
$(args['for']).val( callback_response['url'] ).change()
if args['idInput']
$(args['idInput']).val( callback_response['id'] ).change()
if args['backgroundPreview']
$(args['backgroundPreview']).css('background-image', 'url(\'' + callback_response['url'] + '\')').addClass( '_fileupload_preview' )
if args['imgPreview']
$(args['imgPreview']).attr('src', callback_response['url']).addClass '_fileupload_preview'
if args['callback']
args['callback']( callback_response )
return
#window.console and console.log(request)
$.ajax request
return
fail: (e, data) ->
#window.console and console.log('fail', e, data, data.result)
return
success: (e, data) ->
#window.console and console.log('success', e, data, data.result)
return
$form.find('input').click()
return
jQuery.fn.assetup = (args) ->
args = {} if args == undefined
$(this).each ()->
$this = $(this)
$for = $($this.data('for'))
acceptFileTypes = args['accept-file-types'] || $this.data('accept-file-types') || /(\.|\/)(gif|jpe?g|png)$/i
maxFileSize = args['max-file-size'] || $this.data('max-file-size') || 5000000
asset = args['asset'] || $this.data('asset') || {}
params = args['params'] || $this.data('params') || {}
params.asset = asset
form_id = "new_asset_"+(assetup_counter++)
$('body').append("""
<form accept-charset="UTF-8" action="/asset_manager?response=url&#{$.param(params)}" class="new_asset" enctype="multipart/form-data" id="#{form_id}" method="post" style="display:none;">
<div style="display:none"><input name="utf8" type="hidden" value="✓"><!--<input name="authenticity_token" type="hidden" value="PI:KEY:<KEY>END_PI>--></div>
<input name="file" type="file">
<input name="commit" type="submit" value="Upload">
</form>
""")
$form = $('#'+form_id)
$upload = $form.find('[type=file]')
$form.fileupload(
maxFileSize: maxFileSize,
acceptFileTypes: acceptFileTypes,
progress: (e, data) ->
# Calculate the completion percentage of the upload
progress = parseInt(data.loaded / data.total * 100, 10);
#window.console and console.log progress, e, data if window.console
done: (e, data) ->
#window.console and console.log data.result if window.console
$for.each ()->
if $(this).is('img')
$(this).attr('src',data.result)
else
$(this).val(data.result).change()
$form.remove()
)
$upload.change = (e)->
$form.submit()
$upload.click()
$(document).ready ->
$(document).on(
'click'
'[data-toggle=assetup]',
(e)->
e.preventDefault()
$(this).assetup()
)
$(document).on(
'click'
'.asset-direct',
(e)->
e.preventDefault()
e.stopPropagation()
#window.console && console.log 'data', $(this).data()
$.assetdirect( $.extend($(this).data()||{},{ newUrl: $(this).attr('href'), progressOutput: $('.progress_output',this), for: $(this).attr('for') }) )
) |
[
{
"context": "re 'swig'\n\nleancloud = {\n \"applicationName\" : \"ywen_blog\",\n \"applicationId\": \"your id\",\n \"applicatio",
"end": 130,
"score": 0.8800698518753052,
"start": 121,
"tag": "USERNAME",
"value": "ywen_blog"
},
{
"context": "icationId\": \"your id\",\n \... | source/coffee/cloud/app.coffee | yaliyingwy/ywen-blog | 0 | 'use strict'
express = require 'express'
app = express()
swig = require 'swig'
leancloud = {
"applicationName" : "ywen_blog",
"applicationId": "your id",
"applicationKey": "your key",
"global": {
"avVersion": "0.3.1"
}
}
app.engine 'html', swig.renderFile
app.set 'views', 'cloud/views'
app.set 'view engine', 'html'
app.use express.bodyParser()
app.get '/', (req, res)->
res.render 'index', {leancloud: leancloud}
app.listen()
| 113245 | 'use strict'
express = require 'express'
app = express()
swig = require 'swig'
leancloud = {
"applicationName" : "ywen_blog",
"applicationId": "your id",
"applicationKey": "your <KEY>",
"global": {
"avVersion": "0.3.1"
}
}
app.engine 'html', swig.renderFile
app.set 'views', 'cloud/views'
app.set 'view engine', 'html'
app.use express.bodyParser()
app.get '/', (req, res)->
res.render 'index', {leancloud: leancloud}
app.listen()
| true | 'use strict'
express = require 'express'
app = express()
swig = require 'swig'
leancloud = {
"applicationName" : "ywen_blog",
"applicationId": "your id",
"applicationKey": "your PI:KEY:<KEY>END_PI",
"global": {
"avVersion": "0.3.1"
}
}
app.engine 'html', swig.renderFile
app.set 'views', 'cloud/views'
app.set 'view engine', 'html'
app.use express.bodyParser()
app.get '/', (req, res)->
res.render 'index', {leancloud: leancloud}
app.listen()
|
[
{
"context": "###\n * DownloadStats\n * http://github.com/ingorichter/BracketsExtensionTweetBot\n *\n * Copyright (c) 201",
"end": 53,
"score": 0.9996300935745239,
"start": 42,
"tag": "USERNAME",
"value": "ingorichter"
},
{
"context": "BracketsExtensionTweetBot\n *\n * Copyright (c) ... | src/DownloadStats.coffee | ingorichter/BracketsExtensionTweetBot | 0 | ###
* DownloadStats
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 Ingo Richter
* Licensed under the MIT license.
###
'use strict'
path = require 'path'
_ = require 'lodash'
Promise = require 'bluebird'
fs = Promise.promisifyAll require 'fs'
p = fs.readFileAsync path.resolve(path.join module.id, 'registry-last-sunday.json')
p.then (json) ->
JSON.parse json
.then (registry) ->
allThemes = _.filter registry, (extension) -> extension.metadata.theme?
allExtensions = _.filter registry, (extension) -> !extension.metadata.theme?
predicate = (extension) ->
sum = _.reduce extension.recent, (num, sum) ->
sum + num
t = {name: extension.metadata.title, sum: sum ? 0}
topExtensions = _.map allExtensions, predicate
topThemes = _.map allThemes, predicate
# list = '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
# console.log _.template list, { 'extensions': _.first((_.sortBy topExtensions, "sum").reverse(), 11) }
# console.log _.template list, { 'extensions': _.first((_.sortBy topThemes, "sum").reverse(), 11) }
compiled = _.template '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
console.log compiled { 'extensions': _.slice((_.sortBy topExtensions, "sum").reverse(), 0, 11) }
console.log compiled { 'extensions': _.slice((_.sortBy topThemes, "sum").reverse(), 0, 11) }
| 102095 | ###
* DownloadStats
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 <NAME>
* Licensed under the MIT license.
###
'use strict'
path = require 'path'
_ = require 'lodash'
Promise = require 'bluebird'
fs = Promise.promisifyAll require 'fs'
p = fs.readFileAsync path.resolve(path.join module.id, 'registry-last-sunday.json')
p.then (json) ->
JSON.parse json
.then (registry) ->
allThemes = _.filter registry, (extension) -> extension.metadata.theme?
allExtensions = _.filter registry, (extension) -> !extension.metadata.theme?
predicate = (extension) ->
sum = _.reduce extension.recent, (num, sum) ->
sum + num
t = {name: extension.metadata.title, sum: sum ? 0}
topExtensions = _.map allExtensions, predicate
topThemes = _.map allThemes, predicate
# list = '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
# console.log _.template list, { 'extensions': _.first((_.sortBy topExtensions, "sum").reverse(), 11) }
# console.log _.template list, { 'extensions': _.first((_.sortBy topThemes, "sum").reverse(), 11) }
compiled = _.template '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
console.log compiled { 'extensions': _.slice((_.sortBy topExtensions, "sum").reverse(), 0, 11) }
console.log compiled { 'extensions': _.slice((_.sortBy topThemes, "sum").reverse(), 0, 11) }
| true | ###
* DownloadStats
* http://github.com/ingorichter/BracketsExtensionTweetBot
*
* Copyright (c) 2014 PI:NAME:<NAME>END_PI
* Licensed under the MIT license.
###
'use strict'
path = require 'path'
_ = require 'lodash'
Promise = require 'bluebird'
fs = Promise.promisifyAll require 'fs'
p = fs.readFileAsync path.resolve(path.join module.id, 'registry-last-sunday.json')
p.then (json) ->
JSON.parse json
.then (registry) ->
allThemes = _.filter registry, (extension) -> extension.metadata.theme?
allExtensions = _.filter registry, (extension) -> !extension.metadata.theme?
predicate = (extension) ->
sum = _.reduce extension.recent, (num, sum) ->
sum + num
t = {name: extension.metadata.title, sum: sum ? 0}
topExtensions = _.map allExtensions, predicate
topThemes = _.map allThemes, predicate
# list = '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
# console.log _.template list, { 'extensions': _.first((_.sortBy topExtensions, "sum").reverse(), 11) }
# console.log _.template list, { 'extensions': _.first((_.sortBy topThemes, "sum").reverse(), 11) }
compiled = _.template '<% _.forEach(extensions, function(extension) { %>|<%= extension.name %>|<%= extension.sum %>|\n<% }); %>'
console.log compiled { 'extensions': _.slice((_.sortBy topExtensions, "sum").reverse(), 0, 11) }
console.log compiled { 'extensions': _.slice((_.sortBy topThemes, "sum").reverse(), 0, 11) }
|
[
{
"context": "# Copyright (c) Konode. All rights reserved.\n# This source code is subje",
"end": 22,
"score": 0.9675344228744507,
"start": 16,
"tag": "NAME",
"value": "Konode"
},
{
"context": "\t\t\t\t})\n\t\t\t\t\tTableHeaderColumn({\n\t\t\t\t\t\tdataField: 'lastName'\n\t\t\t\t\t\td... | src/clientSelectionPage.coffee | LogicalOutcomes/KoNote | 1 | # Copyright (c) Konode. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
_ = require 'underscore'
Imm = require 'immutable'
Async = require 'async'
Config = require './config'
Term = require './term'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
ReactDOM = win.ReactDOM
R = React.DOM
# TODO: Refactor to single require
{BootstrapTable, TableHeaderColumn} = win.ReactBootstrapTable
BootstrapTable = React.createFactory BootstrapTable
TableHeaderColumn = React.createFactory TableHeaderColumn
MainMenu = require('./mainMenu').load(win)
OpenDialogLink = require('./openDialogLink').load(win)
ProgramBubbles = require('./programBubbles').load(win)
ManagerLayer = require('./managerLayer').load(win)
CreateClientFileDialog = require('./createClientFileDialog').load(win)
CrashHandler = require('./crashHandler').load(win)
{FaIcon, openWindow, renderName, stripMetadata, objectsAsIdMap} = require('./utils').load(win)
ClientSelectionPage = React.createFactory React.createClass
displayName: 'ClientSelectionPage'
getInitialState: ->
return {
status: 'init'
loadingFile: false
clientFileHeaders: null
metricsById: null
programsById: null
userProgramId: null
userProgramLinks: Imm.List()
clientFileProgramLinks: null
displayAllPrograms: false
}
init: ->
windowTitle = "#{Config.productName} (#{global.ActiveSession.userName})"
if Config.logoSubtitle
windowTitle = "#{Config.logoSubtitle} - #{windowTitle}"
@props.setWindowTitle(windowTitle)
@_loadInitialData()
deinit: (cb=(->)) ->
# Nothing to deinit
cb()
suggestClose: ->
@props.closeWindow()
nw.App.closeAllWindows()
render: ->
unless @state.status is 'ready'
return null
userProgram = @_getUserProgram()
isAdmin = global.ActiveSession.isAdmin()
# For regular users, we filter out clientFiles that
# and don't match the user's assigned program
clientFileHeaders = if userProgram? and not @state.displayAllPrograms
@state.clientFileHeaders.filter (clientFile) =>
clientFileId = clientFile.get('id')
@state.clientFileProgramLinks.some (link) =>
link.get('clientFileId') is clientFileId and
link.get('programId') is @state.userProgramId and
link.get('status') is 'enrolled'
else
@state.clientFileHeaders
return ClientSelectionPageUi {
openClientFile: _.debounce @_openClientFile, 1000, true
clientFileHeaders
allClientFileHeaders: @state.clientFileHeaders
clientFileProgramLinks: @state.clientFileProgramLinks
programsById: @state.programsById
userProgram
userProgramLinks: @state.userProgramLinks
metricsById: @state.metricsById
displayAllPrograms: @state.displayAllPrograms
toggleAllPrograms: @_toggleAllPrograms
}
_toggleAllPrograms: ->
@setState {displayAllPrograms: not @state.displayAllPrograms}
_getUserProgram: ->
if @state.userProgramId?
return @state.programsById.get(@state.userProgramId)
return null
_openClientFile: (clientFileId) ->
appWindows = chrome.app.window.getAll()
# skip if no client files open
if appWindows.length > 2
clientName = ''
ActiveSession.persist.clientFiles.readLatestRevisions clientFileId, 1, (err, revisions) =>
if err
# fail silently, let user retry
return
clientFile = stripMetadata revisions.get(0)
clientName = renderName clientFile.get('clientName')
clientFileOpen = false
appWindows.forEach (appWindow) ->
winTitle = nw.Window.get(appWindow.contentWindow).window.document.title
if winTitle.includes(clientName)
# already open, focus
clientFileOpen = true
nw.Window.get(appWindow.contentWindow).focus()
return
if clientFileOpen is false
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
clientFileWindow.on 'close', =>
clientFileWindow = null
else
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
# prevent window from closing before its ready
clientFileWindow.on 'close', =>
clientFileWindow = null
_loadInitialData: ->
Async.parallel [
(cb) =>
ActiveSession.persist.clientFiles.list (err, result) =>
if err
cb err
return
@setState (s) ->
return {
clientFileHeaders: result
}
, cb
(cb) =>
programHeaders = null
programs = null
programsById = null
userProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.programs.list (err, result) =>
if err
cb err
return
programHeaders = result
cb()
(cb) =>
Async.map programHeaders.toArray(), (programHeader, cb) =>
progId = programHeader.get('id')
ActiveSession.persist.programs.readLatestRevisions progId, 1, cb
, (err, results) =>
if err
cb err
return
programs = Imm.List(results)
.map (programRevs) -> programRevs.get(0)
programsById = objectsAsIdMap programs
cb()
(cb) =>
ActiveSession.persist.userProgramLinks.list (err, result) ->
if err
cb err
return
# TODO why is metadata stripped here?
userProgramLinks = result.map (link) -> stripMetadata(link)
cb()
(cb) =>
# Figure out userProgramId (We currently assume there can only be one)
# TODO: Refactor to something a little nicer
matchingUserProgramLinks = userProgramLinks.filter (link) ->
return link.get('userName') is global.ActiveSession.userName and
link.get('status') is 'assigned'
if matchingUserProgramLinks.size > 1
console.warn(
"More than 1 assigned programLink found",
matchingUserProgramLinks.toJS()
)
userProgramLink = matchingUserProgramLinks.get(0, null)
userProgramId = userProgramLink?.get('programId')
global.ActiveSession.programId = userProgramId
@setState (s) ->
return {
programsById
userProgramId
userProgramLinks
}
, cb
], cb
(cb) =>
clientFileProgramLinkHeaders = null
clientFileProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.clientFileProgramLinks.list (err, result) =>
if err
cb err
return
clientFileProgramLinkHeaders = result
cb()
(cb) =>
Async.map clientFileProgramLinkHeaders.toArray(), (linkHeader, cb) =>
linkId = linkHeader.get('id')
ActiveSession.persist.clientFileProgramLinks.readLatestRevisions linkId, 1, cb
, (err, results) =>
if err
cb err
return
clientFileProgramLinks = Imm.List(results)
# TODO why is metadata stripped here?
.map (linkRevs) -> stripMetadata linkRevs.get(0)
cb()
(cb) =>
@setState (s) ->
return {
clientFileProgramLinks
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
@setState {
status: 'ready'
}
@_loadSecondaryData()
# Load data not needed for default tab
_loadSecondaryData: ->
Async.parallel [
(cb) =>
# TODO Load metrics on first click to metric definition manager
metricHeaders = null
metrics = null
Async.series [
(cb) ->
ActiveSession.persist.metrics.list (err, result) =>
if err
cb err
return
metricHeaders = result
cb()
(cb) ->
Async.map metricHeaders.toArray(), (metricHeader, cb) =>
metricId = metricHeader.get('id')
ActiveSession.persist.metrics.readLatestRevisions metricId, 1, cb
, (err, results) =>
if err
cb err
return
metrics = Imm.List(results).map (metricRevs) ->
return metricRevs.first()
cb()
(cb) =>
@setState (s) ->
return {
metricsById: objectsAsIdMap metrics
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
# Done
getPageListeners: ->
return {
# Custom listener for overriding userProgram in ActiveSession
'override:userProgram': (userProgram) =>
console.log "Override userProgram to:"
if userProgram?
console.log "Program:", userProgram.toJS()
else
console.log "None (null)"
userProgramId = if userProgram? then userProgram.get('id') else null
global.ActiveSession.programId = userProgramId
@setState {userProgramId}
'create:userProgramLink createRevision:userProgramLink': (userProgramLink) =>
isForCurrentUser = userProgramLink.get('userName') is global.ActiveSession.userName
if isForCurrentUser
if userProgramLink.get('status') is 'assigned'
# Trigger override userProgram for current user
userProgram = @state.programsById.get userProgramLink.get('programId')
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
else
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', null
# Does a revision of the link already exist?
existingLink = @state.userProgramLinks.find (link) -> link.get('id') is userProgramLink.get('id')
if existingLink?
# Overwrite existing link in state
linkIndex = @state.userProgramLinks.indexOf existingLink
userProgramLinks = @state.userProgramLinks.set linkIndex, userProgramLink
else
userProgramLinks = @state.userProgramLinks.push userProgramLink
@setState {userProgramLinks}
'create:clientFile': (newFile) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.push newFile
}
'createRevision:clientFile': (newRev) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.map (cf) ->
if cf.get('id') is newRev.get('id')
return newRev
return cf
}
'create:program createRevision:program': (newObj) =>
@setState (s) ->
return {
programsById: s.programsById.set newObj.get('id'), newObj
}
'create:clientFileProgramLink': (newObj) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.push newObj
}
'createRevision:clientFileProgramLink': (newRev) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.map (obj) ->
if obj.get('id') is newRev.get('id')
return newRev
return obj
}
'create:metric createRevision:metric': (newObj) =>
@setState (s) ->
return {
metricsById: s.metricsById.set newObj.get('id'), newObj
}
}
ClientSelectionPageUi = React.createFactory React.createClass
displayName: 'ClientSelectionPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSmallHeaderSet: false
menuIsOpen: false
menuIconIsOpen: true
managerLayer: null
queryText: ''
}
componentDidMount: ->
# Fire 'loaded' event for loginPage to hide itself
global.ActiveSession.persist.eventBus.trigger 'clientSelectionPage:loaded'
# Key bindings for search results navigation
@_attachKeyBindings()
# Double-ensure that global.ActiveSession.programId lines up with @props.userProgram
global.ActiveSession.programId = if @props.userProgram then @props.userProgram.get('id') else null
render: ->
isAdmin = global.ActiveSession.isAdmin()
smallHeader = @state.queryText.length > 0 or @state.isSmallHeaderSet
return R.div({
id: 'clientSelectionPage'
className: [
'animated fadeIn'
'menuIsOpen' if @state.menuIsOpen
].join ' '
},
R.a({
id: 'expandMenuButton'
className: [
'animated fadeIn'
'menuIsOpen animated fadeInRight' if @state.menuIsOpen
].join ' '
onClick: =>
@_toggleUserMenu()
@refs.searchBox.focus() if @refs.searchBox? and @state.menuIsOpen
},
if @state.menuIsOpen
FaIcon('times', {className:'animated fadeOutRight' unless @state.menuIconIsOpen})
else
"Menu"
)
R.div({
id: 'mainContainer'
style:
width: if @state.menuIsOpen then '80%' else '100%'
},
(if @state.managerLayer?
ManagerLayer({
name: @state.managerLayer
clientFileHeaders: @props.allClientFileHeaders
programsById: @props.programsById
userProgramLinks: @props.userProgramLinks
clientFileProgramLinks: @props.clientFileProgramLinks
metricsById: @props.metricsById
menuIsOpen: @state.menuIsOpen
})
)
R.div({
id: 'main'
onClick: =>
@_toggleUserMenu() if @state.menuIsOpen
@refs.searchBox.focus() if @refs.searchBox?
},
R.header({
className: [
if smallHeader then 'small' else ''
].join ' '
},
R.div({className: 'logoContainer'},
R.img({src: Config.logoCustomerLg})
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
)
R.div({className: 'searchBoxContainer'},
noData = @props.clientFileHeaders.isEmpty()
R.div({className: 'input-group'}
(unless noData or not isAdmin
OpenDialogLink({
className: 'input-group-btn'
ref: 'openCreateClientSmall'
dialog: CreateClientFileDialog
programsById: @props.programsById
},
R.button({
className: 'btn btn-default'
title: "Add new Client File"
},
R.span({className: 'text-success'}, FaIcon('plus'))
)
)
)
R.input({
className: 'searchBox form-control'
ref: 'searchBox'
type: 'text'
autoFocus: true
disabled: noData
placeholder:
unless noData
"Search for a #{Term 'client'}'s profile..."
else
"No #{Term 'client files'} to search yet..."
onChange: @_updateQueryText
value: @state.queryText
})
R.span({className: 'input-group-btn'},
(unless noData
R.button({
className: 'btn btn-default'
onClick: @_showAll
}, "Show All")
else
OpenDialogLink({
className: 'btn btn-success'
dialog: CreateClientFileDialog
programsById: @props.programsById
disabled: not isAdmin
},
"New #{Term 'Client File'} "
FaIcon('folder-open')
)
)
)
)
)
)
R.div({
className: [
'smallHeaderLogo'
if smallHeader then 'show' else 'hidden'
].join ' '
},
R.img({
src: Config.logoCustomerLg
onClick: @_home
})
)
ClientTableWrapper({
ref: 'clientTable'
queryText: @state.queryText
clientFileHeaders: @props.clientFileHeaders
clientFileProgramLinks: @props.clientFileProgramLinks
programsById: @props.programsById
onRowClick: @_onResultSelection
displayAllPrograms: @props.displayAllPrograms
toggleAllPrograms: @props.toggleAllPrograms
})
)
)
(if @state.menuIsOpen
MainMenu({
ref: 'userMenu'
className: 'menuIsOpen animated fadeInRight'
isAdmin
programsById: @props.programsById
userProgram: @props.userProgram
managerLayer: @state.managerLayer
isSmallHeaderSet: @state.isSmallHeaderSet
updateManagerLayer: @_updateManagerLayer
})
)
)
_attachKeyBindings: ->
# Key-bindings for searchBox
$(@refs.searchBox).on 'keydown', (event) =>
# Don't need to see this unless in full search view
return if not @state.isSmallHeaderSet
switch event.which
when 40 # Down arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(1)
when 38 # Up arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(-1)
when 27 # Esc
@refs.clientTable.clearActiveIndex()
when 13 # Enter
$active = $('.activeIndex')
return unless $active.length
$active[0].click()
return false
_updateManagerLayer: (managerLayer) ->
if managerLayer is null
@setState {isSmallHeaderSet: true, queryText: '', managerLayer}
return
@setState {managerLayer}
_toggleUserMenu: ->
if @state.menuIsOpen
mainMenuNode = ReactDOM.findDOMNode(@refs.userMenu)
$(mainMenuNode).addClass('slideOutRight')
# @setState {managerLayer: null}
@setState {menuIconIsOpen: false}
setTimeout(=>
@setState {menuIsOpen: false}
, 400)
else
@setState {menuIsOpen: true}
@setState {menuIconIsOpen: true}
_updateQueryText: (event) ->
@setState {queryText: event.target.value}
if event.target.value.length > 0
@setState {isSmallHeaderSet: true}
_showAll: ->
@setState {isSmallHeaderSet: true, queryText: ''}
_home: ->
@setState {isSmallHeaderSet: false, queryText: ''}
_onResultSelection: (clientFileId) ->
@props.openClientFile(clientFileId)
ClientTableWrapper = React.createFactory React.createClass
displayName: 'ClientTableWrapper'
propTypes: {
queryText: React.PropTypes.string.isRequired
clientFileHeaders: React.PropTypes.instanceOf(Imm.List).isRequired
clientFileProgramLinks: React.PropTypes.instanceOf(Imm.List).isRequired
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
toggleAllPrograms: React.PropTypes.func.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayInactive: false
}
render: ->
queryResults = @_filterResults()
# Add in all program objects this clientFile's a member of
tableData = queryResults.map (clientFile) =>
clientFileId = clientFile.get('id')
programMemberships = null
if @props.clientFileProgramLinks?
programMemberships = @props.clientFileProgramLinks
.filter (link) =>
link.get('clientFileId') is clientFileId and link.get('status') is "enrolled"
.map (link) =>
stripMetadata @props.programsById.get(link.get('programId'))
givenNames = clientFile.getIn(['clientName', 'first'])
middleName = clientFile.getIn(['clientName', 'middle'])
if middleName then givenNames += ", #{middleName}"
return clientFile
.set('programs', programMemberships)
.set('givenNames', givenNames) # Flatten names for columns
.set('lastName', clientFile.getIn(['clientName', 'last']))
# Get inactive clientFile results for filter display
inactiveClientFiles = tableData.filter (clientFile) ->
clientFile.get('status') isnt 'active'
# Filter out inactive clientFile results by default
if not @state.displayInactive
tableData = tableData.filter (clientFile) ->
clientFile.get('status') is 'active'
# Are ANY clientFiles inactive?
hasInactiveFiles = @props.clientFileHeaders.some (clientFile) ->
clientFile.get('status') and (clientFile.get('status') isnt 'active')
return R.div({className: 'clientTableWrapper'},
# TODO: Component for multiple kinds of filters/toggles
R.div({id: 'filterSelectionContainer'}
(if hasInactiveFiles or not hasInactiveFiles
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @_toggleInactive
type: 'checkbox'
checked: @state.displayInactive
})
" Show inactive (#{inactiveClientFiles.size})",
)
)
)
(if global.ActiveSession.isAdmin() and global.ActiveSession.programId?
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @props.toggleAllPrograms
type: 'checkbox'
checked: @props.displayAllPrograms
})
" All Programs",
)
)
)
)
ClientTable({
ref: 'clientTable'
data: tableData
queryText: @props.queryText
hasProgramLinks: not @props.clientFileProgramLinks.isEmpty()
hasInactiveFiles
displayInactive: @state.displayInactive
onRowClick: @props.onRowClick
})
)
shiftActiveIndex: (modifier) -> @refs.clientTable.shiftActiveIndex(modifier)
clearActiveIndex: -> @refs.clientTable.clearActiveIndex()
_toggleInactive: ->
@setState {displayInactive: not @state.displayInactive}
_filterResults: ->
if @props.queryText.trim().length is 0
return @props.clientFileHeaders
# Split into query parts
queryParts = Imm.fromJS(@props.queryText.split(' ')).map (p) -> p.toLowerCase()
# Calculate query results
queryResults = @props.clientFileHeaders
.filter (clientFile) ->
firstName = clientFile.getIn(['clientName', 'first']).toLowerCase()
middleName = clientFile.getIn(['clientName', 'middle']).toLowerCase()
lastName = clientFile.getIn(['clientName', 'last']).toLowerCase()
recordId = clientFile.getIn(['recordId']).toLowerCase()
return queryParts
.every (part) ->
return firstName.includes(part) or
middleName.includes(part) or
lastName.includes(part) or
recordId.includes(part)
return queryResults
ClientTable = React.createFactory React.createClass
displayName: 'ClientTable'
propTypes: {
queryText: React.PropTypes.string.isRequired
data: React.PropTypes.instanceOf(Imm.List).isRequired
hasProgramLinks: React.PropTypes.bool.isRequired
hasInactiveFiles: React.PropTypes.bool.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
activeIndex: null
}
render: ->
return R.div({className: 'responsiveTable'},
BootstrapTable({
data: @props.data.toJS()
keyField: 'id'
bordered: false
options: {
onRowClick: ({id}) => @props.onRowClick(id)
noDataText: (if @props.queryText
"No #{Term 'client files'} matching \"#{@props.queryText}\"."
else
"No #{Term 'client files'} found."
)
defaultSortName: 'lastName'
defaultSortOrder: 'asc'
}
trClassName: (row, index) => [
'clientRow'
'activeIndex' if index is @state.activeIndex
'inactive' unless row.status is 'active'
].join ' '
},
TableHeaderColumn({
dataField: 'programs'
dataFormat: (programs) ->
return null unless programs
ProgramBubbles({programs: Imm.fromJS(programs)})
className: 'leftPadding'
columnClassName: 'leftPadding'
width: '150px'
hidden: not @props.hasProgramLinks
})
TableHeaderColumn({
dataField: 'lastName'
dataSort: true
className: 'leftPadding' if not @props.hasProgramLinks
columnClassName: 'leftPadding' if not @props.hasProgramLinks
}, "Last Name")
TableHeaderColumn({
dataField: 'givenNames'
dataSort: true
className: 'visibleColumn'
columnClassName: 'visibleColumn'
}, "Given Names")
TableHeaderColumn({
dataField: 'recordId'
dataSort: true
className: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
columnClassName: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
headerAlign: 'right'
dataAlign: 'right'
hidden: not Config.clientFileRecordId.isEnabled
}, Config.clientFileRecordId.label)
TableHeaderColumn({
dataField: 'status'
dataSort: true
headerAlign: 'right'
dataAlign: 'right'
className: 'rightPadding' if @props.displayInactive
columnClassName: 'rightPadding' if @props.displayInactive
hidden: not @props.displayInactive
}, "Status")
)
)
shiftActiveIndex: (modifier) ->
if @state.activeIndex is null
activeIndex = 0
@setState {activeIndex}
return
activeIndex = @state.activeIndex + modifier
numberClientRows = @props.data.size
if activeIndex < 0
activeIndex = numberClientRows - 1
else if activeIndex > (numberClientRows - 1)
activeIndex = 0
@setState {activeIndex}
clearActiveIndex: -> @setState {activeIndex: null}
return ClientSelectionPage
module.exports = {load}
| 197459 | # Copyright (c) <NAME>. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
_ = require 'underscore'
Imm = require 'immutable'
Async = require 'async'
Config = require './config'
Term = require './term'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
ReactDOM = win.ReactDOM
R = React.DOM
# TODO: Refactor to single require
{BootstrapTable, TableHeaderColumn} = win.ReactBootstrapTable
BootstrapTable = React.createFactory BootstrapTable
TableHeaderColumn = React.createFactory TableHeaderColumn
MainMenu = require('./mainMenu').load(win)
OpenDialogLink = require('./openDialogLink').load(win)
ProgramBubbles = require('./programBubbles').load(win)
ManagerLayer = require('./managerLayer').load(win)
CreateClientFileDialog = require('./createClientFileDialog').load(win)
CrashHandler = require('./crashHandler').load(win)
{FaIcon, openWindow, renderName, stripMetadata, objectsAsIdMap} = require('./utils').load(win)
ClientSelectionPage = React.createFactory React.createClass
displayName: 'ClientSelectionPage'
getInitialState: ->
return {
status: 'init'
loadingFile: false
clientFileHeaders: null
metricsById: null
programsById: null
userProgramId: null
userProgramLinks: Imm.List()
clientFileProgramLinks: null
displayAllPrograms: false
}
init: ->
windowTitle = "#{Config.productName} (#{global.ActiveSession.userName})"
if Config.logoSubtitle
windowTitle = "#{Config.logoSubtitle} - #{windowTitle}"
@props.setWindowTitle(windowTitle)
@_loadInitialData()
deinit: (cb=(->)) ->
# Nothing to deinit
cb()
suggestClose: ->
@props.closeWindow()
nw.App.closeAllWindows()
render: ->
unless @state.status is 'ready'
return null
userProgram = @_getUserProgram()
isAdmin = global.ActiveSession.isAdmin()
# For regular users, we filter out clientFiles that
# and don't match the user's assigned program
clientFileHeaders = if userProgram? and not @state.displayAllPrograms
@state.clientFileHeaders.filter (clientFile) =>
clientFileId = clientFile.get('id')
@state.clientFileProgramLinks.some (link) =>
link.get('clientFileId') is clientFileId and
link.get('programId') is @state.userProgramId and
link.get('status') is 'enrolled'
else
@state.clientFileHeaders
return ClientSelectionPageUi {
openClientFile: _.debounce @_openClientFile, 1000, true
clientFileHeaders
allClientFileHeaders: @state.clientFileHeaders
clientFileProgramLinks: @state.clientFileProgramLinks
programsById: @state.programsById
userProgram
userProgramLinks: @state.userProgramLinks
metricsById: @state.metricsById
displayAllPrograms: @state.displayAllPrograms
toggleAllPrograms: @_toggleAllPrograms
}
_toggleAllPrograms: ->
@setState {displayAllPrograms: not @state.displayAllPrograms}
_getUserProgram: ->
if @state.userProgramId?
return @state.programsById.get(@state.userProgramId)
return null
_openClientFile: (clientFileId) ->
appWindows = chrome.app.window.getAll()
# skip if no client files open
if appWindows.length > 2
clientName = ''
ActiveSession.persist.clientFiles.readLatestRevisions clientFileId, 1, (err, revisions) =>
if err
# fail silently, let user retry
return
clientFile = stripMetadata revisions.get(0)
clientName = renderName clientFile.get('clientName')
clientFileOpen = false
appWindows.forEach (appWindow) ->
winTitle = nw.Window.get(appWindow.contentWindow).window.document.title
if winTitle.includes(clientName)
# already open, focus
clientFileOpen = true
nw.Window.get(appWindow.contentWindow).focus()
return
if clientFileOpen is false
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
clientFileWindow.on 'close', =>
clientFileWindow = null
else
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
# prevent window from closing before its ready
clientFileWindow.on 'close', =>
clientFileWindow = null
_loadInitialData: ->
Async.parallel [
(cb) =>
ActiveSession.persist.clientFiles.list (err, result) =>
if err
cb err
return
@setState (s) ->
return {
clientFileHeaders: result
}
, cb
(cb) =>
programHeaders = null
programs = null
programsById = null
userProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.programs.list (err, result) =>
if err
cb err
return
programHeaders = result
cb()
(cb) =>
Async.map programHeaders.toArray(), (programHeader, cb) =>
progId = programHeader.get('id')
ActiveSession.persist.programs.readLatestRevisions progId, 1, cb
, (err, results) =>
if err
cb err
return
programs = Imm.List(results)
.map (programRevs) -> programRevs.get(0)
programsById = objectsAsIdMap programs
cb()
(cb) =>
ActiveSession.persist.userProgramLinks.list (err, result) ->
if err
cb err
return
# TODO why is metadata stripped here?
userProgramLinks = result.map (link) -> stripMetadata(link)
cb()
(cb) =>
# Figure out userProgramId (We currently assume there can only be one)
# TODO: Refactor to something a little nicer
matchingUserProgramLinks = userProgramLinks.filter (link) ->
return link.get('userName') is global.ActiveSession.userName and
link.get('status') is 'assigned'
if matchingUserProgramLinks.size > 1
console.warn(
"More than 1 assigned programLink found",
matchingUserProgramLinks.toJS()
)
userProgramLink = matchingUserProgramLinks.get(0, null)
userProgramId = userProgramLink?.get('programId')
global.ActiveSession.programId = userProgramId
@setState (s) ->
return {
programsById
userProgramId
userProgramLinks
}
, cb
], cb
(cb) =>
clientFileProgramLinkHeaders = null
clientFileProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.clientFileProgramLinks.list (err, result) =>
if err
cb err
return
clientFileProgramLinkHeaders = result
cb()
(cb) =>
Async.map clientFileProgramLinkHeaders.toArray(), (linkHeader, cb) =>
linkId = linkHeader.get('id')
ActiveSession.persist.clientFileProgramLinks.readLatestRevisions linkId, 1, cb
, (err, results) =>
if err
cb err
return
clientFileProgramLinks = Imm.List(results)
# TODO why is metadata stripped here?
.map (linkRevs) -> stripMetadata linkRevs.get(0)
cb()
(cb) =>
@setState (s) ->
return {
clientFileProgramLinks
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
@setState {
status: 'ready'
}
@_loadSecondaryData()
# Load data not needed for default tab
_loadSecondaryData: ->
Async.parallel [
(cb) =>
# TODO Load metrics on first click to metric definition manager
metricHeaders = null
metrics = null
Async.series [
(cb) ->
ActiveSession.persist.metrics.list (err, result) =>
if err
cb err
return
metricHeaders = result
cb()
(cb) ->
Async.map metricHeaders.toArray(), (metricHeader, cb) =>
metricId = metricHeader.get('id')
ActiveSession.persist.metrics.readLatestRevisions metricId, 1, cb
, (err, results) =>
if err
cb err
return
metrics = Imm.List(results).map (metricRevs) ->
return metricRevs.first()
cb()
(cb) =>
@setState (s) ->
return {
metricsById: objectsAsIdMap metrics
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
# Done
getPageListeners: ->
return {
# Custom listener for overriding userProgram in ActiveSession
'override:userProgram': (userProgram) =>
console.log "Override userProgram to:"
if userProgram?
console.log "Program:", userProgram.toJS()
else
console.log "None (null)"
userProgramId = if userProgram? then userProgram.get('id') else null
global.ActiveSession.programId = userProgramId
@setState {userProgramId}
'create:userProgramLink createRevision:userProgramLink': (userProgramLink) =>
isForCurrentUser = userProgramLink.get('userName') is global.ActiveSession.userName
if isForCurrentUser
if userProgramLink.get('status') is 'assigned'
# Trigger override userProgram for current user
userProgram = @state.programsById.get userProgramLink.get('programId')
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
else
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', null
# Does a revision of the link already exist?
existingLink = @state.userProgramLinks.find (link) -> link.get('id') is userProgramLink.get('id')
if existingLink?
# Overwrite existing link in state
linkIndex = @state.userProgramLinks.indexOf existingLink
userProgramLinks = @state.userProgramLinks.set linkIndex, userProgramLink
else
userProgramLinks = @state.userProgramLinks.push userProgramLink
@setState {userProgramLinks}
'create:clientFile': (newFile) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.push newFile
}
'createRevision:clientFile': (newRev) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.map (cf) ->
if cf.get('id') is newRev.get('id')
return newRev
return cf
}
'create:program createRevision:program': (newObj) =>
@setState (s) ->
return {
programsById: s.programsById.set newObj.get('id'), newObj
}
'create:clientFileProgramLink': (newObj) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.push newObj
}
'createRevision:clientFileProgramLink': (newRev) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.map (obj) ->
if obj.get('id') is newRev.get('id')
return newRev
return obj
}
'create:metric createRevision:metric': (newObj) =>
@setState (s) ->
return {
metricsById: s.metricsById.set newObj.get('id'), newObj
}
}
ClientSelectionPageUi = React.createFactory React.createClass
displayName: 'ClientSelectionPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSmallHeaderSet: false
menuIsOpen: false
menuIconIsOpen: true
managerLayer: null
queryText: ''
}
componentDidMount: ->
# Fire 'loaded' event for loginPage to hide itself
global.ActiveSession.persist.eventBus.trigger 'clientSelectionPage:loaded'
# Key bindings for search results navigation
@_attachKeyBindings()
# Double-ensure that global.ActiveSession.programId lines up with @props.userProgram
global.ActiveSession.programId = if @props.userProgram then @props.userProgram.get('id') else null
render: ->
isAdmin = global.ActiveSession.isAdmin()
smallHeader = @state.queryText.length > 0 or @state.isSmallHeaderSet
return R.div({
id: 'clientSelectionPage'
className: [
'animated fadeIn'
'menuIsOpen' if @state.menuIsOpen
].join ' '
},
R.a({
id: 'expandMenuButton'
className: [
'animated fadeIn'
'menuIsOpen animated fadeInRight' if @state.menuIsOpen
].join ' '
onClick: =>
@_toggleUserMenu()
@refs.searchBox.focus() if @refs.searchBox? and @state.menuIsOpen
},
if @state.menuIsOpen
FaIcon('times', {className:'animated fadeOutRight' unless @state.menuIconIsOpen})
else
"Menu"
)
R.div({
id: 'mainContainer'
style:
width: if @state.menuIsOpen then '80%' else '100%'
},
(if @state.managerLayer?
ManagerLayer({
name: @state.managerLayer
clientFileHeaders: @props.allClientFileHeaders
programsById: @props.programsById
userProgramLinks: @props.userProgramLinks
clientFileProgramLinks: @props.clientFileProgramLinks
metricsById: @props.metricsById
menuIsOpen: @state.menuIsOpen
})
)
R.div({
id: 'main'
onClick: =>
@_toggleUserMenu() if @state.menuIsOpen
@refs.searchBox.focus() if @refs.searchBox?
},
R.header({
className: [
if smallHeader then 'small' else ''
].join ' '
},
R.div({className: 'logoContainer'},
R.img({src: Config.logoCustomerLg})
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
)
R.div({className: 'searchBoxContainer'},
noData = @props.clientFileHeaders.isEmpty()
R.div({className: 'input-group'}
(unless noData or not isAdmin
OpenDialogLink({
className: 'input-group-btn'
ref: 'openCreateClientSmall'
dialog: CreateClientFileDialog
programsById: @props.programsById
},
R.button({
className: 'btn btn-default'
title: "Add new Client File"
},
R.span({className: 'text-success'}, FaIcon('plus'))
)
)
)
R.input({
className: 'searchBox form-control'
ref: 'searchBox'
type: 'text'
autoFocus: true
disabled: noData
placeholder:
unless noData
"Search for a #{Term 'client'}'s profile..."
else
"No #{Term 'client files'} to search yet..."
onChange: @_updateQueryText
value: @state.queryText
})
R.span({className: 'input-group-btn'},
(unless noData
R.button({
className: 'btn btn-default'
onClick: @_showAll
}, "Show All")
else
OpenDialogLink({
className: 'btn btn-success'
dialog: CreateClientFileDialog
programsById: @props.programsById
disabled: not isAdmin
},
"New #{Term 'Client File'} "
FaIcon('folder-open')
)
)
)
)
)
)
R.div({
className: [
'smallHeaderLogo'
if smallHeader then 'show' else 'hidden'
].join ' '
},
R.img({
src: Config.logoCustomerLg
onClick: @_home
})
)
ClientTableWrapper({
ref: 'clientTable'
queryText: @state.queryText
clientFileHeaders: @props.clientFileHeaders
clientFileProgramLinks: @props.clientFileProgramLinks
programsById: @props.programsById
onRowClick: @_onResultSelection
displayAllPrograms: @props.displayAllPrograms
toggleAllPrograms: @props.toggleAllPrograms
})
)
)
(if @state.menuIsOpen
MainMenu({
ref: 'userMenu'
className: 'menuIsOpen animated fadeInRight'
isAdmin
programsById: @props.programsById
userProgram: @props.userProgram
managerLayer: @state.managerLayer
isSmallHeaderSet: @state.isSmallHeaderSet
updateManagerLayer: @_updateManagerLayer
})
)
)
_attachKeyBindings: ->
# Key-bindings for searchBox
$(@refs.searchBox).on 'keydown', (event) =>
# Don't need to see this unless in full search view
return if not @state.isSmallHeaderSet
switch event.which
when 40 # Down arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(1)
when 38 # Up arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(-1)
when 27 # Esc
@refs.clientTable.clearActiveIndex()
when 13 # Enter
$active = $('.activeIndex')
return unless $active.length
$active[0].click()
return false
_updateManagerLayer: (managerLayer) ->
if managerLayer is null
@setState {isSmallHeaderSet: true, queryText: '', managerLayer}
return
@setState {managerLayer}
_toggleUserMenu: ->
if @state.menuIsOpen
mainMenuNode = ReactDOM.findDOMNode(@refs.userMenu)
$(mainMenuNode).addClass('slideOutRight')
# @setState {managerLayer: null}
@setState {menuIconIsOpen: false}
setTimeout(=>
@setState {menuIsOpen: false}
, 400)
else
@setState {menuIsOpen: true}
@setState {menuIconIsOpen: true}
_updateQueryText: (event) ->
@setState {queryText: event.target.value}
if event.target.value.length > 0
@setState {isSmallHeaderSet: true}
_showAll: ->
@setState {isSmallHeaderSet: true, queryText: ''}
_home: ->
@setState {isSmallHeaderSet: false, queryText: ''}
_onResultSelection: (clientFileId) ->
@props.openClientFile(clientFileId)
ClientTableWrapper = React.createFactory React.createClass
displayName: 'ClientTableWrapper'
propTypes: {
queryText: React.PropTypes.string.isRequired
clientFileHeaders: React.PropTypes.instanceOf(Imm.List).isRequired
clientFileProgramLinks: React.PropTypes.instanceOf(Imm.List).isRequired
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
toggleAllPrograms: React.PropTypes.func.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayInactive: false
}
render: ->
queryResults = @_filterResults()
# Add in all program objects this clientFile's a member of
tableData = queryResults.map (clientFile) =>
clientFileId = clientFile.get('id')
programMemberships = null
if @props.clientFileProgramLinks?
programMemberships = @props.clientFileProgramLinks
.filter (link) =>
link.get('clientFileId') is clientFileId and link.get('status') is "enrolled"
.map (link) =>
stripMetadata @props.programsById.get(link.get('programId'))
givenNames = clientFile.getIn(['clientName', 'first'])
middleName = clientFile.getIn(['clientName', 'middle'])
if middleName then givenNames += ", #{middleName}"
return clientFile
.set('programs', programMemberships)
.set('givenNames', givenNames) # Flatten names for columns
.set('lastName', clientFile.getIn(['clientName', 'last']))
# Get inactive clientFile results for filter display
inactiveClientFiles = tableData.filter (clientFile) ->
clientFile.get('status') isnt 'active'
# Filter out inactive clientFile results by default
if not @state.displayInactive
tableData = tableData.filter (clientFile) ->
clientFile.get('status') is 'active'
# Are ANY clientFiles inactive?
hasInactiveFiles = @props.clientFileHeaders.some (clientFile) ->
clientFile.get('status') and (clientFile.get('status') isnt 'active')
return R.div({className: 'clientTableWrapper'},
# TODO: Component for multiple kinds of filters/toggles
R.div({id: 'filterSelectionContainer'}
(if hasInactiveFiles or not hasInactiveFiles
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @_toggleInactive
type: 'checkbox'
checked: @state.displayInactive
})
" Show inactive (#{inactiveClientFiles.size})",
)
)
)
(if global.ActiveSession.isAdmin() and global.ActiveSession.programId?
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @props.toggleAllPrograms
type: 'checkbox'
checked: @props.displayAllPrograms
})
" All Programs",
)
)
)
)
ClientTable({
ref: 'clientTable'
data: tableData
queryText: @props.queryText
hasProgramLinks: not @props.clientFileProgramLinks.isEmpty()
hasInactiveFiles
displayInactive: @state.displayInactive
onRowClick: @props.onRowClick
})
)
shiftActiveIndex: (modifier) -> @refs.clientTable.shiftActiveIndex(modifier)
clearActiveIndex: -> @refs.clientTable.clearActiveIndex()
_toggleInactive: ->
@setState {displayInactive: not @state.displayInactive}
_filterResults: ->
if @props.queryText.trim().length is 0
return @props.clientFileHeaders
# Split into query parts
queryParts = Imm.fromJS(@props.queryText.split(' ')).map (p) -> p.toLowerCase()
# Calculate query results
queryResults = @props.clientFileHeaders
.filter (clientFile) ->
firstName = clientFile.getIn(['clientName', 'first']).toLowerCase()
middleName = clientFile.getIn(['clientName', 'middle']).toLowerCase()
lastName = clientFile.getIn(['clientName', 'last']).toLowerCase()
recordId = clientFile.getIn(['recordId']).toLowerCase()
return queryParts
.every (part) ->
return firstName.includes(part) or
middleName.includes(part) or
lastName.includes(part) or
recordId.includes(part)
return queryResults
ClientTable = React.createFactory React.createClass
displayName: 'ClientTable'
propTypes: {
queryText: React.PropTypes.string.isRequired
data: React.PropTypes.instanceOf(Imm.List).isRequired
hasProgramLinks: React.PropTypes.bool.isRequired
hasInactiveFiles: React.PropTypes.bool.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
activeIndex: null
}
render: ->
return R.div({className: 'responsiveTable'},
BootstrapTable({
data: @props.data.toJS()
keyField: 'id'
bordered: false
options: {
onRowClick: ({id}) => @props.onRowClick(id)
noDataText: (if @props.queryText
"No #{Term 'client files'} matching \"#{@props.queryText}\"."
else
"No #{Term 'client files'} found."
)
defaultSortName: 'lastName'
defaultSortOrder: 'asc'
}
trClassName: (row, index) => [
'clientRow'
'activeIndex' if index is @state.activeIndex
'inactive' unless row.status is 'active'
].join ' '
},
TableHeaderColumn({
dataField: 'programs'
dataFormat: (programs) ->
return null unless programs
ProgramBubbles({programs: Imm.fromJS(programs)})
className: 'leftPadding'
columnClassName: 'leftPadding'
width: '150px'
hidden: not @props.hasProgramLinks
})
TableHeaderColumn({
dataField: '<NAME>'
dataSort: true
className: 'leftPadding' if not @props.hasProgramLinks
columnClassName: 'leftPadding' if not @props.hasProgramLinks
}, "Last Name")
TableHeaderColumn({
dataField: 'givenNames'
dataSort: true
className: 'visibleColumn'
columnClassName: 'visibleColumn'
}, "Given Names")
TableHeaderColumn({
dataField: 'recordId'
dataSort: true
className: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
columnClassName: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
headerAlign: 'right'
dataAlign: 'right'
hidden: not Config.clientFileRecordId.isEnabled
}, Config.clientFileRecordId.label)
TableHeaderColumn({
dataField: 'status'
dataSort: true
headerAlign: 'right'
dataAlign: 'right'
className: 'rightPadding' if @props.displayInactive
columnClassName: 'rightPadding' if @props.displayInactive
hidden: not @props.displayInactive
}, "Status")
)
)
shiftActiveIndex: (modifier) ->
if @state.activeIndex is null
activeIndex = 0
@setState {activeIndex}
return
activeIndex = @state.activeIndex + modifier
numberClientRows = @props.data.size
if activeIndex < 0
activeIndex = numberClientRows - 1
else if activeIndex > (numberClientRows - 1)
activeIndex = 0
@setState {activeIndex}
clearActiveIndex: -> @setState {activeIndex: null}
return ClientSelectionPage
module.exports = {load}
| true | # Copyright (c) PI:NAME:<NAME>END_PI. All rights reserved.
# This source code is subject to the terms of the Mozilla Public License, v. 2.0
# that can be found in the LICENSE file or at: http://mozilla.org/MPL/2.0
_ = require 'underscore'
Imm = require 'immutable'
Async = require 'async'
Config = require './config'
Term = require './term'
Persist = require './persist'
load = (win) ->
$ = win.jQuery
Bootbox = win.bootbox
React = win.React
ReactDOM = win.ReactDOM
R = React.DOM
# TODO: Refactor to single require
{BootstrapTable, TableHeaderColumn} = win.ReactBootstrapTable
BootstrapTable = React.createFactory BootstrapTable
TableHeaderColumn = React.createFactory TableHeaderColumn
MainMenu = require('./mainMenu').load(win)
OpenDialogLink = require('./openDialogLink').load(win)
ProgramBubbles = require('./programBubbles').load(win)
ManagerLayer = require('./managerLayer').load(win)
CreateClientFileDialog = require('./createClientFileDialog').load(win)
CrashHandler = require('./crashHandler').load(win)
{FaIcon, openWindow, renderName, stripMetadata, objectsAsIdMap} = require('./utils').load(win)
ClientSelectionPage = React.createFactory React.createClass
displayName: 'ClientSelectionPage'
getInitialState: ->
return {
status: 'init'
loadingFile: false
clientFileHeaders: null
metricsById: null
programsById: null
userProgramId: null
userProgramLinks: Imm.List()
clientFileProgramLinks: null
displayAllPrograms: false
}
init: ->
windowTitle = "#{Config.productName} (#{global.ActiveSession.userName})"
if Config.logoSubtitle
windowTitle = "#{Config.logoSubtitle} - #{windowTitle}"
@props.setWindowTitle(windowTitle)
@_loadInitialData()
deinit: (cb=(->)) ->
# Nothing to deinit
cb()
suggestClose: ->
@props.closeWindow()
nw.App.closeAllWindows()
render: ->
unless @state.status is 'ready'
return null
userProgram = @_getUserProgram()
isAdmin = global.ActiveSession.isAdmin()
# For regular users, we filter out clientFiles that
# and don't match the user's assigned program
clientFileHeaders = if userProgram? and not @state.displayAllPrograms
@state.clientFileHeaders.filter (clientFile) =>
clientFileId = clientFile.get('id')
@state.clientFileProgramLinks.some (link) =>
link.get('clientFileId') is clientFileId and
link.get('programId') is @state.userProgramId and
link.get('status') is 'enrolled'
else
@state.clientFileHeaders
return ClientSelectionPageUi {
openClientFile: _.debounce @_openClientFile, 1000, true
clientFileHeaders
allClientFileHeaders: @state.clientFileHeaders
clientFileProgramLinks: @state.clientFileProgramLinks
programsById: @state.programsById
userProgram
userProgramLinks: @state.userProgramLinks
metricsById: @state.metricsById
displayAllPrograms: @state.displayAllPrograms
toggleAllPrograms: @_toggleAllPrograms
}
_toggleAllPrograms: ->
@setState {displayAllPrograms: not @state.displayAllPrograms}
_getUserProgram: ->
if @state.userProgramId?
return @state.programsById.get(@state.userProgramId)
return null
_openClientFile: (clientFileId) ->
appWindows = chrome.app.window.getAll()
# skip if no client files open
if appWindows.length > 2
clientName = ''
ActiveSession.persist.clientFiles.readLatestRevisions clientFileId, 1, (err, revisions) =>
if err
# fail silently, let user retry
return
clientFile = stripMetadata revisions.get(0)
clientName = renderName clientFile.get('clientName')
clientFileOpen = false
appWindows.forEach (appWindow) ->
winTitle = nw.Window.get(appWindow.contentWindow).window.document.title
if winTitle.includes(clientName)
# already open, focus
clientFileOpen = true
nw.Window.get(appWindow.contentWindow).focus()
return
if clientFileOpen is false
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
clientFileWindow.on 'close', =>
clientFileWindow = null
else
openWindow {page: 'clientFile', clientFileId}, offset:true, (clientFileWindow) =>
# prevent window from closing before its ready
clientFileWindow.on 'close', =>
clientFileWindow = null
_loadInitialData: ->
Async.parallel [
(cb) =>
ActiveSession.persist.clientFiles.list (err, result) =>
if err
cb err
return
@setState (s) ->
return {
clientFileHeaders: result
}
, cb
(cb) =>
programHeaders = null
programs = null
programsById = null
userProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.programs.list (err, result) =>
if err
cb err
return
programHeaders = result
cb()
(cb) =>
Async.map programHeaders.toArray(), (programHeader, cb) =>
progId = programHeader.get('id')
ActiveSession.persist.programs.readLatestRevisions progId, 1, cb
, (err, results) =>
if err
cb err
return
programs = Imm.List(results)
.map (programRevs) -> programRevs.get(0)
programsById = objectsAsIdMap programs
cb()
(cb) =>
ActiveSession.persist.userProgramLinks.list (err, result) ->
if err
cb err
return
# TODO why is metadata stripped here?
userProgramLinks = result.map (link) -> stripMetadata(link)
cb()
(cb) =>
# Figure out userProgramId (We currently assume there can only be one)
# TODO: Refactor to something a little nicer
matchingUserProgramLinks = userProgramLinks.filter (link) ->
return link.get('userName') is global.ActiveSession.userName and
link.get('status') is 'assigned'
if matchingUserProgramLinks.size > 1
console.warn(
"More than 1 assigned programLink found",
matchingUserProgramLinks.toJS()
)
userProgramLink = matchingUserProgramLinks.get(0, null)
userProgramId = userProgramLink?.get('programId')
global.ActiveSession.programId = userProgramId
@setState (s) ->
return {
programsById
userProgramId
userProgramLinks
}
, cb
], cb
(cb) =>
clientFileProgramLinkHeaders = null
clientFileProgramLinks = null
Async.series [
(cb) =>
ActiveSession.persist.clientFileProgramLinks.list (err, result) =>
if err
cb err
return
clientFileProgramLinkHeaders = result
cb()
(cb) =>
Async.map clientFileProgramLinkHeaders.toArray(), (linkHeader, cb) =>
linkId = linkHeader.get('id')
ActiveSession.persist.clientFileProgramLinks.readLatestRevisions linkId, 1, cb
, (err, results) =>
if err
cb err
return
clientFileProgramLinks = Imm.List(results)
# TODO why is metadata stripped here?
.map (linkRevs) -> stripMetadata linkRevs.get(0)
cb()
(cb) =>
@setState (s) ->
return {
clientFileProgramLinks
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
@setState {
status: 'ready'
}
@_loadSecondaryData()
# Load data not needed for default tab
_loadSecondaryData: ->
Async.parallel [
(cb) =>
# TODO Load metrics on first click to metric definition manager
metricHeaders = null
metrics = null
Async.series [
(cb) ->
ActiveSession.persist.metrics.list (err, result) =>
if err
cb err
return
metricHeaders = result
cb()
(cb) ->
Async.map metricHeaders.toArray(), (metricHeader, cb) =>
metricId = metricHeader.get('id')
ActiveSession.persist.metrics.readLatestRevisions metricId, 1, cb
, (err, results) =>
if err
cb err
return
metrics = Imm.List(results).map (metricRevs) ->
return metricRevs.first()
cb()
(cb) =>
@setState (s) ->
return {
metricsById: objectsAsIdMap metrics
}
, cb
], cb
], (err) =>
if err
if err instanceof Persist.IOError
Bootbox.alert "Please check your network connection and try again."
return
CrashHandler.handle err
return
# Done
getPageListeners: ->
return {
# Custom listener for overriding userProgram in ActiveSession
'override:userProgram': (userProgram) =>
console.log "Override userProgram to:"
if userProgram?
console.log "Program:", userProgram.toJS()
else
console.log "None (null)"
userProgramId = if userProgram? then userProgram.get('id') else null
global.ActiveSession.programId = userProgramId
@setState {userProgramId}
'create:userProgramLink createRevision:userProgramLink': (userProgramLink) =>
isForCurrentUser = userProgramLink.get('userName') is global.ActiveSession.userName
if isForCurrentUser
if userProgramLink.get('status') is 'assigned'
# Trigger override userProgram for current user
userProgram = @state.programsById.get userProgramLink.get('programId')
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', userProgram
else
global.ActiveSession.persist.eventBus.trigger 'override:userProgram', null
# Does a revision of the link already exist?
existingLink = @state.userProgramLinks.find (link) -> link.get('id') is userProgramLink.get('id')
if existingLink?
# Overwrite existing link in state
linkIndex = @state.userProgramLinks.indexOf existingLink
userProgramLinks = @state.userProgramLinks.set linkIndex, userProgramLink
else
userProgramLinks = @state.userProgramLinks.push userProgramLink
@setState {userProgramLinks}
'create:clientFile': (newFile) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.push newFile
}
'createRevision:clientFile': (newRev) =>
@setState (s) ->
return {
clientFileHeaders: s.clientFileHeaders.map (cf) ->
if cf.get('id') is newRev.get('id')
return newRev
return cf
}
'create:program createRevision:program': (newObj) =>
@setState (s) ->
return {
programsById: s.programsById.set newObj.get('id'), newObj
}
'create:clientFileProgramLink': (newObj) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.push newObj
}
'createRevision:clientFileProgramLink': (newRev) =>
@setState (s) ->
return {
clientFileProgramLinks: s.clientFileProgramLinks.map (obj) ->
if obj.get('id') is newRev.get('id')
return newRev
return obj
}
'create:metric createRevision:metric': (newObj) =>
@setState (s) ->
return {
metricsById: s.metricsById.set newObj.get('id'), newObj
}
}
ClientSelectionPageUi = React.createFactory React.createClass
displayName: 'ClientSelectionPageUi'
mixins: [React.addons.PureRenderMixin]
getInitialState: ->
return {
isSmallHeaderSet: false
menuIsOpen: false
menuIconIsOpen: true
managerLayer: null
queryText: ''
}
componentDidMount: ->
# Fire 'loaded' event for loginPage to hide itself
global.ActiveSession.persist.eventBus.trigger 'clientSelectionPage:loaded'
# Key bindings for search results navigation
@_attachKeyBindings()
# Double-ensure that global.ActiveSession.programId lines up with @props.userProgram
global.ActiveSession.programId = if @props.userProgram then @props.userProgram.get('id') else null
render: ->
isAdmin = global.ActiveSession.isAdmin()
smallHeader = @state.queryText.length > 0 or @state.isSmallHeaderSet
return R.div({
id: 'clientSelectionPage'
className: [
'animated fadeIn'
'menuIsOpen' if @state.menuIsOpen
].join ' '
},
R.a({
id: 'expandMenuButton'
className: [
'animated fadeIn'
'menuIsOpen animated fadeInRight' if @state.menuIsOpen
].join ' '
onClick: =>
@_toggleUserMenu()
@refs.searchBox.focus() if @refs.searchBox? and @state.menuIsOpen
},
if @state.menuIsOpen
FaIcon('times', {className:'animated fadeOutRight' unless @state.menuIconIsOpen})
else
"Menu"
)
R.div({
id: 'mainContainer'
style:
width: if @state.menuIsOpen then '80%' else '100%'
},
(if @state.managerLayer?
ManagerLayer({
name: @state.managerLayer
clientFileHeaders: @props.allClientFileHeaders
programsById: @props.programsById
userProgramLinks: @props.userProgramLinks
clientFileProgramLinks: @props.clientFileProgramLinks
metricsById: @props.metricsById
menuIsOpen: @state.menuIsOpen
})
)
R.div({
id: 'main'
onClick: =>
@_toggleUserMenu() if @state.menuIsOpen
@refs.searchBox.focus() if @refs.searchBox?
},
R.header({
className: [
if smallHeader then 'small' else ''
].join ' '
},
R.div({className: 'logoContainer'},
R.img({src: Config.logoCustomerLg})
R.div({className: 'subtitleContainer'},
R.div({
className: 'subtitleText'
style: {color: Config.logoSubtitleColor}
},
Config.logoSubtitle
)
(if not Config.logoSubtitle
R.div({className: 'versionNumber'},
"v" + nw.App.manifest.version
)
)
)
)
R.div({className: 'searchBoxContainer'},
noData = @props.clientFileHeaders.isEmpty()
R.div({className: 'input-group'}
(unless noData or not isAdmin
OpenDialogLink({
className: 'input-group-btn'
ref: 'openCreateClientSmall'
dialog: CreateClientFileDialog
programsById: @props.programsById
},
R.button({
className: 'btn btn-default'
title: "Add new Client File"
},
R.span({className: 'text-success'}, FaIcon('plus'))
)
)
)
R.input({
className: 'searchBox form-control'
ref: 'searchBox'
type: 'text'
autoFocus: true
disabled: noData
placeholder:
unless noData
"Search for a #{Term 'client'}'s profile..."
else
"No #{Term 'client files'} to search yet..."
onChange: @_updateQueryText
value: @state.queryText
})
R.span({className: 'input-group-btn'},
(unless noData
R.button({
className: 'btn btn-default'
onClick: @_showAll
}, "Show All")
else
OpenDialogLink({
className: 'btn btn-success'
dialog: CreateClientFileDialog
programsById: @props.programsById
disabled: not isAdmin
},
"New #{Term 'Client File'} "
FaIcon('folder-open')
)
)
)
)
)
)
R.div({
className: [
'smallHeaderLogo'
if smallHeader then 'show' else 'hidden'
].join ' '
},
R.img({
src: Config.logoCustomerLg
onClick: @_home
})
)
ClientTableWrapper({
ref: 'clientTable'
queryText: @state.queryText
clientFileHeaders: @props.clientFileHeaders
clientFileProgramLinks: @props.clientFileProgramLinks
programsById: @props.programsById
onRowClick: @_onResultSelection
displayAllPrograms: @props.displayAllPrograms
toggleAllPrograms: @props.toggleAllPrograms
})
)
)
(if @state.menuIsOpen
MainMenu({
ref: 'userMenu'
className: 'menuIsOpen animated fadeInRight'
isAdmin
programsById: @props.programsById
userProgram: @props.userProgram
managerLayer: @state.managerLayer
isSmallHeaderSet: @state.isSmallHeaderSet
updateManagerLayer: @_updateManagerLayer
})
)
)
_attachKeyBindings: ->
# Key-bindings for searchBox
$(@refs.searchBox).on 'keydown', (event) =>
# Don't need to see this unless in full search view
return if not @state.isSmallHeaderSet
switch event.which
when 40 # Down arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(1)
when 38 # Up arrow
event.preventDefault()
@refs.clientTable.shiftActiveIndex(-1)
when 27 # Esc
@refs.clientTable.clearActiveIndex()
when 13 # Enter
$active = $('.activeIndex')
return unless $active.length
$active[0].click()
return false
_updateManagerLayer: (managerLayer) ->
if managerLayer is null
@setState {isSmallHeaderSet: true, queryText: '', managerLayer}
return
@setState {managerLayer}
_toggleUserMenu: ->
if @state.menuIsOpen
mainMenuNode = ReactDOM.findDOMNode(@refs.userMenu)
$(mainMenuNode).addClass('slideOutRight')
# @setState {managerLayer: null}
@setState {menuIconIsOpen: false}
setTimeout(=>
@setState {menuIsOpen: false}
, 400)
else
@setState {menuIsOpen: true}
@setState {menuIconIsOpen: true}
_updateQueryText: (event) ->
@setState {queryText: event.target.value}
if event.target.value.length > 0
@setState {isSmallHeaderSet: true}
_showAll: ->
@setState {isSmallHeaderSet: true, queryText: ''}
_home: ->
@setState {isSmallHeaderSet: false, queryText: ''}
_onResultSelection: (clientFileId) ->
@props.openClientFile(clientFileId)
ClientTableWrapper = React.createFactory React.createClass
displayName: 'ClientTableWrapper'
propTypes: {
queryText: React.PropTypes.string.isRequired
clientFileHeaders: React.PropTypes.instanceOf(Imm.List).isRequired
clientFileProgramLinks: React.PropTypes.instanceOf(Imm.List).isRequired
programsById: React.PropTypes.instanceOf(Imm.Map).isRequired
toggleAllPrograms: React.PropTypes.func.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
displayInactive: false
}
render: ->
queryResults = @_filterResults()
# Add in all program objects this clientFile's a member of
tableData = queryResults.map (clientFile) =>
clientFileId = clientFile.get('id')
programMemberships = null
if @props.clientFileProgramLinks?
programMemberships = @props.clientFileProgramLinks
.filter (link) =>
link.get('clientFileId') is clientFileId and link.get('status') is "enrolled"
.map (link) =>
stripMetadata @props.programsById.get(link.get('programId'))
givenNames = clientFile.getIn(['clientName', 'first'])
middleName = clientFile.getIn(['clientName', 'middle'])
if middleName then givenNames += ", #{middleName}"
return clientFile
.set('programs', programMemberships)
.set('givenNames', givenNames) # Flatten names for columns
.set('lastName', clientFile.getIn(['clientName', 'last']))
# Get inactive clientFile results for filter display
inactiveClientFiles = tableData.filter (clientFile) ->
clientFile.get('status') isnt 'active'
# Filter out inactive clientFile results by default
if not @state.displayInactive
tableData = tableData.filter (clientFile) ->
clientFile.get('status') is 'active'
# Are ANY clientFiles inactive?
hasInactiveFiles = @props.clientFileHeaders.some (clientFile) ->
clientFile.get('status') and (clientFile.get('status') isnt 'active')
return R.div({className: 'clientTableWrapper'},
# TODO: Component for multiple kinds of filters/toggles
R.div({id: 'filterSelectionContainer'}
(if hasInactiveFiles or not hasInactiveFiles
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @_toggleInactive
type: 'checkbox'
checked: @state.displayInactive
})
" Show inactive (#{inactiveClientFiles.size})",
)
)
)
(if global.ActiveSession.isAdmin() and global.ActiveSession.programId?
R.div({className: "toggle animated fadeIn"},
R.label({}
R.input({
onChange: @props.toggleAllPrograms
type: 'checkbox'
checked: @props.displayAllPrograms
})
" All Programs",
)
)
)
)
ClientTable({
ref: 'clientTable'
data: tableData
queryText: @props.queryText
hasProgramLinks: not @props.clientFileProgramLinks.isEmpty()
hasInactiveFiles
displayInactive: @state.displayInactive
onRowClick: @props.onRowClick
})
)
shiftActiveIndex: (modifier) -> @refs.clientTable.shiftActiveIndex(modifier)
clearActiveIndex: -> @refs.clientTable.clearActiveIndex()
_toggleInactive: ->
@setState {displayInactive: not @state.displayInactive}
_filterResults: ->
if @props.queryText.trim().length is 0
return @props.clientFileHeaders
# Split into query parts
queryParts = Imm.fromJS(@props.queryText.split(' ')).map (p) -> p.toLowerCase()
# Calculate query results
queryResults = @props.clientFileHeaders
.filter (clientFile) ->
firstName = clientFile.getIn(['clientName', 'first']).toLowerCase()
middleName = clientFile.getIn(['clientName', 'middle']).toLowerCase()
lastName = clientFile.getIn(['clientName', 'last']).toLowerCase()
recordId = clientFile.getIn(['recordId']).toLowerCase()
return queryParts
.every (part) ->
return firstName.includes(part) or
middleName.includes(part) or
lastName.includes(part) or
recordId.includes(part)
return queryResults
ClientTable = React.createFactory React.createClass
displayName: 'ClientTable'
propTypes: {
queryText: React.PropTypes.string.isRequired
data: React.PropTypes.instanceOf(Imm.List).isRequired
hasProgramLinks: React.PropTypes.bool.isRequired
hasInactiveFiles: React.PropTypes.bool.isRequired
onRowClick: React.PropTypes.func.isRequired
}
getInitialState: -> {
activeIndex: null
}
render: ->
return R.div({className: 'responsiveTable'},
BootstrapTable({
data: @props.data.toJS()
keyField: 'id'
bordered: false
options: {
onRowClick: ({id}) => @props.onRowClick(id)
noDataText: (if @props.queryText
"No #{Term 'client files'} matching \"#{@props.queryText}\"."
else
"No #{Term 'client files'} found."
)
defaultSortName: 'lastName'
defaultSortOrder: 'asc'
}
trClassName: (row, index) => [
'clientRow'
'activeIndex' if index is @state.activeIndex
'inactive' unless row.status is 'active'
].join ' '
},
TableHeaderColumn({
dataField: 'programs'
dataFormat: (programs) ->
return null unless programs
ProgramBubbles({programs: Imm.fromJS(programs)})
className: 'leftPadding'
columnClassName: 'leftPadding'
width: '150px'
hidden: not @props.hasProgramLinks
})
TableHeaderColumn({
dataField: 'PI:NAME:<NAME>END_PI'
dataSort: true
className: 'leftPadding' if not @props.hasProgramLinks
columnClassName: 'leftPadding' if not @props.hasProgramLinks
}, "Last Name")
TableHeaderColumn({
dataField: 'givenNames'
dataSort: true
className: 'visibleColumn'
columnClassName: 'visibleColumn'
}, "Given Names")
TableHeaderColumn({
dataField: 'recordId'
dataSort: true
className: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
columnClassName: 'rightPadding' if Config.clientFileRecordId.isEnabled and not @props.displayInactive
headerAlign: 'right'
dataAlign: 'right'
hidden: not Config.clientFileRecordId.isEnabled
}, Config.clientFileRecordId.label)
TableHeaderColumn({
dataField: 'status'
dataSort: true
headerAlign: 'right'
dataAlign: 'right'
className: 'rightPadding' if @props.displayInactive
columnClassName: 'rightPadding' if @props.displayInactive
hidden: not @props.displayInactive
}, "Status")
)
)
shiftActiveIndex: (modifier) ->
if @state.activeIndex is null
activeIndex = 0
@setState {activeIndex}
return
activeIndex = @state.activeIndex + modifier
numberClientRows = @props.data.size
if activeIndex < 0
activeIndex = numberClientRows - 1
else if activeIndex > (numberClientRows - 1)
activeIndex = 0
@setState {activeIndex}
clearActiveIndex: -> @setState {activeIndex: null}
return ClientSelectionPage
module.exports = {load}
|
[
{
"context": "configOverwrite:\n # See https://github.com/jitsi/jitsi-meet/blob/master/config.js\n prejoinP",
"end": 1758,
"score": 0.9996046423912048,
"start": 1753,
"tag": "USERNAME",
"value": "jitsi"
},
{
"context": "ct: room.title\n defaultRemoteDisplayName: ... | client/TabJitsi.coffee | notaplanet/comingle | 37 | import React, {useEffect, useRef, useState} from 'react'
import {useTracker} from 'meteor/react-meteor-data'
import useScript from 'react-script-hook'
import {Alert, Button, Card} from 'react-bootstrap'
import {Loading} from './Loading'
import {useName} from './Name'
import {getDark} from './Settings'
import {Tabs} from '/lib/tabs'
## Remember the state of the last Jitsi call, except when there are no calls
## and resetJitsiStatusAfter seconds elapse; then reset to default state.
resetJitsiStatusAfter = 30 # seconds
defaultJitsiStatus = ->
joined: false
audioMuted: false
videoMuted: false
lastJitsiStatus = defaultJitsiStatus()
timeoutJitsiStatus = null
numJitsi = 0 # number of joined Jitsi calls
parseJitsiUrl = (url) ->
return {} unless url?
parsed = new URL url
host = parsed.host
roomName = parsed.pathname
roomName = roomName[1..] if roomName[0] == '/'
parsed.pathname = '/external_api.js'
script = parsed.toString()
{host, roomName, script}
export TabJitsi = React.memo ({tabId, room}) ->
tab = useTracker ->
Tabs.findOne tabId
, [tabId]
{host, roomName, script} = parseJitsiUrl tab?.url
[loading, error] = useScript
src: script
checkForExisting: true
ref = useRef() # div container for Jitsi iframe
[joined, setJoined] = useState lastJitsiStatus.joined # joined call?
[api, setApi] = useState() # JitsiMeetExternalAPI object
name = useName()
## Jitsi API
useEffect ->
return unless tab?
return if loading or error
return unless joined
Jitsi = window.exports?.JitsiMeetExternalAPI ? window.JitsiMeetExternalAPI
setApi jitsi = new Jitsi host,
parentNode: ref.current
roomName: roomName
configOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/config.js
prejoinPageEnabled: false
subject: room.title
defaultRemoteDisplayName: 'Fellow Comingler'
startWithAudioMuted: lastJitsiStatus.audioMuted
startWithVideoMuted: lastJitsiStatus.videoMuted
interfaceConfigOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/interface_config.js
DEFAULT_BACKGROUND:
if getDark() then '#111' else '#474747'
DISABLE_VIDEO_BACKGROUND: true
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'closedcaptions', 'desktop',
'embedmeeting', 'fullscreen', 'fodeviceselection', 'hangup',
'profile', 'recording', 'livestreaming', 'etherpad',
'settings', 'videoquality', 'filmstrip', 'feedback', 'stats',
'shortcuts', 'tileview', 'videobackgroundblur', 'download', 'help',
'mute-everyone'
] # omit 'chat', 'security', 'invite', 'raisehand', 'sharedvideo' [YouTube]
SETTINGS_SECTIONS: [
'devices', 'language', 'moderator'
] # omit 'profile' and 'calendar'
DISPLAY_WELCOME_PAGE_CONTENT: false
SHOW_CHROME_EXTENSION_BANNER: false
HIDE_INVITE_MORE_HEADER: true
RECENT_LIST_ENABLED: false
SHOW_PROMOTIONAL_CLOSE_PAGE: false # if supported by server
userInfo:
displayName: name
jitsi.addListener 'audioMuteStatusChanged', ({muted}) ->
lastJitsiStatus.audioMuted = muted
jitsi.addListener 'videoMuteStatusChanged', ({muted}) ->
lastJitsiStatus.videoMuted = muted
jitsi.addListener 'readyToClose', -> # hangup call
setJoined false
## Before hanging up, Jitsi mutes the video and emits an event, so we no
## longer know the correct Jitsi status. So reset to default upon hangup.
lastJitsiStatus = defaultJitsiStatus()
-> # cleanup
jitsi?.dispose()
, [tab?.url, loading, error, joined]
## Keep settings up-to-date
useEffect ->
api?.executeCommand 'displayName', name
undefined
, [name]
useEffect ->
api?.executeCommand 'subject', room.title
undefined
, [room.title]
## Maintain number of joined Jitsi calls, and reset state if zero and timeout.
useEffect ->
numJitsi++ if joined
lastJitsiStatus.joined = (numJitsi > 0)
if timeoutJitsiStatus?
clearTimeout timeoutJitsiStatus
timeoutJitsiStatus = null
->
numJitsi-- if joined
if numJitsi == 0 and resetJitsiStatusAfter?
timeoutJitsiStatus = setTimeout ->
timeoutJitsiStatus = null
#lastJitsiStatus = defaultJitsiStatus()
lastJitsiStatus.joined = defaultJitsiStatus().joined
, resetJitsiStatusAfter * 1000
, [joined]
return null unless tab
<div ref={ref}>
{if error
<Alert variant="danger">
Failed to load <a href={script} target="_blank" rel="noopener">Jitsi external API script</a>.
Is <a href={'https://' + host} target="_blank" rel="noopener">{host}</a> a valid Jitsi server?
</Alert>
else if not joined
<Card>
<Card.Body>
<Card.Title>Jitsi Meeting</Card.Title>
<p>
<b>Server:</b> <a href={'https://' + host} target="_blank" rel="noopener"><code>{host}</code></a><br/>
<b>Room ID:</b> <code>{roomName}</code>
</p>
<Button block onClick={-> setJoined true}>Join Call</Button>
<p>When joining, you may need to grant access to your microphone and/or camera. If you want to try again, select the “Reload Tab” button at the top of this tab.</p>
<p>If you hang up on the call and receive an ad, click the X button (at the top right of the ad) to fully leave the call, and prevent Comingle from automatically joining future Jitsi calls.</p>
</Card.Body>
</Card>
else if loading
<Loading/>
}
</div>
TabJitsi.displayName = 'TabJitsi'
| 7366 | import React, {useEffect, useRef, useState} from 'react'
import {useTracker} from 'meteor/react-meteor-data'
import useScript from 'react-script-hook'
import {Alert, Button, Card} from 'react-bootstrap'
import {Loading} from './Loading'
import {useName} from './Name'
import {getDark} from './Settings'
import {Tabs} from '/lib/tabs'
## Remember the state of the last Jitsi call, except when there are no calls
## and resetJitsiStatusAfter seconds elapse; then reset to default state.
resetJitsiStatusAfter = 30 # seconds
defaultJitsiStatus = ->
joined: false
audioMuted: false
videoMuted: false
lastJitsiStatus = defaultJitsiStatus()
timeoutJitsiStatus = null
numJitsi = 0 # number of joined Jitsi calls
parseJitsiUrl = (url) ->
return {} unless url?
parsed = new URL url
host = parsed.host
roomName = parsed.pathname
roomName = roomName[1..] if roomName[0] == '/'
parsed.pathname = '/external_api.js'
script = parsed.toString()
{host, roomName, script}
export TabJitsi = React.memo ({tabId, room}) ->
tab = useTracker ->
Tabs.findOne tabId
, [tabId]
{host, roomName, script} = parseJitsiUrl tab?.url
[loading, error] = useScript
src: script
checkForExisting: true
ref = useRef() # div container for Jitsi iframe
[joined, setJoined] = useState lastJitsiStatus.joined # joined call?
[api, setApi] = useState() # JitsiMeetExternalAPI object
name = useName()
## Jitsi API
useEffect ->
return unless tab?
return if loading or error
return unless joined
Jitsi = window.exports?.JitsiMeetExternalAPI ? window.JitsiMeetExternalAPI
setApi jitsi = new Jitsi host,
parentNode: ref.current
roomName: roomName
configOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/config.js
prejoinPageEnabled: false
subject: room.title
defaultRemoteDisplayName: '<NAME>'
startWithAudioMuted: lastJitsiStatus.audioMuted
startWithVideoMuted: lastJitsiStatus.videoMuted
interfaceConfigOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/interface_config.js
DEFAULT_BACKGROUND:
if getDark() then '#111' else '#474747'
DISABLE_VIDEO_BACKGROUND: true
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'closedcaptions', 'desktop',
'embedmeeting', 'fullscreen', 'fodeviceselection', 'hangup',
'profile', 'recording', 'livestreaming', 'etherpad',
'settings', 'videoquality', 'filmstrip', 'feedback', 'stats',
'shortcuts', 'tileview', 'videobackgroundblur', 'download', 'help',
'mute-everyone'
] # omit 'chat', 'security', 'invite', 'raisehand', 'sharedvideo' [YouTube]
SETTINGS_SECTIONS: [
'devices', 'language', 'moderator'
] # omit 'profile' and 'calendar'
DISPLAY_WELCOME_PAGE_CONTENT: false
SHOW_CHROME_EXTENSION_BANNER: false
HIDE_INVITE_MORE_HEADER: true
RECENT_LIST_ENABLED: false
SHOW_PROMOTIONAL_CLOSE_PAGE: false # if supported by server
userInfo:
displayName: <NAME>
jitsi.addListener 'audioMuteStatusChanged', ({muted}) ->
lastJitsiStatus.audioMuted = muted
jitsi.addListener 'videoMuteStatusChanged', ({muted}) ->
lastJitsiStatus.videoMuted = muted
jitsi.addListener 'readyToClose', -> # hangup call
setJoined false
## Before hanging up, Jitsi mutes the video and emits an event, so we no
## longer know the correct Jitsi status. So reset to default upon hangup.
lastJitsiStatus = defaultJitsiStatus()
-> # cleanup
jitsi?.dispose()
, [tab?.url, loading, error, joined]
## Keep settings up-to-date
useEffect ->
api?.executeCommand 'displayName', name
undefined
, [name]
useEffect ->
api?.executeCommand 'subject', room.title
undefined
, [room.title]
## Maintain number of joined Jitsi calls, and reset state if zero and timeout.
useEffect ->
numJitsi++ if joined
lastJitsiStatus.joined = (numJitsi > 0)
if timeoutJitsiStatus?
clearTimeout timeoutJitsiStatus
timeoutJitsiStatus = null
->
numJitsi-- if joined
if numJitsi == 0 and resetJitsiStatusAfter?
timeoutJitsiStatus = setTimeout ->
timeoutJitsiStatus = null
#lastJitsiStatus = defaultJitsiStatus()
lastJitsiStatus.joined = defaultJitsiStatus().joined
, resetJitsiStatusAfter * 1000
, [joined]
return null unless tab
<div ref={ref}>
{if error
<Alert variant="danger">
Failed to load <a href={script} target="_blank" rel="noopener">Jitsi external API script</a>.
Is <a href={'https://' + host} target="_blank" rel="noopener">{host}</a> a valid Jitsi server?
</Alert>
else if not joined
<Card>
<Card.Body>
<Card.Title>Jitsi Meeting</Card.Title>
<p>
<b>Server:</b> <a href={'https://' + host} target="_blank" rel="noopener"><code>{host}</code></a><br/>
<b>Room ID:</b> <code>{roomName}</code>
</p>
<Button block onClick={-> setJoined true}>Join Call</Button>
<p>When joining, you may need to grant access to your microphone and/or camera. If you want to try again, select the “Reload Tab” button at the top of this tab.</p>
<p>If you hang up on the call and receive an ad, click the X button (at the top right of the ad) to fully leave the call, and prevent Comingle from automatically joining future Jitsi calls.</p>
</Card.Body>
</Card>
else if loading
<Loading/>
}
</div>
TabJitsi.displayName = 'TabJitsi'
| true | import React, {useEffect, useRef, useState} from 'react'
import {useTracker} from 'meteor/react-meteor-data'
import useScript from 'react-script-hook'
import {Alert, Button, Card} from 'react-bootstrap'
import {Loading} from './Loading'
import {useName} from './Name'
import {getDark} from './Settings'
import {Tabs} from '/lib/tabs'
## Remember the state of the last Jitsi call, except when there are no calls
## and resetJitsiStatusAfter seconds elapse; then reset to default state.
resetJitsiStatusAfter = 30 # seconds
defaultJitsiStatus = ->
joined: false
audioMuted: false
videoMuted: false
lastJitsiStatus = defaultJitsiStatus()
timeoutJitsiStatus = null
numJitsi = 0 # number of joined Jitsi calls
parseJitsiUrl = (url) ->
return {} unless url?
parsed = new URL url
host = parsed.host
roomName = parsed.pathname
roomName = roomName[1..] if roomName[0] == '/'
parsed.pathname = '/external_api.js'
script = parsed.toString()
{host, roomName, script}
export TabJitsi = React.memo ({tabId, room}) ->
tab = useTracker ->
Tabs.findOne tabId
, [tabId]
{host, roomName, script} = parseJitsiUrl tab?.url
[loading, error] = useScript
src: script
checkForExisting: true
ref = useRef() # div container for Jitsi iframe
[joined, setJoined] = useState lastJitsiStatus.joined # joined call?
[api, setApi] = useState() # JitsiMeetExternalAPI object
name = useName()
## Jitsi API
useEffect ->
return unless tab?
return if loading or error
return unless joined
Jitsi = window.exports?.JitsiMeetExternalAPI ? window.JitsiMeetExternalAPI
setApi jitsi = new Jitsi host,
parentNode: ref.current
roomName: roomName
configOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/config.js
prejoinPageEnabled: false
subject: room.title
defaultRemoteDisplayName: 'PI:NAME:<NAME>END_PI'
startWithAudioMuted: lastJitsiStatus.audioMuted
startWithVideoMuted: lastJitsiStatus.videoMuted
interfaceConfigOverwrite:
# See https://github.com/jitsi/jitsi-meet/blob/master/interface_config.js
DEFAULT_BACKGROUND:
if getDark() then '#111' else '#474747'
DISABLE_VIDEO_BACKGROUND: true
TOOLBAR_BUTTONS: [
'microphone', 'camera', 'closedcaptions', 'desktop',
'embedmeeting', 'fullscreen', 'fodeviceselection', 'hangup',
'profile', 'recording', 'livestreaming', 'etherpad',
'settings', 'videoquality', 'filmstrip', 'feedback', 'stats',
'shortcuts', 'tileview', 'videobackgroundblur', 'download', 'help',
'mute-everyone'
] # omit 'chat', 'security', 'invite', 'raisehand', 'sharedvideo' [YouTube]
SETTINGS_SECTIONS: [
'devices', 'language', 'moderator'
] # omit 'profile' and 'calendar'
DISPLAY_WELCOME_PAGE_CONTENT: false
SHOW_CHROME_EXTENSION_BANNER: false
HIDE_INVITE_MORE_HEADER: true
RECENT_LIST_ENABLED: false
SHOW_PROMOTIONAL_CLOSE_PAGE: false # if supported by server
userInfo:
displayName: PI:NAME:<NAME>END_PI
jitsi.addListener 'audioMuteStatusChanged', ({muted}) ->
lastJitsiStatus.audioMuted = muted
jitsi.addListener 'videoMuteStatusChanged', ({muted}) ->
lastJitsiStatus.videoMuted = muted
jitsi.addListener 'readyToClose', -> # hangup call
setJoined false
## Before hanging up, Jitsi mutes the video and emits an event, so we no
## longer know the correct Jitsi status. So reset to default upon hangup.
lastJitsiStatus = defaultJitsiStatus()
-> # cleanup
jitsi?.dispose()
, [tab?.url, loading, error, joined]
## Keep settings up-to-date
useEffect ->
api?.executeCommand 'displayName', name
undefined
, [name]
useEffect ->
api?.executeCommand 'subject', room.title
undefined
, [room.title]
## Maintain number of joined Jitsi calls, and reset state if zero and timeout.
useEffect ->
numJitsi++ if joined
lastJitsiStatus.joined = (numJitsi > 0)
if timeoutJitsiStatus?
clearTimeout timeoutJitsiStatus
timeoutJitsiStatus = null
->
numJitsi-- if joined
if numJitsi == 0 and resetJitsiStatusAfter?
timeoutJitsiStatus = setTimeout ->
timeoutJitsiStatus = null
#lastJitsiStatus = defaultJitsiStatus()
lastJitsiStatus.joined = defaultJitsiStatus().joined
, resetJitsiStatusAfter * 1000
, [joined]
return null unless tab
<div ref={ref}>
{if error
<Alert variant="danger">
Failed to load <a href={script} target="_blank" rel="noopener">Jitsi external API script</a>.
Is <a href={'https://' + host} target="_blank" rel="noopener">{host}</a> a valid Jitsi server?
</Alert>
else if not joined
<Card>
<Card.Body>
<Card.Title>Jitsi Meeting</Card.Title>
<p>
<b>Server:</b> <a href={'https://' + host} target="_blank" rel="noopener"><code>{host}</code></a><br/>
<b>Room ID:</b> <code>{roomName}</code>
</p>
<Button block onClick={-> setJoined true}>Join Call</Button>
<p>When joining, you may need to grant access to your microphone and/or camera. If you want to try again, select the “Reload Tab” button at the top of this tab.</p>
<p>If you hang up on the call and receive an ad, click the X button (at the top right of the ad) to fully leave the call, and prevent Comingle from automatically joining future Jitsi calls.</p>
</Card.Body>
</Card>
else if loading
<Loading/>
}
</div>
TabJitsi.displayName = 'TabJitsi'
|
[
{
"context": "##########################\n# Minday 0.009 Lykia\n# timer.coffee\n# Кнопка для таймера\n#############",
"end": 48,
"score": 0.8745150566101074,
"start": 43,
"tag": "NAME",
"value": "Lykia"
}
] | timer.coffee | agershun/minday | 0 | ##########################
# Minday 0.009 Lykia
# timer.coffee
# Кнопка для таймера
###########################
timer = {}
$$tick = null
$$bell = null
setTimer = ->
timer.state = off
$("#timer").click clickTimer
$$tick = document.getElementById("tick-audio")
$$bell = document.getElementById("bell-audio")
changeTime =->
$("#time").html (" "+Math.floor(timer.seconds/60)+":"+("0"+timer.seconds%60).substr(-2))
timer.seconds -= 1
# Если времы прошло, то...
if timer.seconds <= 0
clearInterval(timer.interval)
timer.state = off
alert "Время закончилось!"
$("#time").html "Таймер"
$$bell.load()
$$bell.play()
# Издавать звуки
if (timer.seconds % 60) is 0 or (timer.seconds < 10) or ((timer.seconds < 60) and ((timer.seconds % 10) is 0))
# $$tick.currentTime = 0
$$tick.load()
$$tick.play()
clickTimer =->
if timer.state is off
timer.minutes = prompt "На сколько минут поставить таймер","15"
timer.seconds = timer.minutes*60
timer.interval = setInterval changeTime,1000
timer.state = on
else
clearInterval(timer.interval)
timer.state = off
$("#time").html "Таймер"
| 115630 | ##########################
# Minday 0.009 <NAME>
# timer.coffee
# Кнопка для таймера
###########################
timer = {}
$$tick = null
$$bell = null
setTimer = ->
timer.state = off
$("#timer").click clickTimer
$$tick = document.getElementById("tick-audio")
$$bell = document.getElementById("bell-audio")
changeTime =->
$("#time").html (" "+Math.floor(timer.seconds/60)+":"+("0"+timer.seconds%60).substr(-2))
timer.seconds -= 1
# Если времы прошло, то...
if timer.seconds <= 0
clearInterval(timer.interval)
timer.state = off
alert "Время закончилось!"
$("#time").html "Таймер"
$$bell.load()
$$bell.play()
# Издавать звуки
if (timer.seconds % 60) is 0 or (timer.seconds < 10) or ((timer.seconds < 60) and ((timer.seconds % 10) is 0))
# $$tick.currentTime = 0
$$tick.load()
$$tick.play()
clickTimer =->
if timer.state is off
timer.minutes = prompt "На сколько минут поставить таймер","15"
timer.seconds = timer.minutes*60
timer.interval = setInterval changeTime,1000
timer.state = on
else
clearInterval(timer.interval)
timer.state = off
$("#time").html "Таймер"
| true | ##########################
# Minday 0.009 PI:NAME:<NAME>END_PI
# timer.coffee
# Кнопка для таймера
###########################
timer = {}
$$tick = null
$$bell = null
setTimer = ->
timer.state = off
$("#timer").click clickTimer
$$tick = document.getElementById("tick-audio")
$$bell = document.getElementById("bell-audio")
changeTime =->
$("#time").html (" "+Math.floor(timer.seconds/60)+":"+("0"+timer.seconds%60).substr(-2))
timer.seconds -= 1
# Если времы прошло, то...
if timer.seconds <= 0
clearInterval(timer.interval)
timer.state = off
alert "Время закончилось!"
$("#time").html "Таймер"
$$bell.load()
$$bell.play()
# Издавать звуки
if (timer.seconds % 60) is 0 or (timer.seconds < 10) or ((timer.seconds < 60) and ((timer.seconds % 10) is 0))
# $$tick.currentTime = 0
$$tick.load()
$$tick.play()
clickTimer =->
if timer.state is off
timer.minutes = prompt "На сколько минут поставить таймер","15"
timer.seconds = timer.minutes*60
timer.interval = setInterval changeTime,1000
timer.state = on
else
clearInterval(timer.interval)
timer.state = off
$("#time").html "Таймер"
|
[
{
"context": "8d32ce4cb04/mist/subscribe/websocket?X-AUTH-TOKEN=eP524w9IpvfXQ8lRCcFBqLmdrMayUKOhHt3EAsuWojZiVJS7nz\",\n tags: [\"log\"],\n logging: ",
"end": 298,
"score": 0.9452414512634277,
"start": 248,
"tag": "KEY",
"value": "eP524w9IpvfXQ8lRCcFBqLmdrMayUKOhHt3EAsuWo... | stage/stage.coffee | nanobox-io/nanobox-dash-ui-logs | 1 | window.init = () ->
# scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
#
options = {
liveConfig: {
url: "wss://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/mist/subscribe/websocket?X-AUTH-TOKEN=eP524w9IpvfXQ8lRCcFBqLmdrMayUKOhHt3EAsuWojZiVJS7nz",
tags: ["log"],
logging: {enabled: true, level: "DEBUG"}
},
historicConfig: {
url: "https://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/logvac/logs?X-USER-TOKEN=01DifGBnr8xVjds4ACKY5oERTkc6gePMXuqZawtOLFIlpvUzym",
type: "app",
id: "",
limit: 50,
logging: {enabled: true, level: "DEBUG"}
},
}
#
logs = new nanobox.Logs $("body"), $("#absolute-wrapper"), options
logs.build()
| 98467 | window.init = () ->
# scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
#
options = {
liveConfig: {
url: "wss://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/mist/subscribe/websocket?X-AUTH-TOKEN=<KEY>",
tags: ["log"],
logging: {enabled: true, level: "DEBUG"}
},
historicConfig: {
url: "https://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/logvac/logs?X-USER-TOKEN=<KEY>",
type: "app",
id: "",
limit: 50,
logging: {enabled: true, level: "DEBUG"}
},
}
#
logs = new nanobox.Logs $("body"), $("#absolute-wrapper"), options
logs.build()
| true | window.init = () ->
# scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
#
options = {
liveConfig: {
url: "wss://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/mist/subscribe/websocket?X-AUTH-TOKEN=PI:KEY:<KEY>END_PI",
tags: ["log"],
logging: {enabled: true, level: "DEBUG"}
},
historicConfig: {
url: "https://proxy.nanobox.io/1c43fbab-8d75-4a38-b191-98d32ce4cb04/logvac/logs?X-USER-TOKEN=PI:KEY:<KEY>END_PI",
type: "app",
id: "",
limit: 50,
logging: {enabled: true, level: "DEBUG"}
},
}
#
logs = new nanobox.Logs $("body"), $("#absolute-wrapper"), options
logs.build()
|
[
{
"context": "rityE1__u1\"\n \n mx_hash_stub.hash_key = \"pre_op\"\n mx_hash_stub.hash_key_idx = 1\n mx_has",
"end": 3664,
"score": 0.9575136303901672,
"start": 3658,
"tag": "KEY",
"value": "pre_op"
},
{
"context": "rityE1__u2\"\n \n mx_hash_stub.hash_ke... | src/strict_gen_for_coverage.coffee | hu2prod/gram3 | 0 | # WARNING!!! AUTOGENERATED with gen_strict.coffee
module = @
{
Tokenizer
Token_parser
} = require './tokenizer'
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ (
(&&?|\|\|?|[-+*/])|
<>|[<>!=]=|<|>
) ///)
tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/)
# tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/)
# ###################################################################################################
# gram
# ###################################################################################################
require 'fy'
STATE_NA = 0
STATE_RQ = 1 # REQ
STATE_IG = 2 # REQ_IGNORE
STATE_FL = 3 # REQ_FILL
state_stub = []
for i in [0 ... 12]
state_stub.push STATE_NA
counter_stub = []
for i in [0 ... 76]
counter_stub.push 0
hash_key_list = [
"_",
"pre_op",
"bin_op",
"access_rvalue",
"dollar_id",
"hash_id",
"rvalue",
"number",
"id",
"string_literal_singleq",
"string_literal_doubleq",
"strict_rule"
]
class @Parser
length: 0
cache : []
state : []
counter: []
Node : null
proxy : null
proxy2: null
go : (token_list_list)->
@cache= []
@state= []
@counter= []
@length = token_list_list.length
return [] if @length == 0
@Node = token_list_list[0]?[0]?.constructor
@proxy= new @Node
@proxy2= new @Node
for token_list,idx in token_list_list
stub = new Array 62
for k in [0 ... 62]
stub[k] = []
for token in token_list
token.a = idx
token.b = idx+1
if -1 != stub_idx = hash_key_list.idx token.mx_hash.hash_key
stub[stub_idx].push token
stub[0].upush token
@cache.push stub
@state.push state_stub.slice()
@counter.push counter_stub.slice()
# one const rule opt
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "!"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u1"
mx_hash_stub.hash_key = "pre_op"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "-"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u2"
mx_hash_stub.hash_key = "pre_op"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "+"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XP_priorityE1__u3"
mx_hash_stub.hash_key = "pre_op"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
@fsm()
list = @cache[0][11]
max_token = token_list_list.length
filter_list = []
for v in list
if v.b == max_token
@node_fix v
filter_list.push v
# Прим. А все ошибки, почему не прошло ... смотрим и анализируем @cache
filter_list
node_fix : (node)->
walk = (node)->
vv_list = []
max_depth = -1
for v in node.value_array
walk v
max_depth = Math.max max_depth, v.depth
node.depth = max_depth + 1
if node.depth < 10 # HARDCODE !!!
for v in node.value_array
vv_list.push v.value_view or v.value
node.value_view = vv_list.join ' '
return
walk node
return
fsm : ()->
FAcache = @cache
FAstate = @state
FAcounter = @counter
stack = [
[
11
0
0
]
]
FAstate[0][11] = STATE_RQ
length = @length
request_make = (token_hki, pos, is_new)->
state = FAstate[pos][token_hki]
switch state
when 0 # STATE_NA
if is_new
### !pragma coverage-skip-block ###
throw new Error 'invalid call. STATE_NA + is_new'
stack.push [token_hki, pos, is_new]
FAstate[pos][token_hki] = STATE_RQ
return true
when 1 # STATE_RQ
FAstate[pos][token_hki] = STATE_IG
return false
when 2 # STATE_IG
# stack.push [token_hki, pos, is_new]
return false
when 3 # STATE_FL
FAstate[pos][token_hki] = STATE_RQ
stack.push [token_hki, pos, is_new]
return true
return
# TODO remove
safe_collect = (dst, src)->
# TODO hash[candidate.b] optimization
# Вместо того, чтобы проходить всегда можно спросить а есть ли такой длинны уже найденый токен
# И хранить можно hash или массив b и быстро спрашивать по надобности
# В случае хэша, там же можно хранить только токены такой длинны
for candidate in src
found = false
for chk in dst
# continue if chk.b != candidate.b
c_varr = candidate.value_array
continue if chk.value_array.length != c_varr.length
match = true
for chk_v,idx in chk.value_array
if chk_v != c_varr[idx]
match = false
break
if match
found = true
break
if !found
dst.push candidate
return
while cur = stack.pop()
[
hki
start_pos
only_new
] = cur
continue if start_pos >= length
switch hki
when 0
### token__ queue ###
stack.push [
12
start_pos
only_new
]
when 12
### token__ collect ###
node_list = []
FAstate[start_pos][0] = STATE_FL
FAcache[start_pos][0].uappend node_list
when 1
### token_pre_op queue ###
stack.push [
13
start_pos
only_new
]
when 13
### token_pre_op collect ###
node_list = []
FAstate[start_pos][1] = STATE_FL
FAcache[start_pos][1].uappend node_list
when 2
### token_bin_op queue ###
stack.push [
22
start_pos
only_new
]
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
stack.push [
14
start_pos
only_new
]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
stack.push [
16
start_pos
only_new
]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
stack.push [
18
start_pos
only_new
]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
stack.push [
20
start_pos
only_new
]
when 22
### token_bin_op collect ###
node_list = []
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
node_list.append FAcache[start_pos][14]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
node_list.append FAcache[start_pos][16]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
node_list.append FAcache[start_pos][18]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
node_list.append FAcache[start_pos][20]
FAstate[start_pos][2] = STATE_FL
FAcache[start_pos][2].uappend node_list
when 3
### token_access_rvalue queue ###
stack.push [
29
start_pos
only_new
]
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
stack.push [
23
start_pos
only_new
]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
stack.push [
25
start_pos
only_new
]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
stack.push [
27
start_pos
only_new
]
when 29
### token_access_rvalue collect ###
node_list = []
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
node_list.append FAcache[start_pos][23]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
node_list.append FAcache[start_pos][25]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
node_list.append FAcache[start_pos][27]
FAstate[start_pos][3] = STATE_FL
FAcache[start_pos][3].uappend node_list
when 4
### token_dollar_id queue ###
stack.push [
30
start_pos
only_new
]
when 30
### token_dollar_id collect ###
node_list = []
FAstate[start_pos][4] = STATE_FL
FAcache[start_pos][4].uappend node_list
when 5
### token_hash_id queue ###
stack.push [
31
start_pos
only_new
]
when 31
### token_hash_id collect ###
node_list = []
FAstate[start_pos][5] = STATE_FL
FAcache[start_pos][5].uappend node_list
when 6
### token_rvalue queue ###
stack.push [
54
start_pos
only_new
]
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
stack.push [
32
start_pos
only_new
]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
stack.push [
34
start_pos
only_new
]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
stack.push [
36
start_pos
only_new
]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
stack.push [
38
start_pos
only_new
]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
stack.push [
40
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
stack.push [
42
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
stack.push [
44
start_pos
only_new
]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
stack.push [
46
start_pos
only_new
]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
stack.push [
48
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
stack.push [
50
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
stack.push [
52
start_pos
only_new
]
when 54
### token_rvalue collect ###
node_list = []
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
node_list.append FAcache[start_pos][32]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
node_list.append FAcache[start_pos][34]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
node_list.append FAcache[start_pos][36]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
node_list.append FAcache[start_pos][38]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
node_list.append FAcache[start_pos][40]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
node_list.append FAcache[start_pos][42]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
node_list.append FAcache[start_pos][44]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
node_list.append FAcache[start_pos][46]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
node_list.append FAcache[start_pos][48]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
node_list.append FAcache[start_pos][50]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
node_list.append FAcache[start_pos][52]
append_list = FAcache[start_pos][6]
has_new = false
for node in node_list
if append_list.has node
node._is_new = false
else
node._is_new = true
append_list.push node
has_new = true
state = FAstate[start_pos][6]
FAstate[start_pos][6] = STATE_FL
if state == STATE_IG
if has_new
# recursive case
FAstate[start_pos][6] = STATE_RQ
stack.push [
6
start_pos
1
]
request_make 6, start_pos, 1
when 7
### token_number queue ###
stack.push [
55
start_pos
only_new
]
when 55
### token_number collect ###
node_list = []
FAstate[start_pos][7] = STATE_FL
FAcache[start_pos][7].uappend node_list
when 8
### token_id queue ###
stack.push [
56
start_pos
only_new
]
when 56
### token_id collect ###
node_list = []
FAstate[start_pos][8] = STATE_FL
FAcache[start_pos][8].uappend node_list
when 9
### token_string_literal_singleq queue ###
stack.push [
57
start_pos
only_new
]
when 57
### token_string_literal_singleq collect ###
node_list = []
FAstate[start_pos][9] = STATE_FL
FAcache[start_pos][9].uappend node_list
when 10
### token_string_literal_doubleq queue ###
stack.push [
58
start_pos
only_new
]
when 58
### token_string_literal_doubleq collect ###
node_list = []
FAstate[start_pos][10] = STATE_FL
FAcache[start_pos][10].uappend node_list
when 11
### token_strict_rule queue ###
stack.push [
61
start_pos
only_new
]
### rule_Hrvalue_ultEdeep__u22 ###
stack.push [
59
start_pos
only_new
]
when 61
### token_strict_rule collect ###
node_list = []
### rule_Hrvalue_ultEdeep__u22 ###
node_list.append FAcache[start_pos][59]
FAstate[start_pos][11] = STATE_FL
FAcache[start_pos][11].uappend node_list
when 14
### rule_XSXXX_priorityE5__right_assocE1__u4 queue ###
chk_len = stack.push [
14
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][0] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][1] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 15
when 15
### rule_XSXXX_priorityE5__right_assocE1__u4 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][2] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][2] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][3] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][3] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XSXXX_priorityE5__right_assocE1__u4"
mx_hash_stub.hash_key = "bin_op"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 5
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][14].append ret_list
#safe_collect FAcache[start_pos][14], ret_list
when 16
### rule_XPXXX_priorityE6__right_assocE1__u5 queue ###
chk_len = stack.push [
16
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][4] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][5] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 17
when 17
### rule_XPXXX_priorityE6__right_assocE1__u5 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][6] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][6] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][7] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][7] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XPXXX_priorityE6__right_assocE1__u5"
mx_hash_stub.hash_key = "bin_op"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 6
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][16].append ret_list
#safe_collect FAcache[start_pos][16], ret_list
when 18
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 queue ###
chk_len = stack.push [
18
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][8] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][9] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][10] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][11] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][12] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][13] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][14] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 19
when 19
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][15] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][15] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][16] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][16] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][17] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][17] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][18] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][18] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][19] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][19] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][20] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][20] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][21] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][21] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6"
mx_hash_stub.hash_key = "bin_op"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 9
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][18].append ret_list
#safe_collect FAcache[start_pos][18], ret_list
when 20
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 queue ###
chk_len = stack.push [
20
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][22] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][23] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][24] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][25] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 21
when 21
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][26] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][26] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][27] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][27] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][28] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][28] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][29] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][29] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7"
mx_hash_stub.hash_key = "bin_op"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 10
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][20].append ret_list
#safe_collect FAcache[start_pos][20], ret_list
when 23
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 queue ###
chk_len = stack.push [
23
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][4]
if state_1 != STATE_FL
if request_make 4, b_0, 0
continue
list_1 = FAcache[b_0][4]
if chk_len == stack.length
stack[chk_len-1][0] = 24
when 24
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][4]
for idx_1 in [FAcounter[b_0][30] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8"
mx_hash_stub.hash_key = "access_rvalue"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "dollar_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][30] = list_1.length
FAcache[start_pos][23].append ret_list
#safe_collect FAcache[start_pos][23], ret_list
when 25
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 queue ###
chk_len = stack.push [
25
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
if chk_len == stack.length
stack[chk_len-1][0] = 26
when 26
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][31] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_priorityEX9000_ultEhash_id__u9"
mx_hash_stub.hash_key = "access_rvalue"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][31] = list_1.length
FAcache[start_pos][25].append ret_list
#safe_collect FAcache[start_pos][25], ret_list
when 27
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 queue ###
chk_len = stack.push [
27
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][33] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 28
when 28
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][37] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != "]"
b_4 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19"
mx_hash_stub.hash_key = "access_rvalue"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_array_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][37] = list_1.length
FAcache[start_pos][27].append ret_list
#safe_collect FAcache[start_pos][27], ret_list
when 32
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 queue ###
chk_len = stack.push [
32
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
if chk_len == stack.length
stack[chk_len-1][0] = 33
when 33
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][38] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "access_rvalue"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][38] = list_1.length
FAcache[start_pos][32].append ret_list
#safe_collect FAcache[start_pos][32], ret_list
when 34
### rule_Hnumber_priorityEX9000_ultEvalue__u11 queue ###
chk_len = stack.push [
34
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][7]
if state_1 != STATE_FL
if request_make 7, b_0, 0
continue
list_1 = FAcache[b_0][7]
if chk_len == stack.length
stack[chk_len-1][0] = 35
when 35
### rule_Hnumber_priorityEX9000_ultEvalue__u11 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][7]
for idx_1 in [FAcounter[b_0][39] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hnumber_priorityEX9000_ultEvalue__u11"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][39] = list_1.length
FAcache[start_pos][34].append ret_list
#safe_collect FAcache[start_pos][34], ret_list
when 36
### rule_Hid_priorityEX9000_ultEwrap_string__u12 queue ###
chk_len = stack.push [
36
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][8]
if state_1 != STATE_FL
if request_make 8, b_0, 0
continue
list_1 = FAcache[b_0][8]
if chk_len == stack.length
stack[chk_len-1][0] = 37
when 37
### rule_Hid_priorityEX9000_ultEwrap_string__u12 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][8]
for idx_1 in [FAcounter[b_0][40] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hid_priorityEX9000_ultEwrap_string__u12"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "wrap_string"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][40] = list_1.length
FAcache[start_pos][36].append ret_list
#safe_collect FAcache[start_pos][36], ret_list
when 38
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 queue ###
chk_len = stack.push [
38
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][9]
if state_1 != STATE_FL
if request_make 9, b_0, 0
continue
list_1 = FAcache[b_0][9]
if chk_len == stack.length
stack[chk_len-1][0] = 39
when 39
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][9]
for idx_1 in [FAcounter[b_0][41] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][41] = list_1.length
FAcache[start_pos][38].append ret_list
#safe_collect FAcache[start_pos][38], ret_list
when 40
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 queue ###
chk_len = stack.push [
40
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][10]
if state_1 != STATE_FL
if request_make 10, b_0, 0
continue
list_1 = FAcache[b_0][10]
if chk_len == stack.length
stack[chk_len-1][0] = 41
when 41
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][10]
for idx_1 in [FAcounter[b_0][42] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][42] = list_1.length
FAcache[start_pos][40].append ret_list
#safe_collect FAcache[start_pos][40], ret_list
when 42
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 queue ###
chk_len = stack.push [
42
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][44] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 43
when 43
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][47] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][47] = list_1.length
FAcache[start_pos][42].append ret_list
#safe_collect FAcache[start_pos][42], ret_list
when 44
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 queue ###
chk_len = stack.push [
44
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][49] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 45
when 45
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][52] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority==arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !(arg_list[1].mx_hash.right_assoc)
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][52] = list_1.length
FAcache[start_pos][44].append ret_list
#safe_collect FAcache[start_pos][44], ret_list
when 46
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 queue ###
chk_len = stack.push [
46
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][1]
if state_1 != STATE_FL
if request_make 1, b_0, 0
continue
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][53] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 47
when 47
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][55] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[1].mx_hash.priority<=arg_list[0].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[0].mx_hash.priority
mx_hash_stub["ult"] = "pre_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][55] = list_1.length
FAcache[start_pos][46].append ret_list
#safe_collect FAcache[start_pos][46], ret_list
when 48
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 queue ###
chk_len = stack.push [
48
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][56] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 49
when 49
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][59] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][0]
for tok in list_3
continue if tok.value != ")"
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "bra"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][59] = list_1.length
FAcache[start_pos][48].append ret_list
#safe_collect FAcache[start_pos][48], ret_list
when 50
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 queue ###
chk_len = stack.push [
50
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][63] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
state_5 = FAstate[b_4][7]
if state_5 != STATE_FL
if request_make 7, b_4, 0
continue
list_5 = FAcache[b_4][7]
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 51
when 51
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][69] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
list_5 = FAcache[b_4][7]
for tok in list_5
b_5 = tok.b
node.value_array.push tok
if b_5 >= length
node.value_array.pop()
continue
list_6 = FAcache[b_5][0]
for tok in list_6
continue if tok.value != "]"
b_6 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "slice_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][69] = list_1.length
FAcache[start_pos][50].append ret_list
#safe_collect FAcache[start_pos][50], ret_list
when 52
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 queue ###
chk_len = stack.push [
52
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][71] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][8]
if state_3 != STATE_FL
if request_make 8, b_2, 0
continue
list_3 = FAcache[b_2][8]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 53
when 53
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][74] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][8]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "field_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][74] = list_1.length
FAcache[start_pos][52].append ret_list
#safe_collect FAcache[start_pos][52], ret_list
when 59
### rule_Hrvalue_ultEdeep__u22 queue ###
chk_len = stack.push [
59
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
if chk_len == stack.length
stack[chk_len-1][0] = 60
when 60
### rule_Hrvalue_ultEdeep__u22 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][75] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_ultEdeep__u22"
mx_hash_stub.hash_key = "strict_rule"
mx_hash_stub.hash_key_idx = 11
mx_hash_stub["ult"] = "deep"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][75] = list_1.length
FAcache[start_pos][59].append ret_list
#safe_collect FAcache[start_pos][59], ret_list
return
# ###################################################################################################
parser = new module.Parser
@parse = (str)->
tok_list = tokenizer.go str
res_list = parser.go tok_list
# debug
@tokenizer = tokenizer
@parser = parser
| 176931 | # WARNING!!! AUTOGENERATED with gen_strict.coffee
module = @
{
Tokenizer
Token_parser
} = require './tokenizer'
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ (
(&&?|\|\|?|[-+*/])|
<>|[<>!=]=|<|>
) ///)
tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/)
# tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/)
# ###################################################################################################
# gram
# ###################################################################################################
require 'fy'
STATE_NA = 0
STATE_RQ = 1 # REQ
STATE_IG = 2 # REQ_IGNORE
STATE_FL = 3 # REQ_FILL
state_stub = []
for i in [0 ... 12]
state_stub.push STATE_NA
counter_stub = []
for i in [0 ... 76]
counter_stub.push 0
hash_key_list = [
"_",
"pre_op",
"bin_op",
"access_rvalue",
"dollar_id",
"hash_id",
"rvalue",
"number",
"id",
"string_literal_singleq",
"string_literal_doubleq",
"strict_rule"
]
class @Parser
length: 0
cache : []
state : []
counter: []
Node : null
proxy : null
proxy2: null
go : (token_list_list)->
@cache= []
@state= []
@counter= []
@length = token_list_list.length
return [] if @length == 0
@Node = token_list_list[0]?[0]?.constructor
@proxy= new @Node
@proxy2= new @Node
for token_list,idx in token_list_list
stub = new Array 62
for k in [0 ... 62]
stub[k] = []
for token in token_list
token.a = idx
token.b = idx+1
if -1 != stub_idx = hash_key_list.idx token.mx_hash.hash_key
stub[stub_idx].push token
stub[0].upush token
@cache.push stub
@state.push state_stub.slice()
@counter.push counter_stub.slice()
# one const rule opt
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "!"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u1"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "-"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u2"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "+"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XP_priorityE1__u3"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
@fsm()
list = @cache[0][11]
max_token = token_list_list.length
filter_list = []
for v in list
if v.b == max_token
@node_fix v
filter_list.push v
# Прим. А все ошибки, почему не прошло ... смотрим и анализируем @cache
filter_list
node_fix : (node)->
walk = (node)->
vv_list = []
max_depth = -1
for v in node.value_array
walk v
max_depth = Math.max max_depth, v.depth
node.depth = max_depth + 1
if node.depth < 10 # HARDCODE !!!
for v in node.value_array
vv_list.push v.value_view or v.value
node.value_view = vv_list.join ' '
return
walk node
return
fsm : ()->
FAcache = @cache
FAstate = @state
FAcounter = @counter
stack = [
[
11
0
0
]
]
FAstate[0][11] = STATE_RQ
length = @length
request_make = (token_hki, pos, is_new)->
state = FAstate[pos][token_hki]
switch state
when 0 # STATE_NA
if is_new
### !pragma coverage-skip-block ###
throw new Error 'invalid call. STATE_NA + is_new'
stack.push [token_hki, pos, is_new]
FAstate[pos][token_hki] = STATE_RQ
return true
when 1 # STATE_RQ
FAstate[pos][token_hki] = STATE_IG
return false
when 2 # STATE_IG
# stack.push [token_hki, pos, is_new]
return false
when 3 # STATE_FL
FAstate[pos][token_hki] = STATE_RQ
stack.push [token_hki, pos, is_new]
return true
return
# TODO remove
safe_collect = (dst, src)->
# TODO hash[candidate.b] optimization
# Вместо того, чтобы проходить всегда можно спросить а есть ли такой длинны уже найденый токен
# И хранить можно hash или массив b и быстро спрашивать по надобности
# В случае хэша, там же можно хранить только токены такой длинны
for candidate in src
found = false
for chk in dst
# continue if chk.b != candidate.b
c_varr = candidate.value_array
continue if chk.value_array.length != c_varr.length
match = true
for chk_v,idx in chk.value_array
if chk_v != c_varr[idx]
match = false
break
if match
found = true
break
if !found
dst.push candidate
return
while cur = stack.pop()
[
hki
start_pos
only_new
] = cur
continue if start_pos >= length
switch hki
when 0
### token__ queue ###
stack.push [
12
start_pos
only_new
]
when 12
### token__ collect ###
node_list = []
FAstate[start_pos][0] = STATE_FL
FAcache[start_pos][0].uappend node_list
when 1
### token_pre_op queue ###
stack.push [
13
start_pos
only_new
]
when 13
### token_pre_op collect ###
node_list = []
FAstate[start_pos][1] = STATE_FL
FAcache[start_pos][1].uappend node_list
when 2
### token_bin_op queue ###
stack.push [
22
start_pos
only_new
]
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
stack.push [
14
start_pos
only_new
]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
stack.push [
16
start_pos
only_new
]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
stack.push [
18
start_pos
only_new
]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
stack.push [
20
start_pos
only_new
]
when 22
### token_bin_op collect ###
node_list = []
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
node_list.append FAcache[start_pos][14]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
node_list.append FAcache[start_pos][16]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
node_list.append FAcache[start_pos][18]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
node_list.append FAcache[start_pos][20]
FAstate[start_pos][2] = STATE_FL
FAcache[start_pos][2].uappend node_list
when 3
### token_access_rvalue queue ###
stack.push [
29
start_pos
only_new
]
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
stack.push [
23
start_pos
only_new
]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
stack.push [
25
start_pos
only_new
]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
stack.push [
27
start_pos
only_new
]
when 29
### token_access_rvalue collect ###
node_list = []
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
node_list.append FAcache[start_pos][23]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
node_list.append FAcache[start_pos][25]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
node_list.append FAcache[start_pos][27]
FAstate[start_pos][3] = STATE_FL
FAcache[start_pos][3].uappend node_list
when 4
### token_dollar_id queue ###
stack.push [
30
start_pos
only_new
]
when 30
### token_dollar_id collect ###
node_list = []
FAstate[start_pos][4] = STATE_FL
FAcache[start_pos][4].uappend node_list
when 5
### token_hash_id queue ###
stack.push [
31
start_pos
only_new
]
when 31
### token_hash_id collect ###
node_list = []
FAstate[start_pos][5] = STATE_FL
FAcache[start_pos][5].uappend node_list
when 6
### token_rvalue queue ###
stack.push [
54
start_pos
only_new
]
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
stack.push [
32
start_pos
only_new
]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
stack.push [
34
start_pos
only_new
]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
stack.push [
36
start_pos
only_new
]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
stack.push [
38
start_pos
only_new
]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
stack.push [
40
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
stack.push [
42
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
stack.push [
44
start_pos
only_new
]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
stack.push [
46
start_pos
only_new
]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
stack.push [
48
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
stack.push [
50
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
stack.push [
52
start_pos
only_new
]
when 54
### token_rvalue collect ###
node_list = []
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
node_list.append FAcache[start_pos][32]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
node_list.append FAcache[start_pos][34]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
node_list.append FAcache[start_pos][36]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
node_list.append FAcache[start_pos][38]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
node_list.append FAcache[start_pos][40]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
node_list.append FAcache[start_pos][42]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
node_list.append FAcache[start_pos][44]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
node_list.append FAcache[start_pos][46]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
node_list.append FAcache[start_pos][48]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
node_list.append FAcache[start_pos][50]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
node_list.append FAcache[start_pos][52]
append_list = FAcache[start_pos][6]
has_new = false
for node in node_list
if append_list.has node
node._is_new = false
else
node._is_new = true
append_list.push node
has_new = true
state = FAstate[start_pos][6]
FAstate[start_pos][6] = STATE_FL
if state == STATE_IG
if has_new
# recursive case
FAstate[start_pos][6] = STATE_RQ
stack.push [
6
start_pos
1
]
request_make 6, start_pos, 1
when 7
### token_number queue ###
stack.push [
55
start_pos
only_new
]
when 55
### token_number collect ###
node_list = []
FAstate[start_pos][7] = STATE_FL
FAcache[start_pos][7].uappend node_list
when 8
### token_id queue ###
stack.push [
56
start_pos
only_new
]
when 56
### token_id collect ###
node_list = []
FAstate[start_pos][8] = STATE_FL
FAcache[start_pos][8].uappend node_list
when 9
### token_string_literal_singleq queue ###
stack.push [
57
start_pos
only_new
]
when 57
### token_string_literal_singleq collect ###
node_list = []
FAstate[start_pos][9] = STATE_FL
FAcache[start_pos][9].uappend node_list
when 10
### token_string_literal_doubleq queue ###
stack.push [
58
start_pos
only_new
]
when 58
### token_string_literal_doubleq collect ###
node_list = []
FAstate[start_pos][10] = STATE_FL
FAcache[start_pos][10].uappend node_list
when 11
### token_strict_rule queue ###
stack.push [
61
start_pos
only_new
]
### rule_Hrvalue_ultEdeep__u22 ###
stack.push [
59
start_pos
only_new
]
when 61
### token_strict_rule collect ###
node_list = []
### rule_Hrvalue_ultEdeep__u22 ###
node_list.append FAcache[start_pos][59]
FAstate[start_pos][11] = STATE_FL
FAcache[start_pos][11].uappend node_list
when 14
### rule_XSXXX_priorityE5__right_assocE1__u4 queue ###
chk_len = stack.push [
14
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][0] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][1] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 15
when 15
### rule_XSXXX_priorityE5__right_assocE1__u4 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][2] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][2] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][3] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][3] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XSXXX_priorityE5__right_assocE1__u4"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 5
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][14].append ret_list
#safe_collect FAcache[start_pos][14], ret_list
when 16
### rule_XPXXX_priorityE6__right_assocE1__u5 queue ###
chk_len = stack.push [
16
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][4] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][5] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 17
when 17
### rule_XPXXX_priorityE6__right_assocE1__u5 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][6] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][6] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][7] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][7] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XPXXX_priorityE6__right_assocE1__u5"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 6
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][16].append ret_list
#safe_collect FAcache[start_pos][16], ret_list
when 18
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 queue ###
chk_len = stack.push [
18
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][8] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][9] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][10] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][11] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][12] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][13] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][14] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 19
when 19
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][15] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][15] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][16] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][16] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][17] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][17] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][18] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][18] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][19] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][19] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][20] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][20] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][21] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][21] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 9
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][18].append ret_list
#safe_collect FAcache[start_pos][18], ret_list
when 20
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 queue ###
chk_len = stack.push [
20
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][22] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][23] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][24] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][25] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 21
when 21
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][26] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][26] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][27] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][27] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][28] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][28] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][29] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][29] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 10
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][20].append ret_list
#safe_collect FAcache[start_pos][20], ret_list
when 23
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 queue ###
chk_len = stack.push [
23
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][4]
if state_1 != STATE_FL
if request_make 4, b_0, 0
continue
list_1 = FAcache[b_0][4]
if chk_len == stack.length
stack[chk_len-1][0] = 24
when 24
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][4]
for idx_1 in [FAcounter[b_0][30] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "dollar_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][30] = list_1.length
FAcache[start_pos][23].append ret_list
#safe_collect FAcache[start_pos][23], ret_list
when 25
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 queue ###
chk_len = stack.push [
25
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
if chk_len == stack.length
stack[chk_len-1][0] = 26
when 26
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][31] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_priorityEX9000_ultEhash_id__u9"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][31] = list_1.length
FAcache[start_pos][25].append ret_list
#safe_collect FAcache[start_pos][25], ret_list
when 27
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 queue ###
chk_len = stack.push [
27
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][33] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 28
when 28
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][37] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != "]"
b_4 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_array_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][37] = list_1.length
FAcache[start_pos][27].append ret_list
#safe_collect FAcache[start_pos][27], ret_list
when 32
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 queue ###
chk_len = stack.push [
32
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
if chk_len == stack.length
stack[chk_len-1][0] = 33
when 33
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][38] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "access_rvalue"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][38] = list_1.length
FAcache[start_pos][32].append ret_list
#safe_collect FAcache[start_pos][32], ret_list
when 34
### rule_Hnumber_priorityEX9000_ultEvalue__u11 queue ###
chk_len = stack.push [
34
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][7]
if state_1 != STATE_FL
if request_make 7, b_0, 0
continue
list_1 = FAcache[b_0][7]
if chk_len == stack.length
stack[chk_len-1][0] = 35
when 35
### rule_Hnumber_priorityEX9000_ultEvalue__u11 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][7]
for idx_1 in [FAcounter[b_0][39] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hnumber_priorityEX9000_ultEvalue__u11"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][39] = list_1.length
FAcache[start_pos][34].append ret_list
#safe_collect FAcache[start_pos][34], ret_list
when 36
### rule_Hid_priorityEX9000_ultEwrap_string__u12 queue ###
chk_len = stack.push [
36
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][8]
if state_1 != STATE_FL
if request_make 8, b_0, 0
continue
list_1 = FAcache[b_0][8]
if chk_len == stack.length
stack[chk_len-1][0] = 37
when 37
### rule_Hid_priorityEX9000_ultEwrap_string__u12 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][8]
for idx_1 in [FAcounter[b_0][40] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hid_priorityEX9000_ultEwrap_string__u12"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "wrap_string"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][40] = list_1.length
FAcache[start_pos][36].append ret_list
#safe_collect FAcache[start_pos][36], ret_list
when 38
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 queue ###
chk_len = stack.push [
38
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][9]
if state_1 != STATE_FL
if request_make 9, b_0, 0
continue
list_1 = FAcache[b_0][9]
if chk_len == stack.length
stack[chk_len-1][0] = 39
when 39
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][9]
for idx_1 in [FAcounter[b_0][41] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][41] = list_1.length
FAcache[start_pos][38].append ret_list
#safe_collect FAcache[start_pos][38], ret_list
when 40
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 queue ###
chk_len = stack.push [
40
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][10]
if state_1 != STATE_FL
if request_make 10, b_0, 0
continue
list_1 = FAcache[b_0][10]
if chk_len == stack.length
stack[chk_len-1][0] = 41
when 41
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][10]
for idx_1 in [FAcounter[b_0][42] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][42] = list_1.length
FAcache[start_pos][40].append ret_list
#safe_collect FAcache[start_pos][40], ret_list
when 42
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 queue ###
chk_len = stack.push [
42
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][44] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 43
when 43
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][47] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][47] = list_1.length
FAcache[start_pos][42].append ret_list
#safe_collect FAcache[start_pos][42], ret_list
when 44
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 queue ###
chk_len = stack.push [
44
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][49] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 45
when 45
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][52] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority==arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !(arg_list[1].mx_hash.right_assoc)
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][52] = list_1.length
FAcache[start_pos][44].append ret_list
#safe_collect FAcache[start_pos][44], ret_list
when 46
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 queue ###
chk_len = stack.push [
46
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][1]
if state_1 != STATE_FL
if request_make 1, b_0, 0
continue
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][53] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 47
when 47
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][55] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[1].mx_hash.priority<=arg_list[0].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[0].mx_hash.priority
mx_hash_stub["ult"] = "pre_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][55] = list_1.length
FAcache[start_pos][46].append ret_list
#safe_collect FAcache[start_pos][46], ret_list
when 48
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 queue ###
chk_len = stack.push [
48
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][56] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 49
when 49
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][59] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][0]
for tok in list_3
continue if tok.value != ")"
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18"
mx_hash_stub.hash_key = "r<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "bra"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][59] = list_1.length
FAcache[start_pos][48].append ret_list
#safe_collect FAcache[start_pos][48], ret_list
when 50
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 queue ###
chk_len = stack.push [
50
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][63] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
state_5 = FAstate[b_4][7]
if state_5 != STATE_FL
if request_make 7, b_4, 0
continue
list_5 = FAcache[b_4][7]
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 51
when 51
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][69] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
list_5 = FAcache[b_4][7]
for tok in list_5
b_5 = tok.b
node.value_array.push tok
if b_5 >= length
node.value_array.pop()
continue
list_6 = FAcache[b_5][0]
for tok in list_6
continue if tok.value != "]"
b_6 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "slice_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][69] = list_1.length
FAcache[start_pos][50].append ret_list
#safe_collect FAcache[start_pos][50], ret_list
when 52
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 queue ###
chk_len = stack.push [
52
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][71] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][8]
if state_3 != STATE_FL
if request_make 8, b_2, 0
continue
list_3 = FAcache[b_2][8]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 53
when 53
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][74] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][8]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "field_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][74] = list_1.length
FAcache[start_pos][52].append ret_list
#safe_collect FAcache[start_pos][52], ret_list
when 59
### rule_Hrvalue_ultEdeep__u22 queue ###
chk_len = stack.push [
59
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
if chk_len == stack.length
stack[chk_len-1][0] = 60
when 60
### rule_Hrvalue_ultEdeep__u22 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][75] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_ultEdeep__u22"
mx_hash_stub.hash_key = "<KEY>"
mx_hash_stub.hash_key_idx = 11
mx_hash_stub["ult"] = "deep"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][75] = list_1.length
FAcache[start_pos][59].append ret_list
#safe_collect FAcache[start_pos][59], ret_list
return
# ###################################################################################################
parser = new module.Parser
@parse = (str)->
tok_list = tokenizer.go str
res_list = parser.go tok_list
# debug
@tokenizer = tokenizer
@parser = parser
| true | # WARNING!!! AUTOGENERATED with gen_strict.coffee
module = @
{
Tokenizer
Token_parser
} = require './tokenizer'
tokenizer = new Tokenizer
tokenizer.parser_list.push (new Token_parser 'dollar_id', /^\$[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'hash_id', /^\#[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'pass_id', /^\@[_a-z0-9]+/i)
tokenizer.parser_list.push (new Token_parser 'id', /^[_a-z][_a-z0-9]*/i)
tokenizer.parser_list.push (new Token_parser '_bin_op', /// ^ (
(&&?|\|\|?|[-+*/])|
<>|[<>!=]=|<|>
) ///)
tokenizer.parser_list.push (new Token_parser '_pre_op', /^!/)
# tokenizer.parser_list.push (new Token_parser 'assign_bin_op', /^(&&?|\|\|?|[-+])?=/)
tokenizer.parser_list.push (new Token_parser 'bracket', /^[\[\]\(\)\{\}]/)
tokenizer.parser_list.push (new Token_parser 'delimiter', /^[:.]/)
string_regex_craft = ///
\\[^xu] | # x and u are case sensitive while hex letters are not
\\x[0-9a-fA-F]{2} | # Hexadecimal escape sequence
\\u(?:
[0-9a-fA-F]{4} | # Unicode escape sequence
\{(?:
[0-9a-fA-F]{1,5} | # Unicode code point escapes from 0 to FFFFF
10[0-9a-fA-F]{4} # Unicode code point escapes from 100000 to 10FFFF
)\}
)
///.toString().replace(/\//g,'')
single_quoted_regex_craft = ///
(?:
[^\\] |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_singleq' , /// ^ ' #{single_quoted_regex_craft} ' ///)
double_quoted_regexp_craft = ///
(?:
[^\\#] |
\#(?!\{) |
#{string_regex_craft}
)*?
///.toString().replace(/\//g,'')
tokenizer.parser_list.push (new Token_parser 'string_literal_doubleq' , /// ^ " #{double_quoted_regexp_craft} " ///)
tokenizer.parser_list.push (new Token_parser 'number', /^[0-9]+/)
# ###################################################################################################
# gram
# ###################################################################################################
require 'fy'
STATE_NA = 0
STATE_RQ = 1 # REQ
STATE_IG = 2 # REQ_IGNORE
STATE_FL = 3 # REQ_FILL
state_stub = []
for i in [0 ... 12]
state_stub.push STATE_NA
counter_stub = []
for i in [0 ... 76]
counter_stub.push 0
hash_key_list = [
"_",
"pre_op",
"bin_op",
"access_rvalue",
"dollar_id",
"hash_id",
"rvalue",
"number",
"id",
"string_literal_singleq",
"string_literal_doubleq",
"strict_rule"
]
class @Parser
length: 0
cache : []
state : []
counter: []
Node : null
proxy : null
proxy2: null
go : (token_list_list)->
@cache= []
@state= []
@counter= []
@length = token_list_list.length
return [] if @length == 0
@Node = token_list_list[0]?[0]?.constructor
@proxy= new @Node
@proxy2= new @Node
for token_list,idx in token_list_list
stub = new Array 62
for k in [0 ... 62]
stub[k] = []
for token in token_list
token.a = idx
token.b = idx+1
if -1 != stub_idx = hash_key_list.idx token.mx_hash.hash_key
stub[stub_idx].push token
stub[0].upush token
@cache.push stub
@state.push state_stub.slice()
@counter.push counter_stub.slice()
# one const rule opt
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "!"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u1"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "-"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_priorityE1__u2"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
for token_list,idx in token_list_list
token = token_list[0]
continue if token.value != "+"
node = new @Node
node.value_array.push token
# COPYPASTE
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XP_priorityE1__u3"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 1
mx_hash_stub["priority"] = 1
node.a = node.value_array[0].a
node.b = node.value_array.last().b
# TODO у ret могут быть и другие правила, потому не надо сразу засырать cache
_pos_list = @cache[idx]
if !_pos_list[1]?
_pos_list[1] = []
_pos_list[1].push node
@fsm()
list = @cache[0][11]
max_token = token_list_list.length
filter_list = []
for v in list
if v.b == max_token
@node_fix v
filter_list.push v
# Прим. А все ошибки, почему не прошло ... смотрим и анализируем @cache
filter_list
node_fix : (node)->
walk = (node)->
vv_list = []
max_depth = -1
for v in node.value_array
walk v
max_depth = Math.max max_depth, v.depth
node.depth = max_depth + 1
if node.depth < 10 # HARDCODE !!!
for v in node.value_array
vv_list.push v.value_view or v.value
node.value_view = vv_list.join ' '
return
walk node
return
fsm : ()->
FAcache = @cache
FAstate = @state
FAcounter = @counter
stack = [
[
11
0
0
]
]
FAstate[0][11] = STATE_RQ
length = @length
request_make = (token_hki, pos, is_new)->
state = FAstate[pos][token_hki]
switch state
when 0 # STATE_NA
if is_new
### !pragma coverage-skip-block ###
throw new Error 'invalid call. STATE_NA + is_new'
stack.push [token_hki, pos, is_new]
FAstate[pos][token_hki] = STATE_RQ
return true
when 1 # STATE_RQ
FAstate[pos][token_hki] = STATE_IG
return false
when 2 # STATE_IG
# stack.push [token_hki, pos, is_new]
return false
when 3 # STATE_FL
FAstate[pos][token_hki] = STATE_RQ
stack.push [token_hki, pos, is_new]
return true
return
# TODO remove
safe_collect = (dst, src)->
# TODO hash[candidate.b] optimization
# Вместо того, чтобы проходить всегда можно спросить а есть ли такой длинны уже найденый токен
# И хранить можно hash или массив b и быстро спрашивать по надобности
# В случае хэша, там же можно хранить только токены такой длинны
for candidate in src
found = false
for chk in dst
# continue if chk.b != candidate.b
c_varr = candidate.value_array
continue if chk.value_array.length != c_varr.length
match = true
for chk_v,idx in chk.value_array
if chk_v != c_varr[idx]
match = false
break
if match
found = true
break
if !found
dst.push candidate
return
while cur = stack.pop()
[
hki
start_pos
only_new
] = cur
continue if start_pos >= length
switch hki
when 0
### token__ queue ###
stack.push [
12
start_pos
only_new
]
when 12
### token__ collect ###
node_list = []
FAstate[start_pos][0] = STATE_FL
FAcache[start_pos][0].uappend node_list
when 1
### token_pre_op queue ###
stack.push [
13
start_pos
only_new
]
when 13
### token_pre_op collect ###
node_list = []
FAstate[start_pos][1] = STATE_FL
FAcache[start_pos][1].uappend node_list
when 2
### token_bin_op queue ###
stack.push [
22
start_pos
only_new
]
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
stack.push [
14
start_pos
only_new
]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
stack.push [
16
start_pos
only_new
]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
stack.push [
18
start_pos
only_new
]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
stack.push [
20
start_pos
only_new
]
when 22
### token_bin_op collect ###
node_list = []
### rule_XSXXX_priorityE5__right_assocE1__u4 ###
node_list.append FAcache[start_pos][14]
### rule_XPXXX_priorityE6__right_assocE1__u5 ###
node_list.append FAcache[start_pos][16]
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 ###
node_list.append FAcache[start_pos][18]
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 ###
node_list.append FAcache[start_pos][20]
FAstate[start_pos][2] = STATE_FL
FAcache[start_pos][2].uappend node_list
when 3
### token_access_rvalue queue ###
stack.push [
29
start_pos
only_new
]
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
stack.push [
23
start_pos
only_new
]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
stack.push [
25
start_pos
only_new
]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
stack.push [
27
start_pos
only_new
]
when 29
### token_access_rvalue collect ###
node_list = []
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 ###
node_list.append FAcache[start_pos][23]
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 ###
node_list.append FAcache[start_pos][25]
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 ###
node_list.append FAcache[start_pos][27]
FAstate[start_pos][3] = STATE_FL
FAcache[start_pos][3].uappend node_list
when 4
### token_dollar_id queue ###
stack.push [
30
start_pos
only_new
]
when 30
### token_dollar_id collect ###
node_list = []
FAstate[start_pos][4] = STATE_FL
FAcache[start_pos][4].uappend node_list
when 5
### token_hash_id queue ###
stack.push [
31
start_pos
only_new
]
when 31
### token_hash_id collect ###
node_list = []
FAstate[start_pos][5] = STATE_FL
FAcache[start_pos][5].uappend node_list
when 6
### token_rvalue queue ###
stack.push [
54
start_pos
only_new
]
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
stack.push [
32
start_pos
only_new
]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
stack.push [
34
start_pos
only_new
]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
stack.push [
36
start_pos
only_new
]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
stack.push [
38
start_pos
only_new
]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
stack.push [
40
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
stack.push [
42
start_pos
only_new
]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
stack.push [
44
start_pos
only_new
]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
stack.push [
46
start_pos
only_new
]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
stack.push [
48
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
stack.push [
50
start_pos
only_new
]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
stack.push [
52
start_pos
only_new
]
when 54
### token_rvalue collect ###
node_list = []
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 ###
node_list.append FAcache[start_pos][32]
### rule_Hnumber_priorityEX9000_ultEvalue__u11 ###
node_list.append FAcache[start_pos][34]
### rule_Hid_priorityEX9000_ultEwrap_string__u12 ###
node_list.append FAcache[start_pos][36]
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 ###
node_list.append FAcache[start_pos][38]
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 ###
node_list.append FAcache[start_pos][40]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 ###
node_list.append FAcache[start_pos][42]
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 ###
node_list.append FAcache[start_pos][44]
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 ###
node_list.append FAcache[start_pos][46]
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 ###
node_list.append FAcache[start_pos][48]
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 ###
node_list.append FAcache[start_pos][50]
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 ###
node_list.append FAcache[start_pos][52]
append_list = FAcache[start_pos][6]
has_new = false
for node in node_list
if append_list.has node
node._is_new = false
else
node._is_new = true
append_list.push node
has_new = true
state = FAstate[start_pos][6]
FAstate[start_pos][6] = STATE_FL
if state == STATE_IG
if has_new
# recursive case
FAstate[start_pos][6] = STATE_RQ
stack.push [
6
start_pos
1
]
request_make 6, start_pos, 1
when 7
### token_number queue ###
stack.push [
55
start_pos
only_new
]
when 55
### token_number collect ###
node_list = []
FAstate[start_pos][7] = STATE_FL
FAcache[start_pos][7].uappend node_list
when 8
### token_id queue ###
stack.push [
56
start_pos
only_new
]
when 56
### token_id collect ###
node_list = []
FAstate[start_pos][8] = STATE_FL
FAcache[start_pos][8].uappend node_list
when 9
### token_string_literal_singleq queue ###
stack.push [
57
start_pos
only_new
]
when 57
### token_string_literal_singleq collect ###
node_list = []
FAstate[start_pos][9] = STATE_FL
FAcache[start_pos][9].uappend node_list
when 10
### token_string_literal_doubleq queue ###
stack.push [
58
start_pos
only_new
]
when 58
### token_string_literal_doubleq collect ###
node_list = []
FAstate[start_pos][10] = STATE_FL
FAcache[start_pos][10].uappend node_list
when 11
### token_strict_rule queue ###
stack.push [
61
start_pos
only_new
]
### rule_Hrvalue_ultEdeep__u22 ###
stack.push [
59
start_pos
only_new
]
when 61
### token_strict_rule collect ###
node_list = []
### rule_Hrvalue_ultEdeep__u22 ###
node_list.append FAcache[start_pos][59]
FAstate[start_pos][11] = STATE_FL
FAcache[start_pos][11].uappend node_list
when 14
### rule_XSXXX_priorityE5__right_assocE1__u4 queue ###
chk_len = stack.push [
14
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][0] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][1] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 15
when 15
### rule_XSXXX_priorityE5__right_assocE1__u4 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][2] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "*"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][2] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][3] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "/"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][3] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XSXXX_priorityE5__right_assocE1__u4"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 5
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][14].append ret_list
#safe_collect FAcache[start_pos][14], ret_list
when 16
### rule_XPXXX_priorityE6__right_assocE1__u5 queue ###
chk_len = stack.push [
16
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][4] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][5] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 17
when 17
### rule_XPXXX_priorityE6__right_assocE1__u5 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][6] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "+"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][6] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][7] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "-"
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][7] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XPXXX_priorityE6__right_assocE1__u5"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 6
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][16].append ret_list
#safe_collect FAcache[start_pos][16], ret_list
when 18
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 queue ###
chk_len = stack.push [
18
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][8] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][9] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][10] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][11] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][12] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][13] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][14] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 19
when 19
### rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][15] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][15] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][16] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][16] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][17] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][17] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][18] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '>='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][18] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][19] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '!='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][19] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][20] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '<>'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][20] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][21] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '=='
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][21] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXEXXXXXXXXEXXXXEXXXXXXXXEEX_priorityE9__u6"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 9
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][18].append ret_list
#safe_collect FAcache[start_pos][18], ret_list
when 20
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 queue ###
chk_len = stack.push [
20
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][22] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][23] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][24] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][25] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
node.value_array.length -= tok_list.length
if chk_len == stack.length
stack[chk_len-1][0] = 21
when 21
### rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
hyp_list_1 = []
old_node = node
node = @proxy
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][26] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][26] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][27] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '&&'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][27] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][28] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '|'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][28] = list_1.length
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][29] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != '||'
b_1 = tok.b
node.value_array.push tok
hyp_list_1.push node.value_array.clone()
node.value_array.pop()
FAcounter[b_0][29] = list_1.length
node = old_node
for tok_list in hyp_list_1
node.value_array.append tok_list
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XXXXXXXXXXXXXXXXX_priorityE10_right_assocE1__u7"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 2
mx_hash_stub["priority"] = 10
mx_hash_stub["right_assoc"] = 1
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.length -= tok_list.length
FAcache[start_pos][20].append ret_list
#safe_collect FAcache[start_pos][20], ret_list
when 23
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 queue ###
chk_len = stack.push [
23
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][4]
if state_1 != STATE_FL
if request_make 4, b_0, 0
continue
list_1 = FAcache[b_0][4]
if chk_len == stack.length
stack[chk_len-1][0] = 24
when 24
### rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][4]
for idx_1 in [FAcounter[b_0][30] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hdollar_id_priorityEX9000_ultEdollar_id__u8"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "dollar_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][30] = list_1.length
FAcache[start_pos][23].append ret_list
#safe_collect FAcache[start_pos][23], ret_list
when 25
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 queue ###
chk_len = stack.push [
25
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
if chk_len == stack.length
stack[chk_len-1][0] = 26
when 26
### rule_Hhash_id_priorityEX9000_ultEhash_id__u9 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][31] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_priorityEX9000_ultEhash_id__u9"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_id"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][31] = list_1.length
FAcache[start_pos][25].append ret_list
#safe_collect FAcache[start_pos][25], ret_list
when 27
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 queue ###
chk_len = stack.push [
27
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][5]
if state_1 != STATE_FL
if request_make 5, b_0, 0
continue
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][33] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 28
when 28
### rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][5]
for idx_1 in [FAcounter[b_0][37] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != "]"
b_4 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hhash_id_XX_Hnumber_XX_priorityEX9000_ultEhash_array_access__u19"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 3
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "hash_array_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][37] = list_1.length
FAcache[start_pos][27].append ret_list
#safe_collect FAcache[start_pos][27], ret_list
when 32
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 queue ###
chk_len = stack.push [
32
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
if chk_len == stack.length
stack[chk_len-1][0] = 33
when 33
### rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][38] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_priorityEX9000_ultEaccess_rvalue__u10"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "access_rvalue"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][38] = list_1.length
FAcache[start_pos][32].append ret_list
#safe_collect FAcache[start_pos][32], ret_list
when 34
### rule_Hnumber_priorityEX9000_ultEvalue__u11 queue ###
chk_len = stack.push [
34
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][7]
if state_1 != STATE_FL
if request_make 7, b_0, 0
continue
list_1 = FAcache[b_0][7]
if chk_len == stack.length
stack[chk_len-1][0] = 35
when 35
### rule_Hnumber_priorityEX9000_ultEvalue__u11 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][7]
for idx_1 in [FAcounter[b_0][39] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hnumber_priorityEX9000_ultEvalue__u11"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][39] = list_1.length
FAcache[start_pos][34].append ret_list
#safe_collect FAcache[start_pos][34], ret_list
when 36
### rule_Hid_priorityEX9000_ultEwrap_string__u12 queue ###
chk_len = stack.push [
36
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][8]
if state_1 != STATE_FL
if request_make 8, b_0, 0
continue
list_1 = FAcache[b_0][8]
if chk_len == stack.length
stack[chk_len-1][0] = 37
when 37
### rule_Hid_priorityEX9000_ultEwrap_string__u12 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][8]
for idx_1 in [FAcounter[b_0][40] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hid_priorityEX9000_ultEwrap_string__u12"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "wrap_string"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][40] = list_1.length
FAcache[start_pos][36].append ret_list
#safe_collect FAcache[start_pos][36], ret_list
when 38
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 queue ###
chk_len = stack.push [
38
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][9]
if state_1 != STATE_FL
if request_make 9, b_0, 0
continue
list_1 = FAcache[b_0][9]
if chk_len == stack.length
stack[chk_len-1][0] = 39
when 39
### rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][9]
for idx_1 in [FAcounter[b_0][41] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_singleq_priorityEX9000_ultEvalue__u13"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][41] = list_1.length
FAcache[start_pos][38].append ret_list
#safe_collect FAcache[start_pos][38], ret_list
when 40
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 queue ###
chk_len = stack.push [
40
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][10]
if state_1 != STATE_FL
if request_make 10, b_0, 0
continue
list_1 = FAcache[b_0][10]
if chk_len == stack.length
stack[chk_len-1][0] = 41
when 41
### rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][10]
for idx_1 in [FAcounter[b_0][42] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hstring_literal_doubleq_priorityEX9000_ultEvalue__u14"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "value"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][42] = list_1.length
FAcache[start_pos][40].append ret_list
#safe_collect FAcache[start_pos][40], ret_list
when 42
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 queue ###
chk_len = stack.push [
42
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][44] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 43
when 43
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][47] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityXHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_u15"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][47] = list_1.length
FAcache[start_pos][42].append ret_list
#safe_collect FAcache[start_pos][42], ret_list
when 44
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 queue ###
chk_len = stack.push [
44
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][49] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][2]
if state_2 != STATE_FL
if request_make 2, b_1, 0
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][6]
if state_3 != STATE_FL
if request_make 6, b_2, 0
continue
list_3 = FAcache[b_2][6]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 45
when 45
### rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][52] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][2]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][6]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[0].mx_hash.priority==arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !((arg_list[2].mx_hash.priority<arg_list[1].mx_hash.priority))
node.value_array.pop()
continue
if !(arg_list[1].mx_hash.right_assoc)
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_Hbin_op_Hrvalue_priorityEHbin_opXpriority_ultEbin_op_HrvalueX1XXpriorityEEHbin_opXpriority_HrvalueX2XXpriorityXHbin_opXpriority_Hbin_opXright_assoc_u16"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[1].mx_hash.priority
mx_hash_stub["ult"] = "bin_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][52] = list_1.length
FAcache[start_pos][44].append ret_list
#safe_collect FAcache[start_pos][44], ret_list
when 46
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 queue ###
chk_len = stack.push [
46
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][1]
if state_1 != STATE_FL
if request_make 1, b_0, 0
continue
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][53] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 47
when 47
### rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][1]
for idx_1 in [FAcounter[b_0][55] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
arg_list = node.value_array
if !((arg_list[1].mx_hash.priority<=arg_list[0].mx_hash.priority))
node.value_array.pop()
continue
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hpre_op_Hrvalue_priorityEHpre_opXpriority_ultEpre_op_HrvalueX1XXpriorityXEHpre_opXpriority_u17"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = arg_list[0].mx_hash.priority
mx_hash_stub["ult"] = "pre_op"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][55] = list_1.length
FAcache[start_pos][46].append ret_list
#safe_collect FAcache[start_pos][46], ret_list
when 48
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 queue ###
chk_len = stack.push [
48
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][56] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
state_2 = FAstate[b_1][6]
if state_2 != STATE_FL
if request_make 6, b_1, 0
continue
list_2 = FAcache[b_1][6]
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 49
when 49
### rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][0]
for idx_1 in [FAcounter[b_0][59] ... list_1.length] by 1
tok = list_1[idx_1]
continue if tok.value != "("
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][6]
for tok in list_2
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][0]
for tok in list_3
continue if tok.value != ")"
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_XX_Hrvalue_XX_priorityEX9000_ultEbra__u18"
mx_hash_stub.hash_key = "rPI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "bra"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][59] = list_1.length
FAcache[start_pos][48].append ret_list
#safe_collect FAcache[start_pos][48], ret_list
when 50
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 queue ###
chk_len = stack.push [
50
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][63] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][7]
if state_3 != STATE_FL
if request_make 7, b_2, 0
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
state_5 = FAstate[b_4][7]
if state_5 != STATE_FL
if request_make 7, b_4, 0
continue
list_5 = FAcache[b_4][7]
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 51
when 51
### rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][69] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "["
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][7]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
if b_3 >= length
node.value_array.pop()
continue
list_4 = FAcache[b_3][0]
for tok in list_4
continue if tok.value != ":"
b_4 = tok.b
node.value_array.push tok
if b_4 >= length
node.value_array.pop()
continue
list_5 = FAcache[b_4][7]
for tok in list_5
b_5 = tok.b
node.value_array.push tok
if b_5 >= length
node.value_array.pop()
continue
list_6 = FAcache[b_5][0]
for tok in list_6
continue if tok.value != "]"
b_6 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hnumber_XX_Hnumber_XX_priorityEX9000_ultEslice_access__u20"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "slice_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][69] = list_1.length
FAcache[start_pos][50].append ret_list
#safe_collect FAcache[start_pos][50], ret_list
when 52
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 queue ###
chk_len = stack.push [
52
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][3]
if state_1 != STATE_FL
if request_make 3, b_0, 0
continue
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][71] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
state_3 = FAstate[b_2][8]
if state_3 != STATE_FL
if request_make 8, b_2, 0
continue
list_3 = FAcache[b_2][8]
node.value_array.pop()
node.value_array.pop()
if chk_len == stack.length
stack[chk_len-1][0] = 53
when 53
### rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][3]
for idx_1 in [FAcounter[b_0][74] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
if b_1 >= length
node.value_array.pop()
continue
list_2 = FAcache[b_1][0]
for tok in list_2
continue if tok.value != "."
b_2 = tok.b
node.value_array.push tok
if b_2 >= length
node.value_array.pop()
continue
list_3 = FAcache[b_2][8]
for tok in list_3
b_3 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Haccess_rvalue_XX_Hid_priorityEX9000_ultEfield_access__u21"
mx_hash_stub.hash_key = "rvalue"
mx_hash_stub.hash_key_idx = 6
mx_hash_stub["priority"] = -9000
mx_hash_stub["ult"] = "field_access"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
node.value_array.pop()
node.value_array.pop()
FAcounter[b_0][74] = list_1.length
FAcache[start_pos][52].append ret_list
#safe_collect FAcache[start_pos][52], ret_list
when 59
### rule_Hrvalue_ultEdeep__u22 queue ###
chk_len = stack.push [
59
start_pos
only_new
]
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
state_1 = FAstate[b_0][6]
if state_1 != STATE_FL
if request_make 6, b_0, 0
continue
list_1 = FAcache[b_0][6]
if chk_len == stack.length
stack[chk_len-1][0] = 60
when 60
### rule_Hrvalue_ultEdeep__u22 collect ###
ret_list = []
b_0 = start_pos
node = @proxy2
node.value_array.clear()
node.a = start_pos
list_1 = FAcache[b_0][6]
for idx_1 in [FAcounter[b_0][75] ... list_1.length] by 1
tok = list_1[idx_1]
b_1 = tok.b
node.value_array.push tok
arg_list = node.value_array
mx_hash_stub = node.mx_hash = {}
mx_hash_stub.rule = "rule_Hrvalue_ultEdeep__u22"
mx_hash_stub.hash_key = "PI:KEY:<KEY>END_PI"
mx_hash_stub.hash_key_idx = 11
mx_hash_stub["ult"] = "deep"
node.b = node.value_array.last().b
ret_list.push node.clone()
node.value_array.pop()
FAcounter[b_0][75] = list_1.length
FAcache[start_pos][59].append ret_list
#safe_collect FAcache[start_pos][59], ret_list
return
# ###################################################################################################
parser = new module.Parser
@parse = (str)->
tok_list = tokenizer.go str
res_list = parser.go tok_list
# debug
@tokenizer = tokenizer
@parser = parser
|
[
{
"context": "\timporterPhone: '(495) 9210326'\n\t\timporterEmail: 'np@newproducts.ru'\n\n\t\texportDepartment: 'EXPORT DEPARTMENT'\n\t\texpor",
"end": 693,
"score": 0.9999299645423889,
"start": 676,
"tag": "EMAIL",
"value": "np@newproducts.ru"
},
{
"context": "rtDepartment: 'EXPORT ... | locale/en.coffee | winnlab/Polpharma | 0 | module.exports =
checkAge: 'ARE YOU OVER 18 YEARS OLD?'
yes: 'Yes'
no: 'No'
healthWarn: 'Excessive consumption of alcohol harm your health'
consume: 'consume <span class="clearfix"></span> reasonable'
allCocktails: 'All cocktails'
bottle: 'Bottle'
can: 'Can'
menu: 'Menu'
close: 'Close'
contacts:
contacts: 'Contacts'
mainOffice: 'Main office'
postAddress: '01601, Kyiv'
address: 'Sportyvna sq, 3'
phone: '044 502 99 00'
importerInRF: 'Importer in RF'
novyeProducty: '"Novye Producty"'
importerPlacement: 'Russian Federation, 107078, Moscow'
importerAddress: 'Novaya Basmannaya str. 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: 'np@newproducts.ru'
exportDepartment: 'EXPORT DEPARTMENT'
exportEmail: 'korniyuk@newproducts.ua'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'share'
moment: 'moment'
download: 'download'
ringtone: 'ringtone'
newPodcast: 'new'
by: 'by'
allPodcasts: 'All podcasts'
back: 'Back' | 54149 | module.exports =
checkAge: 'ARE YOU OVER 18 YEARS OLD?'
yes: 'Yes'
no: 'No'
healthWarn: 'Excessive consumption of alcohol harm your health'
consume: 'consume <span class="clearfix"></span> reasonable'
allCocktails: 'All cocktails'
bottle: 'Bottle'
can: 'Can'
menu: 'Menu'
close: 'Close'
contacts:
contacts: 'Contacts'
mainOffice: 'Main office'
postAddress: '01601, Kyiv'
address: 'Sportyvna sq, 3'
phone: '044 502 99 00'
importerInRF: 'Importer in RF'
novyeProducty: '"Novye Producty"'
importerPlacement: 'Russian Federation, 107078, Moscow'
importerAddress: 'Novaya Basmannaya str. 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: '<EMAIL>'
exportDepartment: 'EXPORT DEPARTMENT'
exportEmail: '<EMAIL>'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'share'
moment: 'moment'
download: 'download'
ringtone: 'ringtone'
newPodcast: 'new'
by: 'by'
allPodcasts: 'All podcasts'
back: 'Back' | true | module.exports =
checkAge: 'ARE YOU OVER 18 YEARS OLD?'
yes: 'Yes'
no: 'No'
healthWarn: 'Excessive consumption of alcohol harm your health'
consume: 'consume <span class="clearfix"></span> reasonable'
allCocktails: 'All cocktails'
bottle: 'Bottle'
can: 'Can'
menu: 'Menu'
close: 'Close'
contacts:
contacts: 'Contacts'
mainOffice: 'Main office'
postAddress: '01601, Kyiv'
address: 'Sportyvna sq, 3'
phone: '044 502 99 00'
importerInRF: 'Importer in RF'
novyeProducty: '"Novye Producty"'
importerPlacement: 'Russian Federation, 107078, Moscow'
importerAddress: 'Novaya Basmannaya str. 9/2-4, 6,'
importerPhone: '(495) 9210326'
importerEmail: 'PI:EMAIL:<EMAIL>END_PI'
exportDepartment: 'EXPORT DEPARTMENT'
exportEmail: 'PI:EMAIL:<EMAIL>END_PI'
exportPhone: '+38 (067) 5484945'
shakeit:
share: 'share'
moment: 'moment'
download: 'download'
ringtone: 'ringtone'
newPodcast: 'new'
by: 'by'
allPodcasts: 'All podcasts'
back: 'Back' |
[
{
"context": "#\r\n# Author: Corey Auger\r\n# corey@nxtwv.com\r\n#\r\n\r\nplayWSComet = window.ang",
"end": 24,
"score": 0.9998841285705566,
"start": 13,
"tag": "NAME",
"value": "Corey Auger"
},
{
"context": "#\r\n# Author: Corey Auger\r\n# corey@nxtwv.com\r\n#\r\n\r\nplayWSComet = w... | app/assets/javascripts/app.coffee | coreyauger/play-websocket-comet | 1 | #
# Author: Corey Auger
# corey@nxtwv.com
#
playWSComet = window.angular.module('playWSComet', ['ngRoute','ngSanitize','ui.bootstrap','playWSCometControllers']);
playWSComet.config(($locationProvider,$routeProvider) ->
# $locationProvider.html5Mode(true);
$routeProvider.when('/home',
templateUrl: '/assets/partials/home.html',
controller: 'HomeCtrl'
).when('/slides/:username',
templateUrl: '/assets/partials/slides.html',
controller: 'SlideCtrl'
).otherwise(
redirectTo: '/home'
)
)
playWSComet.run(($rootScope, $location, worker, $modal) ->
isDesktop = self.window.innerWidth > 700;
$rootScope.isDesktop = isDesktop;
# TODO: HACK fix me
$rootScope.$on('webrtc', (event, data) ->
console.log('GOT WebRTC ' + data);
frame = document.getElementById("appframe").contentWindow
frame.postMessage(JSON.stringify(data.msg),'http://'+self.location.host)
)
$rootScope.back = -> window.history.back()
$rootScope.nav = (path) -> $location.path(path)
$rootScope.loading = true
$rootScope.launchCallModal = (friendid) ->
$rootScope.friendId = friendid;
modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
backdrop: true,
resolve:
friendId: ->
#return $sce.trustAsUrl( '/apps/webrtc/531f4bc0042a2c7483af19d8');
#return $sce.trustAsUrl( '/webrtc/' + $rootScope.friendId );
return $rootScope.friendId
})
modalInstance.result.then((selectedItem) ->
$rootScope.selected = selectedItem
, ->
console.log('Modal dismissed at: ' + new Date());
)
# Please note that $modalInstance represents a modal window (instance) dependency.
# It is not the same as the $modal service used above.
ModalInstanceCtrl = ($scope, $modalInstance, friendId) ->
#$scope.friendId = $sce.getTrustedUrl(friendId);
$scope.friendId = friendId
window._webrtc = new WebRTC(worker, friendId)
$scope.ok = -> $modalInstance.close($scope.friendId)
$scope.cancel = ->
window._webrtc.onHangup()
$modalInstance.dismiss('cancel')
window._webrtc.webrtcOnUserMediaSuccess = ->
worker.work('notification','notification',{actors:[friendId],app:{id:'webrtc'}})
$modalInstance.close($scope.friendId)
window._webrtc.webrtcOnUserMediaFail = ->
$modalInstance.dismiss('cancel');
setTimeout( ->
window._webrtc.webRtcInitialize()
,1000)
)
playWSComet.directive('resize', ($window) ->
(scope, element) ->
w = angular.element($window)
scope.getWindowDimensions = ->
return { 'h': w.height(), 'w': w.width() }
scope.$watch(scope.getWindowDimensions, (newValue, oldValue) ->
scope.windowHeight = newValue.h
scope.windowWidth = newValue.w
if( typeof Android == 'undefined' )
scope.chatHeight = newValue.h - 170
else
scope.chatHeight = newValue.h
scope.style = ->
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'}
, true);
w.bind('resize', -> scope.$apply())
)
| 161228 | #
# Author: <NAME>
# <EMAIL>
#
playWSComet = window.angular.module('playWSComet', ['ngRoute','ngSanitize','ui.bootstrap','playWSCometControllers']);
playWSComet.config(($locationProvider,$routeProvider) ->
# $locationProvider.html5Mode(true);
$routeProvider.when('/home',
templateUrl: '/assets/partials/home.html',
controller: 'HomeCtrl'
).when('/slides/:username',
templateUrl: '/assets/partials/slides.html',
controller: 'SlideCtrl'
).otherwise(
redirectTo: '/home'
)
)
playWSComet.run(($rootScope, $location, worker, $modal) ->
isDesktop = self.window.innerWidth > 700;
$rootScope.isDesktop = isDesktop;
# TODO: HACK fix me
$rootScope.$on('webrtc', (event, data) ->
console.log('GOT WebRTC ' + data);
frame = document.getElementById("appframe").contentWindow
frame.postMessage(JSON.stringify(data.msg),'http://'+self.location.host)
)
$rootScope.back = -> window.history.back()
$rootScope.nav = (path) -> $location.path(path)
$rootScope.loading = true
$rootScope.launchCallModal = (friendid) ->
$rootScope.friendId = friendid;
modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
backdrop: true,
resolve:
friendId: ->
#return $sce.trustAsUrl( '/apps/webrtc/531f4bc0042a2c7483af19d8');
#return $sce.trustAsUrl( '/webrtc/' + $rootScope.friendId );
return $rootScope.friendId
})
modalInstance.result.then((selectedItem) ->
$rootScope.selected = selectedItem
, ->
console.log('Modal dismissed at: ' + new Date());
)
# Please note that $modalInstance represents a modal window (instance) dependency.
# It is not the same as the $modal service used above.
ModalInstanceCtrl = ($scope, $modalInstance, friendId) ->
#$scope.friendId = $sce.getTrustedUrl(friendId);
$scope.friendId = friendId
window._webrtc = new WebRTC(worker, friendId)
$scope.ok = -> $modalInstance.close($scope.friendId)
$scope.cancel = ->
window._webrtc.onHangup()
$modalInstance.dismiss('cancel')
window._webrtc.webrtcOnUserMediaSuccess = ->
worker.work('notification','notification',{actors:[friendId],app:{id:'webrtc'}})
$modalInstance.close($scope.friendId)
window._webrtc.webrtcOnUserMediaFail = ->
$modalInstance.dismiss('cancel');
setTimeout( ->
window._webrtc.webRtcInitialize()
,1000)
)
playWSComet.directive('resize', ($window) ->
(scope, element) ->
w = angular.element($window)
scope.getWindowDimensions = ->
return { 'h': w.height(), 'w': w.width() }
scope.$watch(scope.getWindowDimensions, (newValue, oldValue) ->
scope.windowHeight = newValue.h
scope.windowWidth = newValue.w
if( typeof Android == 'undefined' )
scope.chatHeight = newValue.h - 170
else
scope.chatHeight = newValue.h
scope.style = ->
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'}
, true);
w.bind('resize', -> scope.$apply())
)
| true | #
# Author: PI:NAME:<NAME>END_PI
# PI:EMAIL:<EMAIL>END_PI
#
playWSComet = window.angular.module('playWSComet', ['ngRoute','ngSanitize','ui.bootstrap','playWSCometControllers']);
playWSComet.config(($locationProvider,$routeProvider) ->
# $locationProvider.html5Mode(true);
$routeProvider.when('/home',
templateUrl: '/assets/partials/home.html',
controller: 'HomeCtrl'
).when('/slides/:username',
templateUrl: '/assets/partials/slides.html',
controller: 'SlideCtrl'
).otherwise(
redirectTo: '/home'
)
)
playWSComet.run(($rootScope, $location, worker, $modal) ->
isDesktop = self.window.innerWidth > 700;
$rootScope.isDesktop = isDesktop;
# TODO: HACK fix me
$rootScope.$on('webrtc', (event, data) ->
console.log('GOT WebRTC ' + data);
frame = document.getElementById("appframe").contentWindow
frame.postMessage(JSON.stringify(data.msg),'http://'+self.location.host)
)
$rootScope.back = -> window.history.back()
$rootScope.nav = (path) -> $location.path(path)
$rootScope.loading = true
$rootScope.launchCallModal = (friendid) ->
$rootScope.friendId = friendid;
modalInstance = $modal.open({
templateUrl: 'myModalContent.html',
controller: ModalInstanceCtrl,
backdrop: true,
resolve:
friendId: ->
#return $sce.trustAsUrl( '/apps/webrtc/531f4bc0042a2c7483af19d8');
#return $sce.trustAsUrl( '/webrtc/' + $rootScope.friendId );
return $rootScope.friendId
})
modalInstance.result.then((selectedItem) ->
$rootScope.selected = selectedItem
, ->
console.log('Modal dismissed at: ' + new Date());
)
# Please note that $modalInstance represents a modal window (instance) dependency.
# It is not the same as the $modal service used above.
ModalInstanceCtrl = ($scope, $modalInstance, friendId) ->
#$scope.friendId = $sce.getTrustedUrl(friendId);
$scope.friendId = friendId
window._webrtc = new WebRTC(worker, friendId)
$scope.ok = -> $modalInstance.close($scope.friendId)
$scope.cancel = ->
window._webrtc.onHangup()
$modalInstance.dismiss('cancel')
window._webrtc.webrtcOnUserMediaSuccess = ->
worker.work('notification','notification',{actors:[friendId],app:{id:'webrtc'}})
$modalInstance.close($scope.friendId)
window._webrtc.webrtcOnUserMediaFail = ->
$modalInstance.dismiss('cancel');
setTimeout( ->
window._webrtc.webRtcInitialize()
,1000)
)
playWSComet.directive('resize', ($window) ->
(scope, element) ->
w = angular.element($window)
scope.getWindowDimensions = ->
return { 'h': w.height(), 'w': w.width() }
scope.$watch(scope.getWindowDimensions, (newValue, oldValue) ->
scope.windowHeight = newValue.h
scope.windowWidth = newValue.w
if( typeof Android == 'undefined' )
scope.chatHeight = newValue.h - 170
else
scope.chatHeight = newValue.h
scope.style = ->
return {
'height': (newValue.h - 100) + 'px',
'width': (newValue.w - 100) + 'px'}
, true);
w.bind('resize', -> scope.$apply())
)
|
[
{
"context": " sortable_id: \"getty-museum\"\n name: \"J. Paul Getty Museum\"\n default_profile_id: \"getty\"\n icon:\n",
"end": 500,
"score": 0.9998804330825806,
"start": 480,
"tag": "NAME",
"value": "J. Paul Getty Museum"
},
{
"context": "ault_profile_id: \... | src/desktop/test/models/profile.test.coffee | jo-rs/force | 0 | _ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
sd = require('sharify').data
should = require 'should'
Backbone = require 'backbone'
Profile = require '../../models/profile'
sinon = require 'sinon'
describe 'Profile', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@profile = new Profile(fabricate('partner_profile',
owner_type: 'PartnerInstitution'
owner:
type: "Institution"
sortable_id: "getty-museum"
name: "J. Paul Getty Museum"
default_profile_id: "getty"
icon:
id: "51eefb79275b2420810001fe",
image_filename: "GGLogo1.jpg",
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "square140" ]
x: 0
y: 0
width: 140
))
afterEach ->
Backbone.sync.restore()
describe '#isUserClass', ->
it 'returns is-user if the profile is a user and is set to use a circular default icon', ->
@profile.isUserClass().should.equal 'is-partner'
@profile.set owner_type: 'User'
@profile.set default_icon_version: 'circle'
@profile.isUserClass().should.equal 'is-user'
describe '#iconImageUrl', ->
it "returns the icon url for the model's default icon version", ->
@profile.iconImageUrl().should.containEql "square"
describe '#hasIconImage', ->
it 'returns true if profile has an icon', ->
@profile.hasIconImage().should.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', null
@profile.hasIconImage().should.not.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', id: '51eefb79275b2420810001fe'
@profile.hasIconImage().should.not.be.ok()
describe '#bestAvailableImage', ->
it "returns the icon image url if there is no cover", ->
@profile.unset 'cover_image'
@profile.bestAvailableImage().should.containEql("square")
it "returns the cover image url for medium250x165 if it exists", ->
@profile.set
cover_image:
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "medium250x165" ]
@profile.bestAvailableImage().should.containEql('medium250x165')
describe '#alphaSortKey', ->
it "returns the profile owner's display name", ->
@profile.alphaSortKey().should.equal @profile.displayName()
describe '#href', ->
it "returns the client link to this profile", ->
@profile.href().should.containEql "/#{@profile.get('id')}"
describe '#displayName', ->
it "returns the profile owner's display name", ->
@profile.displayName().should.equal @profile.related().owner.get('name')
describe '#isFairOrOrganizer', ->
it "returns true if the profile belongs to either a Fair or a Fair Organizer", ->
@profile.set 'owner_type', 'Fair'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'FairOrganizer'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'User'
@profile.isFairOrOrganizer().should.be.false()
describe '#isPartner', ->
it "returns true if the profile does not belong to a User or Admin", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.isPartner().should.be.true()
@profile.set 'owner_type', 'Admin'
@profile.isPartner().should.be.false()
@profile.set 'owner_type', 'User'
@profile.isPartner().should.be.false()
describe '#defaultIconInitials', ->
it "returns up to two initials for a partner name", ->
@profile.defaultIconInitials().should.equal "JP"
@profile.related().owner.set 'name', "Whitney"
@profile.defaultIconInitials().should.equal "W"
@profile.related().owner.set 'name', "John Jacob Jingle Heimer Schmidt"
@profile.defaultIconInitials().should.equal "JJ"
it "does not include non-word characters", ->
@profile.related().owner.set 'name', "Chime & Read"
@profile.defaultIconInitials().should.equal "CR"
@profile.related().owner.set 'name', "2 % Johan _ Gregor 37"
@profile.defaultIconInitials().should.equal "2J"
describe 'related owner', ->
it "creates PartnerGallery", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates PartnerInstitution", ->
@profile.set 'owner_type', 'PartnerInstitution'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates User", ->
@profile.set 'owner_type', 'User'
@profile.related().owner.constructor.name.should.equal 'User'
it "creates Fair", ->
@profile.set 'owner_type', 'Fair'
@profile.related().owner.constructor.name.should.equal 'Fair'
it "creates FairOrganizer", ->
@profile.set 'owner_type', 'FairOrganizer'
@profile.related().owner.constructor.name.should.equal 'FairOrganizer'
describe '#formatFollowText', ->
it 'returns formatted follows text', ->
@profile.set follows_count: 1234567
@profile.formatFollowText().should.equal '1,234,567 Followers'
describe '#getFormattedWebsite', ->
it 'formats website', ->
@profile.set website: 'https://artsy.net'
@profile.getFormattedWebsite().should.equal 'artsy.net'
describe '#metaTitle', ->
it 'correctly formats title for users', ->
@profile.set owner_type: 'User'
@profile.metaTitle().should.equal 'J. Paul Getty Museum | Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaTitle().should.equal 'J. Paul Getty Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('overview').should.equal 'J. Paul Getty Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('contact').should.equal 'J. Paul Getty Museum | Contact Information | Artsy'
@profile.metaTitle('about').should.equal 'J. Paul Getty Museum | Visitor Information | Artsy'
@profile.metaTitle('collection').should.equal 'J. Paul Getty Museum | Collection | Artsy'
@profile.metaTitle('shop').should.equal 'J. Paul Getty Museum | Shop | Artsy'
@profile.metaTitle('shows').should.equal 'J. Paul Getty Museum | Shows | Artsy'
@profile.metaTitle('artists').should.equal 'J. Paul Getty Museum | Artists | Artsy'
@profile.metaTitle('artist').should.equal 'J. Paul Getty Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('posts').should.equal 'J. Paul Getty Museum | Posts | Artsy'
it 'correctly formats title for non-gallery partners', ->
@profile.set owner_type: 'PartnerInstitution'
@profile.metaTitle().should.equal 'J. Paul Getty Museum | Artists, Artworks, and Contact Info | Artsy'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaTitle().should.equal 'J. Paul Getty Museum | Fair Info, Artists, and Art for Sale | Artsy'
@profile.metaTitle('info').should.equal 'J. Paul Getty Museum | Visitor Information | Artsy'
@profile.metaTitle('posts').should.equal 'J. Paul Getty Museum | Highlighted Articles | Artsy'
@profile.metaTitle('forYou').should.equal 'J. Paul Getty Museum | Your Personal Fair Guide | Artsy'
@profile.metaTitle('search').should.equal 'J. Paul Getty Museum | Search | Artsy'
@profile.metaTitle('browse').should.equal 'J. Paul Getty Museum | Browse | Artsy'
@profile.metaTitle('favorites').should.equal 'J. Paul Getty Museum | Favorites | Artsy'
@profile.metaTitle('follows').should.equal 'J. Paul Getty Museum | Following | Artsy'
describe '#metaDescription', ->
it 'correctly formats description', ->
@profile.set('bio', 'bio')
@profile.metaDescription().should.equal 'bio'
@profile.set('bio', undefined)
@profile.metaDescription().should.equal 'J. Paul Getty Museum on Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaDescription().should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('overview').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('contact').should.equal 'Contact information including a map of locations with phone numbers for J. Paul Getty Museum'
@profile.metaDescription('about').should.equal 'Visitor information including location and phone number for J. Paul Getty Museum'
@profile.metaDescription('collection').should.equal 'Artworks in the collection of J. Paul Getty Museum'
@profile.metaDescription('shop').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('shows').should.equal 'List of current, upcoming and past shows at J. Paul Getty Museum'
@profile.metaDescription('artists').should.equal 'List of artists represented by J. Paul Getty Museum'
@profile.metaDescription('artist').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('posts').should.equal 'Articles about and created by J. Paul Getty Museum'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaDescription().should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('info').should.equal "Visitor information including location, tickets and phone number for the fair"
@profile.metaDescription('posts').should.equal 'Featured articles about the fair'
@profile.metaDescription('forYou').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('search').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('browse').should.equal "Browse artworks at the fair by subject matter, style/technique, movement, price, and booth"
@profile.metaDescription('favorites').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('follows').should.equal "The J. Paul Getty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
describe '#fetchFavorites', ->
it 'fetches the saved-artwork collection based on the owner', ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites({})
Backbone.sync.args[0][1].url.should.containEql 'saved-artwork/artworks'
it 'returns feed items with a set url', (done) ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites success: (items) ->
items.url.should.containEql 'saved-artwork/artworks'
done()
Backbone.sync.args[0][2].success [{ id: 'bar' }]
| 10543 | _ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
sd = require('sharify').data
should = require 'should'
Backbone = require 'backbone'
Profile = require '../../models/profile'
sinon = require 'sinon'
describe 'Profile', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@profile = new Profile(fabricate('partner_profile',
owner_type: 'PartnerInstitution'
owner:
type: "Institution"
sortable_id: "getty-museum"
name: "<NAME>"
default_profile_id: "getty"
icon:
id: "<KEY>",
image_filename: "GGLogo1.jpg",
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "square140" ]
x: 0
y: 0
width: 140
))
afterEach ->
Backbone.sync.restore()
describe '#isUserClass', ->
it 'returns is-user if the profile is a user and is set to use a circular default icon', ->
@profile.isUserClass().should.equal 'is-partner'
@profile.set owner_type: 'User'
@profile.set default_icon_version: 'circle'
@profile.isUserClass().should.equal 'is-user'
describe '#iconImageUrl', ->
it "returns the icon url for the model's default icon version", ->
@profile.iconImageUrl().should.containEql "square"
describe '#hasIconImage', ->
it 'returns true if profile has an icon', ->
@profile.hasIconImage().should.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', null
@profile.hasIconImage().should.not.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', id: '<KEY>5b2420810001fe'
@profile.hasIconImage().should.not.be.ok()
describe '#bestAvailableImage', ->
it "returns the icon image url if there is no cover", ->
@profile.unset 'cover_image'
@profile.bestAvailableImage().should.containEql("square")
it "returns the cover image url for medium250x165 if it exists", ->
@profile.set
cover_image:
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "medium250x165" ]
@profile.bestAvailableImage().should.containEql('medium250x165')
describe '#alphaSortKey', ->
it "returns the profile owner's display name", ->
@profile.alphaSortKey().should.equal @profile.displayName()
describe '#href', ->
it "returns the client link to this profile", ->
@profile.href().should.containEql "/#{@profile.get('id')}"
describe '#displayName', ->
it "returns the profile owner's display name", ->
@profile.displayName().should.equal @profile.related().owner.get('name')
describe '#isFairOrOrganizer', ->
it "returns true if the profile belongs to either a Fair or a Fair Organizer", ->
@profile.set 'owner_type', 'Fair'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'FairOrganizer'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'User'
@profile.isFairOrOrganizer().should.be.false()
describe '#isPartner', ->
it "returns true if the profile does not belong to a User or Admin", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.isPartner().should.be.true()
@profile.set 'owner_type', 'Admin'
@profile.isPartner().should.be.false()
@profile.set 'owner_type', 'User'
@profile.isPartner().should.be.false()
describe '#defaultIconInitials', ->
it "returns up to two initials for a partner name", ->
@profile.defaultIconInitials().should.equal "JP"
@profile.related().owner.set 'name', "<NAME>"
@profile.defaultIconInitials().should.equal "W"
@profile.related().owner.set 'name', "<NAME>"
@profile.defaultIconInitials().should.equal "JJ"
it "does not include non-word characters", ->
@profile.related().owner.set 'name', "<NAME>"
@profile.defaultIconInitials().should.equal "CR"
@profile.related().owner.set 'name', "2 % Johan _ Gregor 37"
@profile.defaultIconInitials().should.equal "2J"
describe 'related owner', ->
it "creates PartnerGallery", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates PartnerInstitution", ->
@profile.set 'owner_type', 'PartnerInstitution'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates User", ->
@profile.set 'owner_type', 'User'
@profile.related().owner.constructor.name.should.equal 'User'
it "creates Fair", ->
@profile.set 'owner_type', 'Fair'
@profile.related().owner.constructor.name.should.equal 'Fair'
it "creates FairOrganizer", ->
@profile.set 'owner_type', 'FairOrganizer'
@profile.related().owner.constructor.name.should.equal 'FairOrganizer'
describe '#formatFollowText', ->
it 'returns formatted follows text', ->
@profile.set follows_count: 1234567
@profile.formatFollowText().should.equal '1,234,567 Followers'
describe '#getFormattedWebsite', ->
it 'formats website', ->
@profile.set website: 'https://artsy.net'
@profile.getFormattedWebsite().should.equal 'artsy.net'
describe '#metaTitle', ->
it 'correctly formats title for users', ->
@profile.set owner_type: 'User'
@profile.metaTitle().should.equal '<NAME> Museum | Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaTitle().should.equal '<NAME> Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('overview').should.equal '<NAME> Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('contact').should.equal '<NAME> Museum | Contact Information | Artsy'
@profile.metaTitle('about').should.equal '<NAME> Museum | Visitor Information | Artsy'
@profile.metaTitle('collection').should.equal '<NAME> Museum | Collection | Artsy'
@profile.metaTitle('shop').should.equal '<NAME> Museum | Shop | Artsy'
@profile.metaTitle('shows').should.equal '<NAME> Museum | Shows | Artsy'
@profile.metaTitle('artists').should.equal '<NAME> Museum | Artists | Artsy'
@profile.metaTitle('artist').should.equal '<NAME> Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('posts').should.equal '<NAME>. <NAME>ty Museum | Posts | Artsy'
it 'correctly formats title for non-gallery partners', ->
@profile.set owner_type: 'PartnerInstitution'
@profile.metaTitle().should.equal '<NAME> Museum | Artists, Artworks, and Contact Info | Artsy'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaTitle().should.equal '<NAME> Museum | Fair Info, Artists, and Art for Sale | Artsy'
@profile.metaTitle('info').should.equal '<NAME> Museum | Visitor Information | Artsy'
@profile.metaTitle('posts').should.equal '<NAME> Museum | Highlighted Articles | Artsy'
@profile.metaTitle('forYou').should.equal '<NAME> Museum | Your Personal Fair Guide | Artsy'
@profile.metaTitle('search').should.equal '<NAME> Museum | Search | Artsy'
@profile.metaTitle('browse').should.equal '<NAME> Museum | Browse | Artsy'
@profile.metaTitle('favorites').should.equal '<NAME> Museum | Favorites | Artsy'
@profile.metaTitle('follows').should.equal '<NAME> Museum | Following | Artsy'
describe '#metaDescription', ->
it 'correctly formats description', ->
@profile.set('bio', 'bio')
@profile.metaDescription().should.equal 'bio'
@profile.set('bio', undefined)
@profile.metaDescription().should.equal '<NAME> Museum on Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaDescription().should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('overview').should.equal "The <NAME>ty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('contact').should.equal 'Contact information including a map of locations with phone numbers for <NAME>um'
@profile.metaDescription('about').should.equal 'Visitor information including location and phone number for <NAME> Museum'
@profile.metaDescription('collection').should.equal 'Artworks in the collection of <NAME>. <NAME> Getty Museum'
@profile.metaDescription('shop').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('shows').should.equal 'List of current, upcoming and past shows at J. <NAME> Getty Museum'
@profile.metaDescription('artists').should.equal 'List of artists represented by <NAME> Museum'
@profile.metaDescription('artist').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('posts').should.equal 'Articles about and created by <NAME>ty Museum'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaDescription().should.equal "The <NAME> is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('info').should.equal "Visitor information including location, tickets and phone number for the fair"
@profile.metaDescription('posts').should.equal 'Featured articles about the fair'
@profile.metaDescription('forYou').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('search').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('browse').should.equal "Browse artworks at the fair by subject matter, style/technique, movement, price, and booth"
@profile.metaDescription('favorites').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('follows').should.equal "The <NAME> Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
describe '#fetchFavorites', ->
it 'fetches the saved-artwork collection based on the owner', ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites({})
Backbone.sync.args[0][1].url.should.containEql 'saved-artwork/artworks'
it 'returns feed items with a set url', (done) ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites success: (items) ->
items.url.should.containEql 'saved-artwork/artworks'
done()
Backbone.sync.args[0][2].success [{ id: 'bar' }]
| true | _ = require 'underscore'
{ fabricate } = require '@artsy/antigravity'
sd = require('sharify').data
should = require 'should'
Backbone = require 'backbone'
Profile = require '../../models/profile'
sinon = require 'sinon'
describe 'Profile', ->
beforeEach ->
sinon.stub Backbone, 'sync'
@profile = new Profile(fabricate('partner_profile',
owner_type: 'PartnerInstitution'
owner:
type: "Institution"
sortable_id: "getty-museum"
name: "PI:NAME:<NAME>END_PI"
default_profile_id: "getty"
icon:
id: "PI:KEY:<KEY>END_PI",
image_filename: "GGLogo1.jpg",
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "square140" ]
x: 0
y: 0
width: 140
))
afterEach ->
Backbone.sync.restore()
describe '#isUserClass', ->
it 'returns is-user if the profile is a user and is set to use a circular default icon', ->
@profile.isUserClass().should.equal 'is-partner'
@profile.set owner_type: 'User'
@profile.set default_icon_version: 'circle'
@profile.isUserClass().should.equal 'is-user'
describe '#iconImageUrl', ->
it "returns the icon url for the model's default icon version", ->
@profile.iconImageUrl().should.containEql "square"
describe '#hasIconImage', ->
it 'returns true if profile has an icon', ->
@profile.hasIconImage().should.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', null
@profile.hasIconImage().should.not.be.ok()
it 'returns false if profile has no valid icon', ->
@profile.set 'icon', id: 'PI:KEY:<KEY>END_PI5b2420810001fe'
@profile.hasIconImage().should.not.be.ok()
describe '#bestAvailableImage', ->
it "returns the icon image url if there is no cover", ->
@profile.unset 'cover_image'
@profile.bestAvailableImage().should.containEql("square")
it "returns the cover image url for medium250x165 if it exists", ->
@profile.set
cover_image:
image_url: "http://static2.artsy.net/profile_icons/51eefb79275b2420810001fe/:version.jpg",
image_versions: [ "medium250x165" ]
@profile.bestAvailableImage().should.containEql('medium250x165')
describe '#alphaSortKey', ->
it "returns the profile owner's display name", ->
@profile.alphaSortKey().should.equal @profile.displayName()
describe '#href', ->
it "returns the client link to this profile", ->
@profile.href().should.containEql "/#{@profile.get('id')}"
describe '#displayName', ->
it "returns the profile owner's display name", ->
@profile.displayName().should.equal @profile.related().owner.get('name')
describe '#isFairOrOrganizer', ->
it "returns true if the profile belongs to either a Fair or a Fair Organizer", ->
@profile.set 'owner_type', 'Fair'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'FairOrganizer'
@profile.isFairOrOrganizer().should.be.true()
@profile.set 'owner_type', 'User'
@profile.isFairOrOrganizer().should.be.false()
describe '#isPartner', ->
it "returns true if the profile does not belong to a User or Admin", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.isPartner().should.be.true()
@profile.set 'owner_type', 'Admin'
@profile.isPartner().should.be.false()
@profile.set 'owner_type', 'User'
@profile.isPartner().should.be.false()
describe '#defaultIconInitials', ->
it "returns up to two initials for a partner name", ->
@profile.defaultIconInitials().should.equal "JP"
@profile.related().owner.set 'name', "PI:NAME:<NAME>END_PI"
@profile.defaultIconInitials().should.equal "W"
@profile.related().owner.set 'name', "PI:NAME:<NAME>END_PI"
@profile.defaultIconInitials().should.equal "JJ"
it "does not include non-word characters", ->
@profile.related().owner.set 'name', "PI:NAME:<NAME>END_PI"
@profile.defaultIconInitials().should.equal "CR"
@profile.related().owner.set 'name', "2 % Johan _ Gregor 37"
@profile.defaultIconInitials().should.equal "2J"
describe 'related owner', ->
it "creates PartnerGallery", ->
@profile.set 'owner_type', 'PartnerGallery'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates PartnerInstitution", ->
@profile.set 'owner_type', 'PartnerInstitution'
@profile.related().owner.constructor.name.should.equal 'Partner'
it "creates User", ->
@profile.set 'owner_type', 'User'
@profile.related().owner.constructor.name.should.equal 'User'
it "creates Fair", ->
@profile.set 'owner_type', 'Fair'
@profile.related().owner.constructor.name.should.equal 'Fair'
it "creates FairOrganizer", ->
@profile.set 'owner_type', 'FairOrganizer'
@profile.related().owner.constructor.name.should.equal 'FairOrganizer'
describe '#formatFollowText', ->
it 'returns formatted follows text', ->
@profile.set follows_count: 1234567
@profile.formatFollowText().should.equal '1,234,567 Followers'
describe '#getFormattedWebsite', ->
it 'formats website', ->
@profile.set website: 'https://artsy.net'
@profile.getFormattedWebsite().should.equal 'artsy.net'
describe '#metaTitle', ->
it 'correctly formats title for users', ->
@profile.set owner_type: 'User'
@profile.metaTitle().should.equal 'PI:NAME:<NAME>END_PI Museum | Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaTitle().should.equal 'PI:NAME:<NAME>END_PI Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('overview').should.equal 'PI:NAME:<NAME>END_PI Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('contact').should.equal 'PI:NAME:<NAME>END_PI Museum | Contact Information | Artsy'
@profile.metaTitle('about').should.equal 'PI:NAME:<NAME>END_PI Museum | Visitor Information | Artsy'
@profile.metaTitle('collection').should.equal 'PI:NAME:<NAME>END_PI Museum | Collection | Artsy'
@profile.metaTitle('shop').should.equal 'PI:NAME:<NAME>END_PI Museum | Shop | Artsy'
@profile.metaTitle('shows').should.equal 'PI:NAME:<NAME>END_PI Museum | Shows | Artsy'
@profile.metaTitle('artists').should.equal 'PI:NAME:<NAME>END_PI Museum | Artists | Artsy'
@profile.metaTitle('artist').should.equal 'PI:NAME:<NAME>END_PI Museum | Artists, Art for Sale, and Contact Info | Artsy'
@profile.metaTitle('posts').should.equal 'PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PIty Museum | Posts | Artsy'
it 'correctly formats title for non-gallery partners', ->
@profile.set owner_type: 'PartnerInstitution'
@profile.metaTitle().should.equal 'PI:NAME:<NAME>END_PI Museum | Artists, Artworks, and Contact Info | Artsy'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaTitle().should.equal 'PI:NAME:<NAME>END_PI Museum | Fair Info, Artists, and Art for Sale | Artsy'
@profile.metaTitle('info').should.equal 'PI:NAME:<NAME>END_PI Museum | Visitor Information | Artsy'
@profile.metaTitle('posts').should.equal 'PI:NAME:<NAME>END_PI Museum | Highlighted Articles | Artsy'
@profile.metaTitle('forYou').should.equal 'PI:NAME:<NAME>END_PI Museum | Your Personal Fair Guide | Artsy'
@profile.metaTitle('search').should.equal 'PI:NAME:<NAME>END_PI Museum | Search | Artsy'
@profile.metaTitle('browse').should.equal 'PI:NAME:<NAME>END_PI Museum | Browse | Artsy'
@profile.metaTitle('favorites').should.equal 'PI:NAME:<NAME>END_PI Museum | Favorites | Artsy'
@profile.metaTitle('follows').should.equal 'PI:NAME:<NAME>END_PI Museum | Following | Artsy'
describe '#metaDescription', ->
it 'correctly formats description', ->
@profile.set('bio', 'bio')
@profile.metaDescription().should.equal 'bio'
@profile.set('bio', undefined)
@profile.metaDescription().should.equal 'PI:NAME:<NAME>END_PI Museum on Artsy'
it 'correctly formats title for galleries', ->
@profile.set owner_type: 'PartnerGallery'
@profile.metaDescription().should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('overview').should.equal "The PI:NAME:<NAME>END_PIty Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('contact').should.equal 'Contact information including a map of locations with phone numbers for PI:NAME:<NAME>END_PIum'
@profile.metaDescription('about').should.equal 'Visitor information including location and phone number for PI:NAME:<NAME>END_PI Museum'
@profile.metaDescription('collection').should.equal 'Artworks in the collection of PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI Getty Museum'
@profile.metaDescription('shop').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('shows').should.equal 'List of current, upcoming and past shows at J. PI:NAME:<NAME>END_PI Getty Museum'
@profile.metaDescription('artists').should.equal 'List of artists represented by PI:NAME:<NAME>END_PI Museum'
@profile.metaDescription('artist').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('posts').should.equal 'Articles about and created by PI:NAME:<NAME>END_PIty Museum'
it 'correctly formats title for fairs', ->
@profile.set owner_type: 'FairOrganizer'
@profile.metaDescription().should.equal "The PI:NAME:<NAME>END_PI is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('info').should.equal "Visitor information including location, tickets and phone number for the fair"
@profile.metaDescription('posts').should.equal 'Featured articles about the fair'
@profile.metaDescription('forYou').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('search').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('browse').should.equal "Browse artworks at the fair by subject matter, style/technique, movement, price, and booth"
@profile.metaDescription('favorites').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
@profile.metaDescription('follows').should.equal "The PI:NAME:<NAME>END_PI Trust is a cultural and philanthropic institution dedicated to critical thinking in the presentation, conservation, and interpretation of the world's artistic legacy."
describe '#fetchFavorites', ->
it 'fetches the saved-artwork collection based on the owner', ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites({})
Backbone.sync.args[0][1].url.should.containEql 'saved-artwork/artworks'
it 'returns feed items with a set url', (done) ->
@profile.related().owner.set('id', 'foobar')
@profile.fetchFavorites success: (items) ->
items.url.should.containEql 'saved-artwork/artworks'
done()
Backbone.sync.args[0][2].success [{ id: 'bar' }]
|
[
{
"context": "amming for microcontrollers\n# * Copyright (c) 2013 Jon Nordby <jononor@gmail.com>\n# * MicroFlo may be freely di",
"end": 90,
"score": 0.9998161196708679,
"start": 80,
"tag": "NAME",
"value": "Jon Nordby"
},
{
"context": "crocontrollers\n# * Copyright (c) 2013 Jon Nord... | lib/componentlib.coffee | microflo/microflo | 136 | # MicroFlo - Flow-Based Programming for microcontrollers
# * Copyright (c) 2013 Jon Nordby <jononor@gmail.com>
# * MicroFlo may be freely distributed under the MIT license
#
util = require "./util"
path = require "path"
fs = require "fs"
bluebird = require 'bluebird'
findHighestId = (components) ->
highest = 0
Object.keys(components).forEach (name) ->
comp = components[name]
highest = comp.id if not comp[".skip"] and comp.id > highest
return highest
extractComponents = (componentLib, inputFile, options) ->
options = {} if not options?
options.ignoreComponents = [] if not options.ignoreComponents
declarec = require "declarec"
yaml = require "js-yaml"
# TODO: check if C file
# TODO: use declarec code for parsing
data = fs.readFileSync inputFile, { encoding: "utf-8" }
raw = declarec.extractDefinition data, "microflo_component", "c"
raw.forEach (def) ->
# HACK: js-yaml fails when document has leading indent and does not start with ---
needsFix = (str) -> str.indexOf(" ") is 0 and str.substring(0, 3) isnt "---"
if def.format is "yaml"
def.content = "---\n" + def.content + "\n" if needsFix def.content
d = yaml.safeLoad(def.content)
if d.name not in options.ignoreComponents
componentLib.addComponent d.name, d, inputFile
class ComponentLibrary
constructor: () ->
@reset()
reset: ->
@definition = components: {}
loadFile: (filePath, options={}) ->
extractComponents this, filePath, options
loadSet: (set, callback) ->
try
set.components.forEach (name) =>
@loadFile set.base + "/" + name + ".hpp"
catch e
return callback(e)
return callback null
loadPaths: (paths, options, callback) ->
options = {} if not options?
options.extensions = ['.hpp', '.cpp'] if not options.extensions
options.ignoreFiles = [] if not options.ignoreFiles
options.ignoreComponents = [] if not options.ignoreComponents
fsStat = bluebird.promisify(fs.stat)
fsReadDir = bluebird.promisify(fs.readdir)
expandDirectory = (p) ->
fsStat(p).then (stats) ->
if stats.isDirectory()
fsReadDir(p).then (files) ->
return files.map((f) -> path.join(p, f))
else
return [ p ]
isComponentFile = (p) ->
ext = path.extname p
validType = ext in options.extensions
notIgnored = not (p in options.ignoreFiles)
return validType and notIgnored
bluebird.map(paths, expandDirectory).then (expanded) =>
files = [].concat.apply([], expanded) # flatten
for p in files.filter isComponentFile
@loadFile path.resolve(p), options
.asCallback(callback)
return null # avoid returning promise
listComponents: (includingSkipped, includingVirtual) ->
Object.keys @getComponents includingSkipped, includingVirtual
getComponents: (includingSkipped, includingVirtual) ->
return @definition.components if includingSkipped
components = {}
for name of @definition.components
comp = @getComponent(name)
skip = comp[".skip"] or false
virtual = comp["graph"] or comp["graphFile"]
components[name] = comp if not skip and (includingVirtual or not virtual)
return components
getComponent: (componentName) ->
throw new Error "getComponent(): component name not specified" if not componentName
c = @definition.components[componentName]
return c
getComponentById: (componentId) ->
for name of @getComponents()
comp = @getComponent name
if comp.id is componentId
comp.name = name
return comp
return null
getComponentSource: (componentName, callback) ->
return callback new Error "Getting component source not implemented"
componentFile = path.join @baseDirectory, "components.cpp"
startLine = 0
endLine = 0
# FIXME: support when running in browser. Probably look up in github?
fs.readFile componentFile, (err, data) =>
return callback(err, null) if err
data = data.toString()
lines = data.split("\n")
i = 0
while i < lines.length
line = lines[i].trim()
startLine = i if startLine is 0 and line.match("class " + componentName)
if startLine isnt 0 and line.match("};")
endLine = i + 1
source = lines.slice(startLine, endLine).join("\n")
return callback(null, source)
i++
return callback new Error 'Could not find component source'
outputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.outPorts
inputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.inPorts
inputPort: (componentName, portName) ->
@inputPortsFor(componentName)[portName]
outputPort: (componentName, portName) ->
@outputPortsFor(componentName)[portName]
inputPortById: (componentName, portId) ->
ports = @inputPortsFor componentName
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
outputPortById: (componentName, portId) ->
ports = @outputPortsFor(componentName)
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
addComponent: (componentName, def, filename) ->
# Normalization
def.filename = filename
def.id = findHighestId(@definition.components) + 1 if typeof def.id is "undefined"
if typeof def.inports isnt "undefined"
def.inPorts = def.inports
def.inports = null
if typeof def.inPorts is "undefined"
def.inPorts = { 'in': { id: 0 } }
if typeof def.outports isnt "undefined"
def.outPorts = def.outports
def.outports = null
if typeof def.outPorts is "undefined"
def.outPorts = { out: { id: 0 } }
checkPortIdsAssigned = (ports) ->
names = Object.keys(ports)
if names.length > 0 and not ports[names[0]].id?
names.forEach (name, idx) ->
port = ports[name]
port.id = idx
# TODO: normalize port description (default "") and type (default: "all")
checkPortIdsAssigned def.inPorts
checkPortIdsAssigned def.outPorts
@definition.components[componentName] = def
module.exports = ComponentLibrary: ComponentLibrary
| 175201 | # MicroFlo - Flow-Based Programming for microcontrollers
# * Copyright (c) 2013 <NAME> <<EMAIL>>
# * MicroFlo may be freely distributed under the MIT license
#
util = require "./util"
path = require "path"
fs = require "fs"
bluebird = require 'bluebird'
findHighestId = (components) ->
highest = 0
Object.keys(components).forEach (name) ->
comp = components[name]
highest = comp.id if not comp[".skip"] and comp.id > highest
return highest
extractComponents = (componentLib, inputFile, options) ->
options = {} if not options?
options.ignoreComponents = [] if not options.ignoreComponents
declarec = require "declarec"
yaml = require "js-yaml"
# TODO: check if C file
# TODO: use declarec code for parsing
data = fs.readFileSync inputFile, { encoding: "utf-8" }
raw = declarec.extractDefinition data, "microflo_component", "c"
raw.forEach (def) ->
# HACK: js-yaml fails when document has leading indent and does not start with ---
needsFix = (str) -> str.indexOf(" ") is 0 and str.substring(0, 3) isnt "---"
if def.format is "yaml"
def.content = "---\n" + def.content + "\n" if needsFix def.content
d = yaml.safeLoad(def.content)
if d.name not in options.ignoreComponents
componentLib.addComponent d.name, d, inputFile
class ComponentLibrary
constructor: () ->
@reset()
reset: ->
@definition = components: {}
loadFile: (filePath, options={}) ->
extractComponents this, filePath, options
loadSet: (set, callback) ->
try
set.components.forEach (name) =>
@loadFile set.base + "/" + name + ".hpp"
catch e
return callback(e)
return callback null
loadPaths: (paths, options, callback) ->
options = {} if not options?
options.extensions = ['.hpp', '.cpp'] if not options.extensions
options.ignoreFiles = [] if not options.ignoreFiles
options.ignoreComponents = [] if not options.ignoreComponents
fsStat = bluebird.promisify(fs.stat)
fsReadDir = bluebird.promisify(fs.readdir)
expandDirectory = (p) ->
fsStat(p).then (stats) ->
if stats.isDirectory()
fsReadDir(p).then (files) ->
return files.map((f) -> path.join(p, f))
else
return [ p ]
isComponentFile = (p) ->
ext = path.extname p
validType = ext in options.extensions
notIgnored = not (p in options.ignoreFiles)
return validType and notIgnored
bluebird.map(paths, expandDirectory).then (expanded) =>
files = [].concat.apply([], expanded) # flatten
for p in files.filter isComponentFile
@loadFile path.resolve(p), options
.asCallback(callback)
return null # avoid returning promise
listComponents: (includingSkipped, includingVirtual) ->
Object.keys @getComponents includingSkipped, includingVirtual
getComponents: (includingSkipped, includingVirtual) ->
return @definition.components if includingSkipped
components = {}
for name of @definition.components
comp = @getComponent(name)
skip = comp[".skip"] or false
virtual = comp["graph"] or comp["graphFile"]
components[name] = comp if not skip and (includingVirtual or not virtual)
return components
getComponent: (componentName) ->
throw new Error "getComponent(): component name not specified" if not componentName
c = @definition.components[componentName]
return c
getComponentById: (componentId) ->
for name of @getComponents()
comp = @getComponent name
if comp.id is componentId
comp.name = name
return comp
return null
getComponentSource: (componentName, callback) ->
return callback new Error "Getting component source not implemented"
componentFile = path.join @baseDirectory, "components.cpp"
startLine = 0
endLine = 0
# FIXME: support when running in browser. Probably look up in github?
fs.readFile componentFile, (err, data) =>
return callback(err, null) if err
data = data.toString()
lines = data.split("\n")
i = 0
while i < lines.length
line = lines[i].trim()
startLine = i if startLine is 0 and line.match("class " + componentName)
if startLine isnt 0 and line.match("};")
endLine = i + 1
source = lines.slice(startLine, endLine).join("\n")
return callback(null, source)
i++
return callback new Error 'Could not find component source'
outputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.outPorts
inputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.inPorts
inputPort: (componentName, portName) ->
@inputPortsFor(componentName)[portName]
outputPort: (componentName, portName) ->
@outputPortsFor(componentName)[portName]
inputPortById: (componentName, portId) ->
ports = @inputPortsFor componentName
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
outputPortById: (componentName, portId) ->
ports = @outputPortsFor(componentName)
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
addComponent: (componentName, def, filename) ->
# Normalization
def.filename = filename
def.id = findHighestId(@definition.components) + 1 if typeof def.id is "undefined"
if typeof def.inports isnt "undefined"
def.inPorts = def.inports
def.inports = null
if typeof def.inPorts is "undefined"
def.inPorts = { 'in': { id: 0 } }
if typeof def.outports isnt "undefined"
def.outPorts = def.outports
def.outports = null
if typeof def.outPorts is "undefined"
def.outPorts = { out: { id: 0 } }
checkPortIdsAssigned = (ports) ->
names = Object.keys(ports)
if names.length > 0 and not ports[names[0]].id?
names.forEach (name, idx) ->
port = ports[name]
port.id = idx
# TODO: normalize port description (default "") and type (default: "all")
checkPortIdsAssigned def.inPorts
checkPortIdsAssigned def.outPorts
@definition.components[componentName] = def
module.exports = ComponentLibrary: ComponentLibrary
| true | # MicroFlo - Flow-Based Programming for microcontrollers
# * Copyright (c) 2013 PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
# * MicroFlo may be freely distributed under the MIT license
#
util = require "./util"
path = require "path"
fs = require "fs"
bluebird = require 'bluebird'
findHighestId = (components) ->
highest = 0
Object.keys(components).forEach (name) ->
comp = components[name]
highest = comp.id if not comp[".skip"] and comp.id > highest
return highest
extractComponents = (componentLib, inputFile, options) ->
options = {} if not options?
options.ignoreComponents = [] if not options.ignoreComponents
declarec = require "declarec"
yaml = require "js-yaml"
# TODO: check if C file
# TODO: use declarec code for parsing
data = fs.readFileSync inputFile, { encoding: "utf-8" }
raw = declarec.extractDefinition data, "microflo_component", "c"
raw.forEach (def) ->
# HACK: js-yaml fails when document has leading indent and does not start with ---
needsFix = (str) -> str.indexOf(" ") is 0 and str.substring(0, 3) isnt "---"
if def.format is "yaml"
def.content = "---\n" + def.content + "\n" if needsFix def.content
d = yaml.safeLoad(def.content)
if d.name not in options.ignoreComponents
componentLib.addComponent d.name, d, inputFile
class ComponentLibrary
constructor: () ->
@reset()
reset: ->
@definition = components: {}
loadFile: (filePath, options={}) ->
extractComponents this, filePath, options
loadSet: (set, callback) ->
try
set.components.forEach (name) =>
@loadFile set.base + "/" + name + ".hpp"
catch e
return callback(e)
return callback null
loadPaths: (paths, options, callback) ->
options = {} if not options?
options.extensions = ['.hpp', '.cpp'] if not options.extensions
options.ignoreFiles = [] if not options.ignoreFiles
options.ignoreComponents = [] if not options.ignoreComponents
fsStat = bluebird.promisify(fs.stat)
fsReadDir = bluebird.promisify(fs.readdir)
expandDirectory = (p) ->
fsStat(p).then (stats) ->
if stats.isDirectory()
fsReadDir(p).then (files) ->
return files.map((f) -> path.join(p, f))
else
return [ p ]
isComponentFile = (p) ->
ext = path.extname p
validType = ext in options.extensions
notIgnored = not (p in options.ignoreFiles)
return validType and notIgnored
bluebird.map(paths, expandDirectory).then (expanded) =>
files = [].concat.apply([], expanded) # flatten
for p in files.filter isComponentFile
@loadFile path.resolve(p), options
.asCallback(callback)
return null # avoid returning promise
listComponents: (includingSkipped, includingVirtual) ->
Object.keys @getComponents includingSkipped, includingVirtual
getComponents: (includingSkipped, includingVirtual) ->
return @definition.components if includingSkipped
components = {}
for name of @definition.components
comp = @getComponent(name)
skip = comp[".skip"] or false
virtual = comp["graph"] or comp["graphFile"]
components[name] = comp if not skip and (includingVirtual or not virtual)
return components
getComponent: (componentName) ->
throw new Error "getComponent(): component name not specified" if not componentName
c = @definition.components[componentName]
return c
getComponentById: (componentId) ->
for name of @getComponents()
comp = @getComponent name
if comp.id is componentId
comp.name = name
return comp
return null
getComponentSource: (componentName, callback) ->
return callback new Error "Getting component source not implemented"
componentFile = path.join @baseDirectory, "components.cpp"
startLine = 0
endLine = 0
# FIXME: support when running in browser. Probably look up in github?
fs.readFile componentFile, (err, data) =>
return callback(err, null) if err
data = data.toString()
lines = data.split("\n")
i = 0
while i < lines.length
line = lines[i].trim()
startLine = i if startLine is 0 and line.match("class " + componentName)
if startLine isnt 0 and line.match("};")
endLine = i + 1
source = lines.slice(startLine, endLine).join("\n")
return callback(null, source)
i++
return callback new Error 'Could not find component source'
outputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.outPorts
inputPortsFor: (componentName) ->
c = @getComponent(componentName)
throw new Error "Could not find outports for #{componentName}" if not c
return c.inPorts
inputPort: (componentName, portName) ->
@inputPortsFor(componentName)[portName]
outputPort: (componentName, portName) ->
@outputPortsFor(componentName)[portName]
inputPortById: (componentName, portId) ->
ports = @inputPortsFor componentName
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
outputPortById: (componentName, portId) ->
ports = @outputPortsFor(componentName)
for name of ports
port = ports[name]
if port.id is portId
port.name = name
return port
return null
addComponent: (componentName, def, filename) ->
# Normalization
def.filename = filename
def.id = findHighestId(@definition.components) + 1 if typeof def.id is "undefined"
if typeof def.inports isnt "undefined"
def.inPorts = def.inports
def.inports = null
if typeof def.inPorts is "undefined"
def.inPorts = { 'in': { id: 0 } }
if typeof def.outports isnt "undefined"
def.outPorts = def.outports
def.outports = null
if typeof def.outPorts is "undefined"
def.outPorts = { out: { id: 0 } }
checkPortIdsAssigned = (ports) ->
names = Object.keys(ports)
if names.length > 0 and not ports[names[0]].id?
names.forEach (name, idx) ->
port = ports[name]
port.id = idx
# TODO: normalize port description (default "") and type (default: "all")
checkPortIdsAssigned def.inPorts
checkPortIdsAssigned def.outPorts
@definition.components[componentName] = def
module.exports = ComponentLibrary: ComponentLibrary
|
[
{
"context": "s\",\"Prov\",\"Eccl\",\"Song\",\"Isa\",\"Jer\",\"Lam\",\"Ezek\",\"Dan\",\"Hos\",\"Joel\",\"Amos\",\"Obad\",\"Jonah\",\"Mic\",\"Nah\",\"",
"end": 505,
"score": 0.7560182809829712,
"start": 502,
"tag": "NAME",
"value": "Dan"
},
{
"context": "ov\",\"Eccl\",\"Song\",\"Isa\"... | lib/bible-tools/lib/Bible-Passage-Reference-Parser/src/cs/spec.coffee | saiba-mais/bible-lessons | 149 | bcv_parser = require("../../js/cs_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic","Nah","Hab","Zeph","Hag","Zech","Mal","Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
describe "Localized book Gen (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gen (cs)", ->
`
expect(p.parse("Prvni kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Exod (cs)", ->
`
expect(p.parse("Druha kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bel (cs)", ->
`
expect(p.parse("Bel a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lev (cs)", ->
`
expect(p.parse("Treti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticusi 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levitikus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUSI 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITIKUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Num (cs)", ->
`
expect(p.parse("Ctvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("CTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sir (cs)", ->
`
expect(p.parse("Kniha Sirachovcova 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Kniha Sírachovcova 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclesiasticus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sírachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Wis (cs)", ->
`
expect(p.parse("Moudrost Salomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost Šalomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha Moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrostí 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Mdr 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lam (cs)", ->
`
expect(p.parse("Plac Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pl 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("PLAC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PL 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: EpJer (cs)", ->
`
expect(p.parse("List Jeremjasuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjasův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rev (cs)", ->
`
expect(p.parse("Zjeveni svateho Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni svatého Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apokalypsa 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zj 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("ZJEVENI SVATEHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI SVATÉHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOKALYPSA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJ 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrMan (cs)", ->
`
expect(p.parse("Modlitbu Manasse 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Deut (cs)", ->
`
expect(p.parse("Pata kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("PATA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book Josh (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Josh (cs)", ->
`
expect(p.parse("Jozue 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Jz 1:1").osis()).toEqual("Josh.1.1")
p.include_apocrypha(false)
expect(p.parse("JOZUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JZ 1:1").osis()).toEqual("Josh.1.1")
`
true
describe "Localized book Judg (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Judg (cs)", ->
`
expect(p.parse("Soudcu 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Soudců 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sdc 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sd 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("SOUDCU 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SOUDCŮ 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SDC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SD 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ruth (cs)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rút 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RÚT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Esd (cs)", ->
`
expect(p.parse("Prvni Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Esd (cs)", ->
`
expect(p.parse("Druha Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Isa (cs)", ->
`
expect(p.parse("Izaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajas 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("IZAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Sam (cs)", ->
`
expect(p.parse("Druha kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Sam (cs)", ->
`
expect(p.parse("Prvni kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I kniha Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Samuelova 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Samuel 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Kgs (cs)", ->
`
expect(p.parse("Druha kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Kgs (cs)", ->
`
expect(p.parse("Prvni kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kr 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KR 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Chr (cs)", ->
`
expect(p.parse("Druha Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Chr (cs)", ->
`
expect(p.parse("Prvni Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Pa 1:1").osis()).toEqual("1Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PA 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezra (cs)", ->
`
expect(p.parse("Ezdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdraš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdrás 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdráš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("EZDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRAŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Neh (cs)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjas 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: GkEsth (cs)", ->
`
expect(p.parse("Ester (řecké dodatky) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (řecké části) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Esth (cs)", ->
`
expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Job (cs)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jób 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JÓB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ps (cs)", ->
`
expect(p.parse("Kniha zalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha zalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("KNIHA ZALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ZALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrAzar (cs)", ->
`
expect(p.parse("Azarjasova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjašova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjásova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjášova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Prov (cs)", ->
`
expect(p.parse("Prislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pris 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přis 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Př 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PRISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘ 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eccl (cs)", ->
`
expect(p.parse("Kazatel 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kohelet 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kaz 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("KAZATEL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KOHELET 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KAZ 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: SgThree (cs)", ->
`
expect(p.parse("Pisen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Song (cs)", ->
`
expect(p.parse("Pisen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pis 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pís 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("PISEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PIS 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍS 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book Jer (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jer (cs)", ->
`
expect(p.parse("Jeremias 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremiaš 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremiás 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremiáš 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremjas 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremjaš 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremjás 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jeremjáš 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezek (cs)", ->
`
expect(p.parse("Ezechiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZECHIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book Dan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Dan (cs)", ->
`
expect(p.parse("Daniel 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
p.include_apocrypha(false)
expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hos (cs)", ->
`
expect(p.parse("Ozeas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeaš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeás 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeáš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OZEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEAŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Joel (cs)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jo 1:1").osis()).toEqual("Joel.1.1")
p.include_apocrypha(false)
expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JO 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Amos (cs)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ámos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1")
p.include_apocrypha(false)
expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("ÁMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Obad (cs)", ->
`
expect(p.parse("Abdijas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjá 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book Jonah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jonah (cs)", ->
`
expect(p.parse("Jonah 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonaš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonáš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Mic (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mic (cs)", ->
`
expect(p.parse("Michaas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mich 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MICHAAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICH 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Nah (cs)", ->
`
expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
p.include_apocrypha(false)
expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hab (cs)", ->
`
expect(p.parse("Abakuk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Abk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("ABAKUK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("ABK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zeph (cs)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjas 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hag (cs)", ->
`
expect(p.parse("Aggeus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("AGGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zech (cs)", ->
`
expect(p.parse("Zacharias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjas 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACHARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mal (cs)", ->
`
expect(p.parse("Malachias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiaš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiás 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiáš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALACHIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIAŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book Matt (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Matt (cs)", ->
`
expect(p.parse("Evangelium podle Matouse 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelium podle Matouše 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matousovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matoušovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matous 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matouš 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MATOUSE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIUM PODLE MATOUŠE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUSOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUS 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠ 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Mark (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mark (cs)", ->
`
expect(p.parse("Evangelium podle Marka 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Markovo evangelium 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marek 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MARKA 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARKOVO EVANGELIUM 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAREK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book Luke (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Luke (cs)", ->
`
expect(p.parse("Evangelium podle Lukase 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukaše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáse 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukasovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukašovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukásovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukášovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukaš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukás 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukáš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE LUKASE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKAŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁSE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKASOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁSOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book 1John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1John (cs)", ->
`
expect(p.parse("Prvni list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2John (cs)", ->
`
expect(p.parse("Druha list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3John (cs)", ->
`
expect(p.parse("Treti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: John (cs)", ->
`
expect(p.parse("Evangelium podle Jana 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Janovo evangelium 1:1").osis()).toEqual("John.1.1")
expect(p.parse("John 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE JANA 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JANOVO EVANGELIUM 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JOHN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Acts (cs)", ->
`
expect(p.parse("Skutky apostolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Sk 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("SKUTKY APOSTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SK 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rom (cs)", ->
`
expect(p.parse("List Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Cor (cs)", ->
`
expect(p.parse("Druha list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhaK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhyK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruháK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhýK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHAK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHYK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Cor (cs)", ->
`
expect(p.parse("Prvni list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvniK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvníK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNIK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gal (cs)", ->
`
expect(p.parse("List Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("List Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("LIST GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eph (cs)", ->
`
expect(p.parse("List Efezanum 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezanům 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST EFEZANUM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZANŮM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1")
`
true
describe "Localized book Phil (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Phil (cs)", ->
`
expect(p.parse("List Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("List Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("LIST FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Col (cs)", ->
`
expect(p.parse("List Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Ko 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KO 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Thess (cs)", ->
`
expect(p.parse("Druha list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Te 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TE 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Thess (cs)", ->
`
expect(p.parse("Prvni list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Te 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TE 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Tim (cs)", ->
`
expect(p.parse("Druha list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Tim (cs)", ->
`
expect(p.parse("Prvni list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tm 1:1").osis()).toEqual("1Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Titus (cs)", ->
`
expect(p.parse("List Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Phlm (cs)", ->
`
expect(p.parse("List Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Heb (cs)", ->
`
expect(p.parse("List Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zd 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Žd 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZD 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽD 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jas (cs)", ->
`
expect(p.parse("List Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("List Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakub 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("LIST JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUB 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Pet (cs)", ->
`
expect(p.parse("Druha list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Pet (cs)", ->
`
expect(p.parse("Prvni list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jude (cs)", ->
`
expect(p.parse("List Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("List Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judova 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juda 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("LIST JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDOVA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Tob (cs)", ->
`
expect(p.parse("Tobijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobias 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jdt (cs)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jud 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júd 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bar (cs)", ->
`
expect(p.parse("Kniha Baruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Báruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Barukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Bárukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bár 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sus (cs)", ->
`
expect(p.parse("Zuzana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Zuz 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book 2Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Macc (cs)", ->
`
expect(p.parse("Druha Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3Macc (cs)", ->
`
expect(p.parse("Treti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 4Macc (cs)", ->
`
expect(p.parse("Ctvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Macc (cs)", ->
`
expect(p.parse("Prvni Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual ["cs"]
it "should handle ranges (cs)", ->
expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (cs)", ->
expect(p.parse("Titus 1:1, kapitola 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLA 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitoly 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLY 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitol 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOL 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (cs)", ->
expect(p.parse("Exod 1:1 verše 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERŠE 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (cs)", ->
expect(p.parse("Exod 1:1 a 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 A 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (cs)", ->
expect(p.parse("Ps 3 titul, 4:2, 5:titul").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITUL, 4:2, 5:TITUL").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (cs)", ->
expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (cs)", ->
expect(p.parse("Lev 1 (B21)").osis_and_translations()).toEqual [["Lev.1", "B21"]]
expect(p.parse("lev 1 b21").osis_and_translations()).toEqual [["Lev.1", "B21"]]
it "should handle book ranges (cs)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("První - Třetí J").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (cs)", ->
p.set_options {book_alone_strategy: "full"}
expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28"
expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
| 225005 | bcv_parser = require("../../js/cs_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","<NAME>","<NAME>","<NAME>","<NAME>mos","<NAME>ad","<NAME>","<NAME>","<NAME>ah","Hab","Zeph","Hag","Zech","<NAME>","<NAME>","<NAME>","<NAME>","<NAME>","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
describe "Localized book Gen (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gen (cs)", ->
`
expect(p.parse("Prvni kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzíso<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzíš<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mo<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. k<NAME> Mo<NAME>i<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. k<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. k<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. k<NAME> Mo<NAME>i<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. k<NAME> 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Exod (cs)", ->
`
expect(p.parse("Druha kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bel (cs)", ->
`
expect(p.parse("Bel a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lev (cs)", ->
`
expect(p.parse("Treti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticusi 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levitikus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUSI 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITIKUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Num (cs)", ->
`
expect(p.parse("Ctvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("CTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sir (cs)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclesiasticus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sírachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Wis (cs)", ->
`
expect(p.parse("Moudrost Salomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost Šalomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha Moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrostí 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Mdr 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lam (cs)", ->
`
expect(p.parse("Plac Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jer<NAME>uv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jer<NAME>uv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jer<NAME>v 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plá<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plá<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plá<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč <NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plá<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jer<NAME> 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pl 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("PLAC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PL 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: EpJer (cs)", ->
`
expect(p.parse("List Jeremjasuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjasův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rev (cs)", ->
`
expect(p.parse("Zjeveni svateho Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni svatého Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apokalypsa 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zj 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("ZJEVENI SVATEHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI SVATÉHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOKALYPSA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJ 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrMan (cs)", ->
`
expect(p.parse("Modlitbu Manasse 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Deut (cs)", ->
`
expect(p.parse("Pata kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kni<NAME> Mojz<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžíš<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. k<NAME>í<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. k<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pat<NAME> Mo<NAME>íso<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mo<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. <NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzíš<NAME> 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("PATA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book <NAME> (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME>osh (cs)", ->
`
expect(p.parse("Jozue 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Jz 1:1").osis()).toEqual("Josh.1.1")
p.include_apocrypha(false)
expect(p.parse("JOZUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JZ 1:1").osis()).toEqual("Josh.1.1")
`
true
describe "Localized book Judg (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Judg (cs)", ->
`
expect(p.parse("Soudcu 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Soudců 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sdc 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sd 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("SOUDCU 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SOUDCŮ 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SDC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SD 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ruth (cs)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rút 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RÚT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Esd (cs)", ->
`
expect(p.parse("Prvni Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Esd (cs)", ->
`
expect(p.parse("Druha Ezdr<NAME> 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Isa (cs)", ->
`
expect(p.parse("Izaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajas 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("IZAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Sam (cs)", ->
`
expect(p.parse("Druha kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. <NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("DRU<NAME> K<NAME>UELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DR<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUH<NAME>UELO<NAME> 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Sam (cs)", ->
`
expect(p.parse("Prvni <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 kniha <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I kni<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prv<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("<NAME>. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. <NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. K<NAME>LO<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. <NAME>LO<NAME> 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 K<NAME> SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I KNI<NAME> SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Kgs (cs)", ->
`
expect(p.parse("Druha kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME> 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>ská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME> K<NAME> 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>ha K<NAME>lovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>hy Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>hy K<NAME>lovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>hy K<NAME>lovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("D<NAME>há K<NAME>ovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá K<NAME>ovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Kgs (cs)", ->
`
expect(p.parse("Prvni kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kralov<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. K<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. K<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kr<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. K<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kr<NAME> 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kr 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KR 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Chr (cs)", ->
`
expect(p.parse("Druha Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Chr (cs)", ->
`
expect(p.parse("Prvni Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Pa 1:1").osis()).toEqual("1Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PA 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezra (cs)", ->
`
expect(p.parse("Ezdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdraš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdrás 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdráš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("EZDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRAŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Neh (cs)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjas 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: GkEsth (cs)", ->
`
expect(p.parse("Ester (řecké dodatky) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (řecké části) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Esth (cs)", ->
`
expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Job (cs)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jób 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JÓB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ps (cs)", ->
`
expect(p.parse("Kniha zalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha zalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("KNIHA ZALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ZALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrAzar (cs)", ->
`
expect(p.parse("Azarjasova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjašova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjásova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjášova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Prov (cs)", ->
`
expect(p.parse("Prislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pris 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přis 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Př 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PRISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘ 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eccl (cs)", ->
`
expect(p.parse("Kazatel 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kohelet 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kaz 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("KAZATEL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KOHELET 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KAZ 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: SgThree (cs)", ->
`
expect(p.parse("Pisen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Song (cs)", ->
`
expect(p.parse("Pisen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pis 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pís 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("PISEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PIS 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍS 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book <NAME> (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezek (cs)", ->
`
expect(p.parse("Ezechiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZECHIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book Dan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
p.include_apocrypha(false)
expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hos (cs)", ->
`
expect(p.parse("Ozeas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeaš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeás 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeáš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OZEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEAŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Joel (cs)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jo 1:1").osis()).toEqual("Joel.1.1")
p.include_apocrypha(false)
expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JO 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Amos (cs)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ámos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1")
p.include_apocrypha(false)
expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("ÁMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Obad (cs)", ->
`
expect(p.parse("Abdijas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjá 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book <NAME>ah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME>ah (cs)", ->
`
expect(p.parse("<NAME> 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonaš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonáš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Mic (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mic (cs)", ->
`
expect(p.parse("Michaas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mich 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MICHAAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICH 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Nah (cs)", ->
`
expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
p.include_apocrypha(false)
expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hab (cs)", ->
`
expect(p.parse("Abakuk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Abk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("ABAKUK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("ABK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zeph (cs)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjas 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hag (cs)", ->
`
expect(p.parse("Aggeus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("AGGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zech (cs)", ->
`
expect(p.parse("Zacharias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjas 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACHARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mal (cs)", ->
`
expect(p.parse("Malachias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiaš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiás 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiáš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALACHIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIAŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book <NAME> (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("Evangelium podle Matouse 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelium podle Matouše 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matousovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matoušovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matous 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matouš 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MATOUSE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIUM PODLE MATOUŠE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUSOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUS 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠ 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Mark (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mark (cs)", ->
`
expect(p.parse("Evangelium podle Marka 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Markovo evangelium 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marek 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MARKA 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARKOVO EVANGELIUM 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAREK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book <NAME> (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("Evangelium podle Lukase 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukaše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáse 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukasovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukašovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukásovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukášovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukaš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukás 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukáš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE LUKASE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKAŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁSE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKASOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁSOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book <NAME>John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME>John (cs)", ->
`
expect(p.parse("Prvni list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2John (cs)", ->
`
expect(p.parse("Druha list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3John (cs)", ->
`
expect(p.parse("Treti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("Evangelium podle Jana 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Janovo evangelium 1:1").osis()).toEqual("John.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE JANA 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JANOVO EVANGELIUM 1:1").osis()).toEqual("John.1.1")
expect(p.parse("<NAME> 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME>s (cs)", ->
`
expect(p.parse("Skutky apostolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Sk 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("SKUTKY APOSTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SK 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rom (cs)", ->
`
expect(p.parse("List Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Cor (cs)", ->
`
expect(p.parse("Druha list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhaK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhyK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruháK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhýK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHAK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHYK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Cor (cs)", ->
`
expect(p.parse("Prvni list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvniK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvníK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNIK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gal (cs)", ->
`
expect(p.parse("List Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("List Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("LIST GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eph (cs)", ->
`
expect(p.parse("List Efezanum 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezanům 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST EFEZANUM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZANŮM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1")
`
true
describe "Localized book Phil (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: <NAME> (cs)", ->
`
expect(p.parse("List Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("List Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("LIST FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Col (cs)", ->
`
expect(p.parse("List Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Ko 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KO 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Thess (cs)", ->
`
expect(p.parse("Druha list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Te 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TE 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Thess (cs)", ->
`
expect(p.parse("Prvni list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Te 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TE 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Tim (cs)", ->
`
expect(p.parse("Druha list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Tim (cs)", ->
`
expect(p.parse("Prvni list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tm 1:1").osis()).toEqual("1Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Titus (cs)", ->
`
expect(p.parse("List Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Phlm (cs)", ->
`
expect(p.parse("List Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Heb (cs)", ->
`
expect(p.parse("List Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zd 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Žd 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZD 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽD 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jas (cs)", ->
`
expect(p.parse("List Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("List Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakub 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("LIST JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUB 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Pet (cs)", ->
`
expect(p.parse("Druha list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Pet (cs)", ->
`
expect(p.parse("Prvni list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jude (cs)", ->
`
expect(p.parse("List Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("List Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judova 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juda 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("LIST JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDOVA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Tob (cs)", ->
`
expect(p.parse("Tobijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobias 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jdt (cs)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jud 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júd 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bar (cs)", ->
`
expect(p.parse("Kniha Baruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Báruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Barukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Bárukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bár 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sus (cs)", ->
`
expect(p.parse("Zuzana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Zuz 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book 2Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Macc (cs)", ->
`
expect(p.parse("Druha Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3Macc (cs)", ->
`
expect(p.parse("Treti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 4Macc (cs)", ->
`
expect(p.parse("Ctvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Macc (cs)", ->
`
expect(p.parse("Prvni Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual ["cs"]
it "should handle ranges (cs)", ->
expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (cs)", ->
expect(p.parse("Titus 1:1, kapitola 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLA 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitoly 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLY 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitol 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOL 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (cs)", ->
expect(p.parse("Exod 1:1 verše 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERŠE 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (cs)", ->
expect(p.parse("Exod 1:1 a 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 A 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (cs)", ->
expect(p.parse("Ps 3 titul, 4:2, 5:titul").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITUL, 4:2, 5:TITUL").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (cs)", ->
expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (cs)", ->
expect(p.parse("Lev 1 (B21)").osis_and_translations()).toEqual [["Lev.1", "B21"]]
expect(p.parse("lev 1 b21").osis_and_translations()).toEqual [["Lev.1", "B21"]]
it "should handle book ranges (cs)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("První - Třetí J").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (cs)", ->
p.set_options {book_alone_strategy: "full"}
expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28"
expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
| true | bcv_parser = require("../../js/cs_bcv_parser.js").bcv_parser
describe "Parsing", ->
p = {}
beforeEach ->
p = new bcv_parser
p.options.osis_compaction_strategy = "b"
p.options.sequence_combination_strategy = "combine"
it "should round-trip OSIS references", ->
p.set_options osis_compaction_strategy: "bc"
books = ["Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth","1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh","Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam","Ezek","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PImos","PI:NAME:<NAME>END_PIad","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PIah","Hab","Zeph","Hag","Zech","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","PI:NAME:<NAME>END_PI","Acts","Rom","1Cor","2Cor","Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim","Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John","3John","Jude","Rev"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
it "should round-trip OSIS Apocrypha references", ->
p.set_options osis_compaction_strategy: "bc", ps151_strategy: "b"
p.include_apocrypha true
books = ["Tob","Jdt","GkEsth","Wis","Sir","Bar","PrAzar","Sus","Bel","SgThree","EpJer","1Macc","2Macc","3Macc","4Macc","1Esd","2Esd","PrMan","Ps151"]
for book in books
bc = book + ".1"
bcv = bc + ".1"
bcv_range = bcv + "-" + bc + ".2"
expect(p.parse(bc).osis()).toEqual bc
expect(p.parse(bcv).osis()).toEqual bcv
expect(p.parse(bcv_range).osis()).toEqual bcv_range
p.set_options ps151_strategy: "bc"
expect(p.parse("Ps151.1").osis()).toEqual "Ps.151"
expect(p.parse("Ps151.1.1").osis()).toEqual "Ps.151.1"
expect(p.parse("Ps151.1-Ps151.2").osis()).toEqual "Ps.151.1-Ps.151.2"
p.include_apocrypha false
for book in books
bc = book + ".1"
expect(p.parse(bc).osis()).toEqual ""
it "should handle a preceding character", ->
expect(p.parse(" Gen 1").osis()).toEqual "Gen.1"
expect(p.parse("Matt5John3").osis()).toEqual "Matt.5,John.3"
expect(p.parse("1Ps 1").osis()).toEqual ""
expect(p.parse("11Sam 1").osis()).toEqual ""
describe "Localized book Gen (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gen (cs)", ->
`
expect(p.parse("Prvni kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha MojzísoPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha MojzíšPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kniha MoPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kPI:NAME:<NAME>END_PI MoPI:NAME:<NAME>END_PIiPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. kPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kPI:NAME:<NAME>END_PI MoPI:NAME:<NAME>END_PIiPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. kPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I kniha Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Prvni Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("První Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojzíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžisova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžišova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžísova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I Mojžíšova 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Genesis 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gen 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("Gn 1:1").osis()).toEqual("Gen.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNI MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("PRVNÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I. MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("1 MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJZÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽISOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽIŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍSOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("I MOJŽÍŠOVA 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GENESIS 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GEN 1:1").osis()).toEqual("Gen.1.1")
expect(p.parse("GN 1:1").osis()).toEqual("Gen.1.1")
`
true
describe "Localized book Exod (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Exod (cs)", ->
`
expect(p.parse("Druha kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 kniha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druha Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhy Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhá Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Druhý Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojzíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžisova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžišova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžísova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 Mojžíšova 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exodus 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Exod 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("Ex 1:1").osis()).toEqual("Exod.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHA MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHY MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("DRUHÝ MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2. MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("II MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJZÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽISOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽIŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍSOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("2 MOJŽÍŠOVA 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXODUS 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EXOD 1:1").osis()).toEqual("Exod.1.1")
expect(p.parse("EX 1:1").osis()).toEqual("Exod.1.1")
`
true
describe "Localized book Bel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bel (cs)", ->
`
expect(p.parse("Bel a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél a drak 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bel 1:1").osis()).toEqual("Bel.1.1")
expect(p.parse("Bél 1:1").osis()).toEqual("Bel.1.1")
`
true
describe "Localized book Lev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lev (cs)", ->
`
expect(p.parse("Treti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 kniha Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Treti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Tretí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třeti Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Třetí Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojzíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžisova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžišova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžísova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 Mojžíšova 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticusi 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Leviticus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Levitikus 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lev 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("Lv 1:1").osis()).toEqual("Lev.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TRETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETI MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("TŘETÍ MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("III MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3. MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJZÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽISOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽIŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍSOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("3 MOJŽÍŠOVA 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUSI 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITICUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEVITIKUS 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LEV 1:1").osis()).toEqual("Lev.1.1")
expect(p.parse("LV 1:1").osis()).toEqual("Lev.1.1")
`
true
describe "Localized book Num (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Num (cs)", ->
`
expect(p.parse("Ctvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 kniha Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Ctvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrta Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Čtvrtá Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojzíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžisova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžišova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžísova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 Mojžíšova 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Numeri 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Num 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("Nu 1:1").osis()).toEqual("Num.1.1")
p.include_apocrypha(false)
expect(p.parse("CTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("CTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTA MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("ČTVRTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4. MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("IV MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJZÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽISOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽIŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍSOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("4 MOJŽÍŠOVA 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUMERI 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NUM 1:1").osis()).toEqual("Num.1.1")
expect(p.parse("NU 1:1").osis()).toEqual("Num.1.1")
`
true
describe "Localized book Sir (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sir (cs)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Ecclesiasticus 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sirachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sírachovec 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sir 1:1").osis()).toEqual("Sir.1.1")
expect(p.parse("Sír 1:1").osis()).toEqual("Sir.1.1")
`
true
describe "Localized book Wis (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Wis (cs)", ->
`
expect(p.parse("Moudrost Salomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost Šalomounova 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha Moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrosti 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Kniha moudrostí 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Moudrost 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Mdr 1:1").osis()).toEqual("Wis.1.1")
expect(p.parse("Wis 1:1").osis()).toEqual("Wis.1.1")
`
true
describe "Localized book Lam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Lam (cs)", ->
`
expect(p.parse("Plac Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač JerPI:NAME:<NAME>END_PIuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác JerPI:NAME:<NAME>END_PIuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác JerPI:NAME:<NAME>END_PIv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremiášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjašův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjásův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác Jeremjášův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasuv 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč Jeremiasův 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PláPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PláPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PláPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PláPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč JerPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha narků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nařků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nárků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářku 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Kniha nářků 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plac 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plač 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Plác 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pláč 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Lam 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("Pl 1:1").osis()).toEqual("Lam.1.1")
p.include_apocrypha(false)
expect(p.parse("PLAC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMIÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJASŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJAŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁSŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠUV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ JEREMJÁŠŮV 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NARKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NAŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁRKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKU 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("KNIHA NÁŘKŮ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLAČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁC 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PLÁČ 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("LAM 1:1").osis()).toEqual("Lam.1.1")
expect(p.parse("PL 1:1").osis()).toEqual("Lam.1.1")
`
true
describe "Localized book EpJer (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: EpJer (cs)", ->
`
expect(p.parse("List Jeremjasuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjasův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjašův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjásův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášuv 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("List Jeremjášův 1:1").osis()).toEqual("EpJer.1.1")
expect(p.parse("EpJer 1:1").osis()).toEqual("EpJer.1.1")
`
true
describe "Localized book Rev (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rev (cs)", ->
`
expect(p.parse("Zjeveni svateho Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni svatého Jana 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení Janovo 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Kniha Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Apokalypsa 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjeveni 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zjevení 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Rev 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("Zj 1:1").osis()).toEqual("Rev.1.1")
p.include_apocrypha(false)
expect(p.parse("ZJEVENI SVATEHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI SVATÉHO JANA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ JANOVO 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("KNIHA ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("APOKALYPSA 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENI 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJEVENÍ 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("REV 1:1").osis()).toEqual("Rev.1.1")
expect(p.parse("ZJ 1:1").osis()).toEqual("Rev.1.1")
`
true
describe "Localized book PrMan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrMan (cs)", ->
`
expect(p.parse("Modlitbu Manasse 1:1").osis()).toEqual("PrMan.1.1")
expect(p.parse("PrMan 1:1").osis()).toEqual("PrMan.1.1")
`
true
describe "Localized book Deut (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Deut (cs)", ->
`
expect(p.parse("Pata kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniPI:NAME:<NAME>END_PI MojzPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. kniha MojžíšPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kPI:NAME:<NAME>END_PIíPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. kPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V kniha Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pata Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PatPI:NAME:<NAME>END_PI MoPI:NAME:<NAME>END_PIísoPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Patá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Páta Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Pátá Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deuteronomium 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MoPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MojzíšPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojzíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžisova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžišova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžísova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V Mojžíšova 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Deut 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("Dt 1:1").osis()).toEqual("Deut.1.1")
p.include_apocrypha(false)
expect(p.parse("PATA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V KNIHA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PATÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTA MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("PÁTÁ MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUTERONOMIUM 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V. MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("5 MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJZÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽISOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽIŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍSOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("V MOJŽÍŠOVA 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DEUT 1:1").osis()).toEqual("Deut.1.1")
expect(p.parse("DT 1:1").osis()).toEqual("Deut.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PIosh (cs)", ->
`
expect(p.parse("Jozue 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Josh 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Joz 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("Jz 1:1").osis()).toEqual("Josh.1.1")
p.include_apocrypha(false)
expect(p.parse("JOZUE 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOSH 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JOZ 1:1").osis()).toEqual("Josh.1.1")
expect(p.parse("JZ 1:1").osis()).toEqual("Josh.1.1")
`
true
describe "Localized book Judg (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Judg (cs)", ->
`
expect(p.parse("Soudcu 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Soudců 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Judg 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sdc 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("Sd 1:1").osis()).toEqual("Judg.1.1")
p.include_apocrypha(false)
expect(p.parse("SOUDCU 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SOUDCŮ 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("JUDG 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SDC 1:1").osis()).toEqual("Judg.1.1")
expect(p.parse("SD 1:1").osis()).toEqual("Judg.1.1")
`
true
describe "Localized book Ruth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ruth (cs)", ->
`
expect(p.parse("Ruth 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rut 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rút 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("Rt 1:1").osis()).toEqual("Ruth.1.1")
p.include_apocrypha(false)
expect(p.parse("RUTH 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RUT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RÚT 1:1").osis()).toEqual("Ruth.1.1")
expect(p.parse("RT 1:1").osis()).toEqual("Ruth.1.1")
`
true
describe "Localized book 1Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Esd (cs)", ->
`
expect(p.parse("Prvni Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("Prvni Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("První Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I. Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1 Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdras 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdraš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdrás 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("I Ezdráš 1:1").osis()).toEqual("1Esd.1.1")
expect(p.parse("1Esd 1:1").osis()).toEqual("1Esd.1.1")
`
true
describe "Localized book 2Esd (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Esd (cs)", ->
`
expect(p.parse("Druha EzdrPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druha Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhy Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhá Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("Druhý Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2. Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("II Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdras 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdraš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdrás 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2 Ezdráš 1:1").osis()).toEqual("2Esd.1.1")
expect(p.parse("2Esd 1:1").osis()).toEqual("2Esd.1.1")
`
true
describe "Localized book Isa (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Isa (cs)", ->
`
expect(p.parse("Izaias 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izaiáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajas 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajaš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajás 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Izajáš 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Isa 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("Iz 1:1").osis()).toEqual("Isa.1.1")
p.include_apocrypha(false)
expect(p.parse("IZAIAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAIÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJAŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁS 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZAJÁŠ 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("ISA 1:1").osis()).toEqual("Isa.1.1")
expect(p.parse("IZ 1:1").osis()).toEqual("Isa.1.1")
`
true
describe "Localized book 2Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Sam (cs)", ->
`
expect(p.parse("Druha kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 kniha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha Samuelova 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Samuel 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druha S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhy S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhá S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("Druhý S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2Sam 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUPI:NAME:<NAME>END_PI KPI:NAME:<NAME>END_PIUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHPI:NAME:<NAME>END_PIUELOPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 KNIHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUELOVA 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAMUEL 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHA S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHY S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÁ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("DRUHÝ S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2. S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2SAM 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("II S 1:1").osis()).toEqual("2Sam.1.1")
expect(p.parse("2 S 1:1").osis()).toEqual("2Sam.1.1")
`
true
describe "Localized book 1Sam (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Sam (cs)", ->
`
expect(p.parse("Prvni PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 kniha PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I kniPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PrvPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("Prvni S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("První S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1Sam 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ KNIHA SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. KPI:NAME:<NAME>END_PILOPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. PI:NAME:<NAME>END_PILOPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 KPI:NAME:<NAME>END_PI SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I KNIPI:NAME:<NAME>END_PI SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUELOVA 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAMUEL 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNI S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("PRVNÍ S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1SAM 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I. S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("1 S 1:1").osis()).toEqual("1Sam.1.1")
expect(p.parse("I S 1:1").osis()).toEqual("1Sam.1.1")
`
true
describe "Localized book 2Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Kgs (cs)", ->
`
expect(p.parse("Druha kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 kniha královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PI KPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIha KPI:NAME:<NAME>END_PIlovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIhy Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIhy KPI:NAME:<NAME>END_PIlovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIhy KPI:NAME:<NAME>END_PIlovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DPI:NAME:<NAME>END_PIhá KPI:NAME:<NAME>END_PIovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá KPI:NAME:<NAME>END_PIovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kralovská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královska 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Královská 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druha Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhy Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhá Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("Druhý Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kral 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Král 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 Kr 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2Kgs 1:1").osis()).toEqual("2Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRALOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKA 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁLOVSKÁ 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHA KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHY KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÁ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("DRUHÝ KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRAL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KRÁL 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2. KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("II KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2 KR 1:1").osis()).toEqual("2Kgs.1.1")
expect(p.parse("2KGS 1:1").osis()).toEqual("2Kgs.1.1")
`
true
describe "Localized book 1Kgs (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Kgs (cs)", ->
`
expect(p.parse("Prvni kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I kniha královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KralovPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kralovská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královska 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Královská 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("Prvni Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("První Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KrPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KrPI:NAME:<NAME>END_PI 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kral 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Král 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 Kr 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1Kgs 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I Kr 1:1").osis()).toEqual("1Kgs.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KNIHA KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRALOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKA 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁLOVSKÁ 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNI KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("PRVNÍ KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRAL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KRÁL 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I. KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1 KR 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("1KGS 1:1").osis()).toEqual("1Kgs.1.1")
expect(p.parse("I KR 1:1").osis()).toEqual("1Kgs.1.1")
`
true
describe "Localized book 2Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Chr (cs)", ->
`
expect(p.parse("Druha Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Paralipomenon 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 kniha kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisu 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Letopisů 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Kronik 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druha Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhy Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhá Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("Druhý Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 Pa 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2Chr 1:1").osis()).toEqual("2Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PARALIPOMENON 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KNIHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISU 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 LETOPISŮ 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 KRONIK 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHA PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHY PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÁ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("DRUHÝ PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2. PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("II PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2 PA 1:1").osis()).toEqual("2Chr.1.1")
expect(p.parse("2CHR 1:1").osis()).toEqual("2Chr.1.1")
`
true
describe "Localized book 1Chr (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Chr (cs)", ->
`
expect(p.parse("Prvni Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Paralipomenon 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I kniha kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisu 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Letopisů 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Kronik 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("Prvni Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("První Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 Pa 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1Chr 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I Pa 1:1").osis()).toEqual("1Chr.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PARALIPOMENON 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KNIHA KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISU 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I LETOPISŮ 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I KRONIK 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNI PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("PRVNÍ PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I. PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1 PA 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("1CHR 1:1").osis()).toEqual("1Chr.1.1")
expect(p.parse("I PA 1:1").osis()).toEqual("1Chr.1.1")
`
true
describe "Localized book Ezra (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezra (cs)", ->
`
expect(p.parse("Ezdras 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdraš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdrás 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezdráš 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezra 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("Ezd 1:1").osis()).toEqual("Ezra.1.1")
p.include_apocrypha(false)
expect(p.parse("EZDRAS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRAŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁS 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZDRÁŠ 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZRA 1:1").osis()).toEqual("Ezra.1.1")
expect(p.parse("EZD 1:1").osis()).toEqual("Ezra.1.1")
`
true
describe "Localized book Neh (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Neh (cs)", ->
`
expect(p.parse("Nehemias 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemiáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjas 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjaš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjás 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Nehemjáš 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("Neh 1:1").osis()).toEqual("Neh.1.1")
p.include_apocrypha(false)
expect(p.parse("NEHEMIAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMIÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJAŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁS 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEHEMJÁŠ 1:1").osis()).toEqual("Neh.1.1")
expect(p.parse("NEH 1:1").osis()).toEqual("Neh.1.1")
`
true
describe "Localized book GkEsth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: GkEsth (cs)", ->
`
expect(p.parse("Ester (řecké dodatky) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester (řecké části) 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké dodatky 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester recké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecke části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké casti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké cásti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké časti 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("Ester řecké části 1:1").osis()).toEqual("GkEsth.1.1")
expect(p.parse("GkEsth 1:1").osis()).toEqual("GkEsth.1.1")
`
true
describe "Localized book Esth (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Esth (cs)", ->
`
expect(p.parse("Ester 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Esth 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("Est 1:1").osis()).toEqual("Esth.1.1")
p.include_apocrypha(false)
expect(p.parse("ESTER 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("ESTH 1:1").osis()).toEqual("Esth.1.1")
expect(p.parse("EST 1:1").osis()).toEqual("Esth.1.1")
`
true
describe "Localized book Job (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Job (cs)", ->
`
expect(p.parse("Job 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jób 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("Jb 1:1").osis()).toEqual("Job.1.1")
p.include_apocrypha(false)
expect(p.parse("JOB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JÓB 1:1").osis()).toEqual("Job.1.1")
expect(p.parse("JB 1:1").osis()).toEqual("Job.1.1")
`
true
describe "Localized book Ps (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ps (cs)", ->
`
expect(p.parse("Kniha zalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha zalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmu 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Kniha žalmů 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalmy 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Zalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Žalm 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ps 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
p.include_apocrypha(false)
expect(p.parse("KNIHA ZALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ZALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMU 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("KNIHA ŽALMŮ 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALMY 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ZALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("ŽALM 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("PS 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Z 1:1").osis()).toEqual("Ps.1.1")
expect(p.parse("Ž 1:1").osis()).toEqual("Ps.1.1")
`
true
describe "Localized book PrAzar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PrAzar (cs)", ->
`
expect(p.parse("Azarjasova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjašova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjásova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("Azarjášova modlitba 1:1").osis()).toEqual("PrAzar.1.1")
expect(p.parse("PrAzar 1:1").osis()).toEqual("PrAzar.1.1")
`
true
describe "Localized book Prov (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Prov (cs)", ->
`
expect(p.parse("Prislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Salomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví Šalomounova 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Príslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přislovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přisloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Příslovi 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přísloví 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pris 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prov 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Prís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přis 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Přís 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Pr 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("Př 1:1").osis()).toEqual("Prov.1.1")
p.include_apocrypha(false)
expect(p.parse("PRISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ SALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ ŠALOMOUNOVA 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘISLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVI 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍSLOVÍ 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PROV 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PRÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘIS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘÍS 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PR 1:1").osis()).toEqual("Prov.1.1")
expect(p.parse("PŘ 1:1").osis()).toEqual("Prov.1.1")
`
true
describe "Localized book Eccl (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eccl (cs)", ->
`
expect(p.parse("Kazatel 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kohelet 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Eccl 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("Kaz 1:1").osis()).toEqual("Eccl.1.1")
p.include_apocrypha(false)
expect(p.parse("KAZATEL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KOHELET 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("ECCL 1:1").osis()).toEqual("Eccl.1.1")
expect(p.parse("KAZ 1:1").osis()).toEqual("Eccl.1.1")
`
true
describe "Localized book SgThree (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: SgThree (cs)", ->
`
expect(p.parse("Pisen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Pisen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Piseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Písen mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mladenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládencu v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horíci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v horící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořici peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořicí peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hoříci peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Píseň mládenců v hořící peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tri muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muzi v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpalené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálene peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("Tři muži v rozpálené peci 1:1").osis()).toEqual("SgThree.1.1")
expect(p.parse("SgThree 1:1").osis()).toEqual("SgThree.1.1")
`
true
describe "Localized book Song (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Song (cs)", ->
`
expect(p.parse("Pisen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Salamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň Šalamounova 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň pisní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písni 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň písní 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pisen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Piseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Písen 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Píseň 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Song 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pis 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("Pís 1:1").osis()).toEqual("Song.1.1")
p.include_apocrypha(false)
expect(p.parse("PISEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ SALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ ŠALAMOUNOVA 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PISNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNI 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ PÍSNÍ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PISEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEN 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍSEŇ 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("SONG 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PIS 1:1").osis()).toEqual("Song.1.1")
expect(p.parse("PÍS 1:1").osis()).toEqual("Song.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jer 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("Jr 1:1").osis()).toEqual("Jer.1.1")
p.include_apocrypha(false)
expect(p.parse("JEREMIAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMIÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJAŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁS 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JEREMJÁŠ 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JER 1:1").osis()).toEqual("Jer.1.1")
expect(p.parse("JR 1:1").osis()).toEqual("Jer.1.1")
`
true
describe "Localized book Ezek (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Ezek (cs)", ->
`
expect(p.parse("Ezechiel 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ezek 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("Ez 1:1").osis()).toEqual("Ezek.1.1")
p.include_apocrypha(false)
expect(p.parse("EZECHIEL 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZEK 1:1").osis()).toEqual("Ezek.1.1")
expect(p.parse("EZ 1:1").osis()).toEqual("Ezek.1.1")
`
true
describe "Localized book Dan (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Dan 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("Da 1:1").osis()).toEqual("Dan.1.1")
p.include_apocrypha(false)
expect(p.parse("DANIEL 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DAN 1:1").osis()).toEqual("Dan.1.1")
expect(p.parse("DA 1:1").osis()).toEqual("Dan.1.1")
`
true
describe "Localized book Hos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hos (cs)", ->
`
expect(p.parse("Ozeas 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeaš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeás 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Ozeáš 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Hos 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("Oz 1:1").osis()).toEqual("Hos.1.1")
p.include_apocrypha(false)
expect(p.parse("OZEAS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEAŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZEÁŠ 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("HOS 1:1").osis()).toEqual("Hos.1.1")
expect(p.parse("OZ 1:1").osis()).toEqual("Hos.1.1")
`
true
describe "Localized book Joel (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Joel (cs)", ->
`
expect(p.parse("Joel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jóel 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jl 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("Jo 1:1").osis()).toEqual("Joel.1.1")
p.include_apocrypha(false)
expect(p.parse("JOEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JÓEL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JL 1:1").osis()).toEqual("Joel.1.1")
expect(p.parse("JO 1:1").osis()).toEqual("Joel.1.1")
`
true
describe "Localized book Amos (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Amos (cs)", ->
`
expect(p.parse("Amos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Ámos 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("Am 1:1").osis()).toEqual("Amos.1.1")
p.include_apocrypha(false)
expect(p.parse("AMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("ÁMOS 1:1").osis()).toEqual("Amos.1.1")
expect(p.parse("AM 1:1").osis()).toEqual("Amos.1.1")
`
true
describe "Localized book Obad (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Obad (cs)", ->
`
expect(p.parse("Abdijas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdijáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjas 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdias 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiaš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiás 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abdiáš 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadja 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obadjá 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Obad 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("Abd 1:1").osis()).toEqual("Obad.1.1")
p.include_apocrypha(false)
expect(p.parse("ABDIJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIAŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁS 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABDIÁŠ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJA 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBADJÁ 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("OBAD 1:1").osis()).toEqual("Obad.1.1")
expect(p.parse("ABD 1:1").osis()).toEqual("Obad.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PIah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PIah (cs)", ->
`
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonas 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonaš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonás 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jonáš 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("Jon 1:1").osis()).toEqual("Jonah.1.1")
p.include_apocrypha(false)
expect(p.parse("JONAH 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONAŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁS 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JONÁŠ 1:1").osis()).toEqual("Jonah.1.1")
expect(p.parse("JON 1:1").osis()).toEqual("Jonah.1.1")
`
true
describe "Localized book Mic (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mic (cs)", ->
`
expect(p.parse("Michaas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Michaáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheas 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheaš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheás 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Micheáš 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mich 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mic 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("Mi 1:1").osis()).toEqual("Mic.1.1")
p.include_apocrypha(false)
expect(p.parse("MICHAAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHAÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEAŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁS 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICHEÁŠ 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MICH 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MIC 1:1").osis()).toEqual("Mic.1.1")
expect(p.parse("MI 1:1").osis()).toEqual("Mic.1.1")
`
true
describe "Localized book Nah (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Nah (cs)", ->
`
expect(p.parse("Nahum 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Nah 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("Na 1:1").osis()).toEqual("Nah.1.1")
p.include_apocrypha(false)
expect(p.parse("NAHUM 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NAH 1:1").osis()).toEqual("Nah.1.1")
expect(p.parse("NA 1:1").osis()).toEqual("Nah.1.1")
`
true
describe "Localized book Hab (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hab (cs)", ->
`
expect(p.parse("Abakuk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Abk 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("Hab 1:1").osis()).toEqual("Hab.1.1")
p.include_apocrypha(false)
expect(p.parse("ABAKUK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("ABK 1:1").osis()).toEqual("Hab.1.1")
expect(p.parse("HAB 1:1").osis()).toEqual("Hab.1.1")
`
true
describe "Localized book Zeph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zeph (cs)", ->
`
expect(p.parse("Sofonias 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofoniáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjas 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjaš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjás 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sofonjáš 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Zeph 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("Sf 1:1").osis()).toEqual("Zeph.1.1")
p.include_apocrypha(false)
expect(p.parse("SOFONIAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONIÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJAŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁS 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SOFONJÁŠ 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("ZEPH 1:1").osis()).toEqual("Zeph.1.1")
expect(p.parse("SF 1:1").osis()).toEqual("Zeph.1.1")
`
true
describe "Localized book Hag (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Hag (cs)", ->
`
expect(p.parse("Aggeus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ageus 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Hag 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("Ag 1:1").osis()).toEqual("Hag.1.1")
p.include_apocrypha(false)
expect(p.parse("AGGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AGEUS 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("HAG 1:1").osis()).toEqual("Hag.1.1")
expect(p.parse("AG 1:1").osis()).toEqual("Hag.1.1")
`
true
describe "Localized book Zech (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Zech (cs)", ->
`
expect(p.parse("Zacharias 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zachariáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjas 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjaš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjás 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zacharjáš 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Zech 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("Za 1:1").osis()).toEqual("Zech.1.1")
p.include_apocrypha(false)
expect(p.parse("ZACHARIAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARIÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJAŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁS 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZACHARJÁŠ 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZECH 1:1").osis()).toEqual("Zech.1.1")
expect(p.parse("ZA 1:1").osis()).toEqual("Zech.1.1")
`
true
describe "Localized book Mal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mal (cs)", ->
`
expect(p.parse("Malachias 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiaš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiás 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Malachiáš 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("Mal 1:1").osis()).toEqual("Mal.1.1")
p.include_apocrypha(false)
expect(p.parse("MALACHIAS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIAŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁS 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MALACHIÁŠ 1:1").osis()).toEqual("Mal.1.1")
expect(p.parse("MAL 1:1").osis()).toEqual("Mal.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("Evangelium podle Matouse 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Evangelium podle Matouše 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matousovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matoušovo evangelium 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matous 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matouš 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Matt 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mat 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("Mt 1:1").osis()).toEqual("Matt.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MATOUSE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("EVANGELIUM PODLE MATOUŠE 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUSOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠOVO EVANGELIUM 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUS 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATOUŠ 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MATT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MAT 1:1").osis()).toEqual("Matt.1.1")
expect(p.parse("MT 1:1").osis()).toEqual("Matt.1.1")
`
true
describe "Localized book Mark (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Mark (cs)", ->
`
expect(p.parse("Evangelium podle Marka 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Markovo evangelium 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Marek 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mark 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("Mk 1:1").osis()).toEqual("Mark.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE MARKA 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARKOVO EVANGELIUM 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MAREK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MARK 1:1").osis()).toEqual("Mark.1.1")
expect(p.parse("MK 1:1").osis()).toEqual("Mark.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PI (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("Evangelium podle Lukase 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukaše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáse 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Evangelium podle Lukáše 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukasovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukašovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukásovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukášovo evangelium 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukas 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukaš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukás 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lukáš 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Luke 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("Lk 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE LUKASE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKAŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁSE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("EVANGELIUM PODLE LUKÁŠE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKASOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁSOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠOVO EVANGELIUM 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKAŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁS 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKÁŠ 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LUKE 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("LK 1:1").osis()).toEqual("Luke.1.1")
expect(p.parse("L 1:1").osis()).toEqual("Luke.1.1")
`
true
describe "Localized book PI:NAME:<NAME>END_PIJohn (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PIJohn (cs)", ->
`
expect(p.parse("Prvni list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I list Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janova 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Januv 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Janův 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("Prvni J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("První J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1John 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I Jan 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I LIST JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANOVA 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANUV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JANŮV 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNI J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("PRVNÍ J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1JOHN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I JAN 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I. J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("1 J 1:1").osis()).toEqual("1John.1.1")
expect(p.parse("I J 1:1").osis()).toEqual("1John.1.1")
`
true
describe "Localized book 2John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2John (cs)", ->
`
expect(p.parse("Druha list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 list Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janova 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Januv 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Janův 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druha J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhy J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhá J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("Druhý J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 Jan 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2John 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 LIST JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANOVA 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANUV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JANŮV 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHA J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHY J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÁ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("DRUHÝ J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 JAN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2JOHN 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2. J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("II J 1:1").osis()).toEqual("2John.1.1")
expect(p.parse("2 J 1:1").osis()).toEqual("2John.1.1")
`
true
describe "Localized book 3John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3John (cs)", ->
`
expect(p.parse("Treti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 list Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janova 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Januv 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Janův 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Treti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Tretí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třeti J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("Třetí J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 Jan 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3John 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
p.include_apocrypha(false)
expect(p.parse("TRETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 LIST JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANOVA 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANUV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JANŮV 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TRETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETI J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("TŘETÍ J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 JAN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3JOHN 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("III J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3. J 1:1").osis()).toEqual("3John.1.1")
expect(p.parse("3 J 1:1").osis()).toEqual("3John.1.1")
`
true
describe "Localized book John (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("Evangelium podle Jana 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Janovo evangelium 1:1").osis()).toEqual("John.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("John.1.1")
expect(p.parse("Jan 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
p.include_apocrypha(false)
expect(p.parse("EVANGELIUM PODLE JANA 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JANOVO EVANGELIUM 1:1").osis()).toEqual("John.1.1")
expect(p.parse("PI:NAME:<NAME>END_PI 1:1").osis()).toEqual("John.1.1")
expect(p.parse("JAN 1:1").osis()).toEqual("John.1.1")
expect(p.parse("J 1:1").osis()).toEqual("John.1.1")
`
true
describe "Localized book Acts (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PIs (cs)", ->
`
expect(p.parse("Skutky apostolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolske 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolské 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apostolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolu 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolü 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky apoštolů 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Skutky 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Acts 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("Sk 1:1").osis()).toEqual("Acts.1.1")
p.include_apocrypha(false)
expect(p.parse("SKUTKY APOSTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKE 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLSKÉ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOSTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLU 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLÜ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY APOŠTOLŮ 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SKUTKY 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("ACTS 1:1").osis()).toEqual("Acts.1.1")
expect(p.parse("SK 1:1").osis()).toEqual("Acts.1.1")
`
true
describe "Localized book Rom (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Rom (cs)", ->
`
expect(p.parse("List Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("List Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rímanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řimanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanum 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Římanům 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rom 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Rím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řim 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Řím 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("LIST ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANUM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍMANŮM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ROM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("RÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘIM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("ŘÍM 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("R 1:1").osis()).toEqual("Rom.1.1")
expect(p.parse("Ř 1:1").osis()).toEqual("Rom.1.1")
`
true
describe "Localized book 2Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Cor (cs)", ->
`
expect(p.parse("Druha list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 list Korinským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintskym 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Korintským 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druha K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhy K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhá K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("Druhý K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhaK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhyK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruháK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DruhýK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Cor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2Kor 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 LIST KORINSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKYM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KORINTSKÝM 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHA K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHY K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝ K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHAK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHYK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÁK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("DRUHÝK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2. K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2COR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2KOR 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("II.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2 K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2.K 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("IIK 1:1").osis()).toEqual("2Cor.1.1")
expect(p.parse("2K 1:1").osis()).toEqual("2Cor.1.1")
`
true
describe "Localized book 1Cor (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Cor (cs)", ->
`
expect(p.parse("Prvni list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I list Korinským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintskym 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Korintským 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("Prvni K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("První K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvniK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PrvníK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I Kor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1Cor 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I LIST KORINSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKYM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KORINTSKÝM 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNI K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍ K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNIK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("PRVNÍK 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I KOR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1COR 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I. K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1 K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("I.K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("1K 1:1").osis()).toEqual("1Cor.1.1")
expect(p.parse("IK 1:1").osis()).toEqual("1Cor.1.1")
`
true
describe "Localized book Gal (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Gal (cs)", ->
`
expect(p.parse("List Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("List Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatskym 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Galatským 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Gal 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("Ga 1:1").osis()).toEqual("Gal.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("LIST GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKYM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GALATSKÝM 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GAL 1:1").osis()).toEqual("Gal.1.1")
expect(p.parse("GA 1:1").osis()).toEqual("Gal.1.1")
`
true
describe "Localized book Eph (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Eph (cs)", ->
`
expect(p.parse("List Efezanum 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezanům 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("List Efézským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efezským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeskym 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Efeským 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Eph 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("Ef 1:1").osis()).toEqual("Eph.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST EFEZANUM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZANŮM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("LIST EFÉZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFEZSKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKYM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EFESKÝM 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EPH 1:1").osis()).toEqual("Eph.1.1")
expect(p.parse("EF 1:1").osis()).toEqual("Eph.1.1")
`
true
describe "Localized book Phil (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: PI:NAME:<NAME>END_PI (cs)", ->
`
expect(p.parse("List Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("List Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipenským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipskym 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Filipským 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Phil 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("Fp 1:1").osis()).toEqual("Phil.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("LIST FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPENSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKYM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FILIPSKÝM 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("PHIL 1:1").osis()).toEqual("Phil.1.1")
expect(p.parse("FP 1:1").osis()).toEqual("Phil.1.1")
`
true
describe "Localized book Col (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Col (cs)", ->
`
expect(p.parse("List Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("List Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolossenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosenským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanum 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kolosanům 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloskym 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Koloským 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Col 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Kol 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("Ko 1:1").osis()).toEqual("Col.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("LIST KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSENSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANUM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSANŮM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKYM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOLOSKÝM 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("COL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KOL 1:1").osis()).toEqual("Col.1.1")
expect(p.parse("KO 1:1").osis()).toEqual("Col.1.1")
`
true
describe "Localized book 2Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Thess (cs)", ->
`
expect(p.parse("Druha list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tessalonicenským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 list Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Tesalonickým 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Solunským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňskym 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Soluňským 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druha Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhy Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhá Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("Druhý Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2Thess 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Sol 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II Te 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 Te 1:1").osis()).toEqual("2Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESSALONICENSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 LIST SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TESALONICKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUNSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKYM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOLUŇSKÝM 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHA TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHY TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÁ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("DRUHÝ TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2THESS 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 SOL 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2. TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("II TE 1:1").osis()).toEqual("2Thess.1.1")
expect(p.parse("2 TE 1:1").osis()).toEqual("2Thess.1.1")
`
true
describe "Localized book 1Thess (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Thess (cs)", ->
`
expect(p.parse("Prvni list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tessalonicenským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I list Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Tesalonickým 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Solunským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňskym 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Soluňským 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("Prvni Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("První Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1Thess 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Sol 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 Te 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I Te 1:1").osis()).toEqual("1Thess.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESSALONICENSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I LIST SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TESALONICKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUNSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKYM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOLUŇSKÝM 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNI TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("PRVNÍ TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1THESS 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I SOL 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I. TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("1 TE 1:1").osis()).toEqual("1Thess.1.1")
expect(p.parse("I TE 1:1").osis()).toEqual("1Thess.1.1")
`
true
describe "Localized book 2Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Tim (cs)", ->
`
expect(p.parse("Druha list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timetejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 list Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timotejovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteovi 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Timoteus 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druha Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhy Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhá Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("Druhý Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tim 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 Tm 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2Tim 1:1").osis()).toEqual("2Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMETEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 LIST TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEJOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEOVI 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIMOTEUS 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHA TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHY TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÁ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("DRUHÝ TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TIM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2. TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("II TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2 TM 1:1").osis()).toEqual("2Tim.1.1")
expect(p.parse("2TIM 1:1").osis()).toEqual("2Tim.1.1")
`
true
describe "Localized book 1Tim (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Tim (cs)", ->
`
expect(p.parse("Prvni list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timeteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I list Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timotejovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteovi 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Timoteus 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("Prvni Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("První Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 Tm 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1Tim 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I Tm 1:1").osis()).toEqual("1Tim.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMETEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I LIST TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEJOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEOVI 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIMOTEUS 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNI TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("PRVNÍ TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I. TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1 TM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("1TIM 1:1").osis()).toEqual("1Tim.1.1")
expect(p.parse("I TM 1:1").osis()).toEqual("1Tim.1.1")
`
true
describe "Localized book Titus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Titus (cs)", ->
`
expect(p.parse("List Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titovi 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Titus 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tit 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("Tt 1:1").osis()).toEqual("Titus.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITOVI 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TITUS 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TIT 1:1").osis()).toEqual("Titus.1.1")
expect(p.parse("TT 1:1").osis()).toEqual("Titus.1.1")
`
true
describe "Localized book Phlm (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Phlm (cs)", ->
`
expect(p.parse("List Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemonovi 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Filemon 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Phlm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Flm 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("Fm 1:1").osis()).toEqual("Phlm.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMONOVI 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FILEMON 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("PHLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FLM 1:1").osis()).toEqual("Phlm.1.1")
expect(p.parse("FM 1:1").osis()).toEqual("Phlm.1.1")
`
true
describe "Localized book Heb (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Heb (cs)", ->
`
expect(p.parse("List Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("List Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Hebrejům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zidům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židum 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Židům 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Heb 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Zd 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("Žd 1:1").osis()).toEqual("Heb.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("LIST ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEBREJŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDUM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽIDŮM 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("HEB 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ZD 1:1").osis()).toEqual("Heb.1.1")
expect(p.parse("ŽD 1:1").osis()).toEqual("Heb.1.1")
`
true
describe "Localized book Jas (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jas (cs)", ->
`
expect(p.parse("List Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("List Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubuv 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakubův 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jakub 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jak 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jas 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("Jk 1:1").osis()).toEqual("Jas.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("LIST JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBUV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUBŮV 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAKUB 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAK 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JAS 1:1").osis()).toEqual("Jas.1.1")
expect(p.parse("JK 1:1").osis()).toEqual("Jas.1.1")
`
true
describe "Localized book 2Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Pet (cs)", ->
`
expect(p.parse("Druha list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 list Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrova 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petruv 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petrův 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druha P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhy P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhá P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("Druhý P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Petr 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 Pt 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2Pet 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("DRUHA LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 LIST PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETROVA 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRUV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETRŮV 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHA P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHY P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÁ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("DRUHÝ P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PETR 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 PT 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2. P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2PET 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("II P 1:1").osis()).toEqual("2Pet.1.1")
expect(p.parse("2 P 1:1").osis()).toEqual("2Pet.1.1")
`
true
describe "Localized book 1Pet (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Pet (cs)", ->
`
expect(p.parse("Prvni list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I list Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrova 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petruv 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petrův 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("Prvni P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("První P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Petr 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1Pet 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I Pt 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
p.include_apocrypha(false)
expect(p.parse("PRVNI LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I LIST PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETROVA 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRUV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETRŮV 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNI P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("PRVNÍ P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PETR 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1PET 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I PT 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I. P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("1 P 1:1").osis()).toEqual("1Pet.1.1")
expect(p.parse("I P 1:1").osis()).toEqual("1Pet.1.1")
`
true
describe "Localized book Jude (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jude (cs)", ->
`
expect(p.parse("List Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("List Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judova 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juduv 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Judův 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Juda 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jude 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Jd 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("Ju 1:1").osis()).toEqual("Jude.1.1")
p.include_apocrypha(false)
expect(p.parse("LIST JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("LIST JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDOVA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDUV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDŮV 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDA 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JUDE 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JD 1:1").osis()).toEqual("Jude.1.1")
expect(p.parse("JU 1:1").osis()).toEqual("Jude.1.1")
`
true
describe "Localized book Tob (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Tob (cs)", ->
`
expect(p.parse("Tobijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijas 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbijáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobias 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiaš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiás 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobiáš 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tobit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tóbit 1:1").osis()).toEqual("Tob.1.1")
expect(p.parse("Tob 1:1").osis()).toEqual("Tob.1.1")
`
true
describe "Localized book Jdt (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Jdt (cs)", ->
`
expect(p.parse("Judit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júdit 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jdt 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Jud 1:1").osis()).toEqual("Jdt.1.1")
expect(p.parse("Júd 1:1").osis()).toEqual("Jdt.1.1")
`
true
describe "Localized book Bar (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Bar (cs)", ->
`
expect(p.parse("Kniha Baruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Báruchova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Barukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Kniha Bárukova 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruch 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Baruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Báruk 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bar 1:1").osis()).toEqual("Bar.1.1")
expect(p.parse("Bár 1:1").osis()).toEqual("Bar.1.1")
`
true
describe "Localized book Sus (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: Sus (cs)", ->
`
expect(p.parse("Zuzana 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Sus 1:1").osis()).toEqual("Sus.1.1")
expect(p.parse("Zuz 1:1").osis()).toEqual("Sus.1.1")
`
true
describe "Localized book 2Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 2Macc (cs)", ->
`
expect(p.parse("Druha Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejska 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Makabejská 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druha Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhy Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhá Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("Druhý Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2. Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("II Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2 Mak 1:1").osis()).toEqual("2Macc.1.1")
expect(p.parse("2Macc 1:1").osis()).toEqual("2Macc.1.1")
`
true
describe "Localized book 3Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 3Macc (cs)", ->
`
expect(p.parse("Treti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejska 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Makabejská 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Treti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Tretí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třeti Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("Třetí Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("III Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3. Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3 Mak 1:1").osis()).toEqual("3Macc.1.1")
expect(p.parse("3Macc 1:1").osis()).toEqual("3Macc.1.1")
`
true
describe "Localized book 4Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 4Macc (cs)", ->
`
expect(p.parse("Ctvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejska 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Makabejská 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Ctvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrta Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("Čtvrtá Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4. Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("IV Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4 Mak 1:1").osis()).toEqual("4Macc.1.1")
expect(p.parse("4Macc 1:1").osis()).toEqual("4Macc.1.1")
`
true
describe "Localized book 1Macc (cs)", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore",book_sequence_strategy: "ignore",osis_compaction_strategy: "bc",captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should handle book: 1Macc (cs)", ->
`
expect(p.parse("Prvni Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejska 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Makabejská 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("Prvni Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("První Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I. Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1 Mak 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("1Macc 1:1").osis()).toEqual("1Macc.1.1")
expect(p.parse("I Mak 1:1").osis()).toEqual("1Macc.1.1")
`
true
describe "Miscellaneous tests", ->
p = {}
beforeEach ->
p = new bcv_parser
p.set_options book_alone_strategy: "ignore", book_sequence_strategy: "ignore", osis_compaction_strategy: "bc", captive_end_digits_strategy: "delete"
p.include_apocrypha true
it "should return the expected language", ->
expect(p.languages).toEqual ["cs"]
it "should handle ranges (cs)", ->
expect(p.parse("Titus 1:1 - 2").osis()).toEqual "Titus.1.1-Titus.1.2"
expect(p.parse("Matt 1-2").osis()).toEqual "Matt.1-Matt.2"
expect(p.parse("Phlm 2 - 3").osis()).toEqual "Phlm.1.2-Phlm.1.3"
it "should handle chapters (cs)", ->
expect(p.parse("Titus 1:1, kapitola 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLA 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitoly 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOLY 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kapitol 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAPITOL 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap. 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP. 6").osis()).toEqual "Matt.3.4,Matt.6"
expect(p.parse("Titus 1:1, kap 2").osis()).toEqual "Titus.1.1,Titus.2"
expect(p.parse("Matt 3:4 KAP 6").osis()).toEqual "Matt.3.4,Matt.6"
it "should handle verses (cs)", ->
expect(p.parse("Exod 1:1 verše 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERŠE 6").osis()).toEqual "Phlm.1.6"
expect(p.parse("Exod 1:1 verse 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm VERSE 6").osis()).toEqual "Phlm.1.6"
it "should handle 'and' (cs)", ->
expect(p.parse("Exod 1:1 a 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 A 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv. 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV. 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
expect(p.parse("Exod 1:1 srv 3").osis()).toEqual "Exod.1.1,Exod.1.3"
expect(p.parse("Phlm 2 SRV 6").osis()).toEqual "Phlm.1.2,Phlm.1.6"
it "should handle titles (cs)", ->
expect(p.parse("Ps 3 titul, 4:2, 5:titul").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
expect(p.parse("PS 3 TITUL, 4:2, 5:TITUL").osis()).toEqual "Ps.3.1,Ps.4.2,Ps.5.1"
it "should handle 'ff' (cs)", ->
expect(p.parse("Rev 3ff, 4:2ff").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
expect(p.parse("REV 3 FF, 4:2 FF").osis()).toEqual "Rev.3-Rev.22,Rev.4.2-Rev.4.11"
it "should handle translations (cs)", ->
expect(p.parse("Lev 1 (B21)").osis_and_translations()).toEqual [["Lev.1", "B21"]]
expect(p.parse("lev 1 b21").osis_and_translations()).toEqual [["Lev.1", "B21"]]
it "should handle book ranges (cs)", ->
p.set_options {book_alone_strategy: "full", book_range_strategy: "include"}
expect(p.parse("První - Třetí J").osis()).toEqual "1John.1-3John.1"
it "should handle boundaries (cs)", ->
p.set_options {book_alone_strategy: "full"}
expect(p.parse("\u2014Matt\u2014").osis()).toEqual "Matt.1-Matt.28"
expect(p.parse("\u201cMatt 1:1\u201d").osis()).toEqual "Matt.1.1"
|
[
{
"context": "onfig.port\n\t\t\tusername\t: config.user\n\t\t\tpassword\t: config.pass\n\t\t\tprivateKey\t: config.privateKey\n\t\t\tpublicKey\t: ",
"end": 910,
"score": 0.9984483122825623,
"start": 899,
"tag": "PASSWORD",
"value": "config.pass"
}
] | src/scheme/sftp.coffee | smartmediaas/dploy | 290 | ssh2 = require "ssh2"
Signal = require "signals"
fs = require "fs"
module.exports = class SFTP
sftp : null
connection : null
connected : null
failed : null
closed : null
closing : null
constructor: ->
@connected = new Signal()
@failed = new Signal()
@closed = new Signal()
@closing = false
# Create a new instance of the FTP
@sftp = new ssh2()
@sftp.on "error", => @failed.dispatch() unless @closing
@sftp.on "close", (hadError) =>
if @hadError
@failed.dispatch() unless @closing
@sftp.on "ready", =>
@sftp.sftp (error, connection) =>
return @failed.dispatch() if error
@connection = connection
@connected.dispatch()
###
Connect to the FTP
@param config <object> Configuration file for your connection
###
connect: (config) ->
@sftp.connect
host : config.host
port : config.port
username : config.user
password : config.pass
privateKey : config.privateKey
publicKey : config.publicKey
passphrase : config.passphrase
###
Close the connection
###
close: (callback) ->
return if @closing
@closing = true
@sftp.on "end", => @closed.dispatch()
@sftp.end()
###
Dispose
###
dispose: ->
if @connected
@connected.dispose()
@connected = null
if @failed
@failed.dispose()
@failed = null
if @closed
@closed.dispose()
@closed = null
###
Retrieve a file on the server
@param path: <string> The path of your file
@param callback: <function> Callback method
###
get: (path, callback) ->
@connection.readFile path, "utf-8", callback
###
Upload a file to the server
@param local_path: <string> The local path of your file
@param remote_path: <string> The remote path where you want your file to be uploaded at
@param callback: <function> Callback method
###
upload: (local_path, remote_path, callback) ->
@connection.fastPut local_path, remote_path, callback
###
Delete a file from the server
@param remote_path: <string> The remote path you want to delete
@param callback: <function> Callback method
###
delete: (remote_path, callback) ->
# Split the path of the file
i = remote_path.lastIndexOf "/"
paths = []
while i > 0
content = remote_path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@connection.unlink remote_path, (error) =>
return callback.apply(this, [error]) if error
@_rdelete paths, callback
###
@private
Delete directories recursively
###
_rdelete: (paths, callback) ->
path = paths.shift()
@connection.opendir path, (error, handle) => # Open the directory
return callback.apply(this, [error]) if error
@connection.readdir handle, (error, list) => # Read the directory
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
if list.length <= 2 # 2 because it includes the "." and ".."
@connection.rmdir path, (error) => # Remove the directory if the directory is empty
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
@_rdelete paths, callback # Keep cleaning the rest
else
return callback.apply(this, [error])
###
Create a directory
@param path: <string> The path of the directory you want to create
@param callback: <function> Callback method
###
mkdir: (path, callback) ->
i = path.length
paths = []
while i > 0
content = path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@_rmkdir paths, callback
###
@private
Create directories recursively
###
_rmkdir: (paths, callback) ->
path = paths.pop()
@connection.opendir path, (error, handle) =>
if error
@connection.mkdir path, (error) =>
return callback.apply(this, [error]) if error or paths.length == 0
@_rmkdir paths, callback
else
return callback.apply(this, [undefined]) if paths.length == 0
@_rmkdir paths, callback | 9984 | ssh2 = require "ssh2"
Signal = require "signals"
fs = require "fs"
module.exports = class SFTP
sftp : null
connection : null
connected : null
failed : null
closed : null
closing : null
constructor: ->
@connected = new Signal()
@failed = new Signal()
@closed = new Signal()
@closing = false
# Create a new instance of the FTP
@sftp = new ssh2()
@sftp.on "error", => @failed.dispatch() unless @closing
@sftp.on "close", (hadError) =>
if @hadError
@failed.dispatch() unless @closing
@sftp.on "ready", =>
@sftp.sftp (error, connection) =>
return @failed.dispatch() if error
@connection = connection
@connected.dispatch()
###
Connect to the FTP
@param config <object> Configuration file for your connection
###
connect: (config) ->
@sftp.connect
host : config.host
port : config.port
username : config.user
password : <PASSWORD>
privateKey : config.privateKey
publicKey : config.publicKey
passphrase : config.passphrase
###
Close the connection
###
close: (callback) ->
return if @closing
@closing = true
@sftp.on "end", => @closed.dispatch()
@sftp.end()
###
Dispose
###
dispose: ->
if @connected
@connected.dispose()
@connected = null
if @failed
@failed.dispose()
@failed = null
if @closed
@closed.dispose()
@closed = null
###
Retrieve a file on the server
@param path: <string> The path of your file
@param callback: <function> Callback method
###
get: (path, callback) ->
@connection.readFile path, "utf-8", callback
###
Upload a file to the server
@param local_path: <string> The local path of your file
@param remote_path: <string> The remote path where you want your file to be uploaded at
@param callback: <function> Callback method
###
upload: (local_path, remote_path, callback) ->
@connection.fastPut local_path, remote_path, callback
###
Delete a file from the server
@param remote_path: <string> The remote path you want to delete
@param callback: <function> Callback method
###
delete: (remote_path, callback) ->
# Split the path of the file
i = remote_path.lastIndexOf "/"
paths = []
while i > 0
content = remote_path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@connection.unlink remote_path, (error) =>
return callback.apply(this, [error]) if error
@_rdelete paths, callback
###
@private
Delete directories recursively
###
_rdelete: (paths, callback) ->
path = paths.shift()
@connection.opendir path, (error, handle) => # Open the directory
return callback.apply(this, [error]) if error
@connection.readdir handle, (error, list) => # Read the directory
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
if list.length <= 2 # 2 because it includes the "." and ".."
@connection.rmdir path, (error) => # Remove the directory if the directory is empty
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
@_rdelete paths, callback # Keep cleaning the rest
else
return callback.apply(this, [error])
###
Create a directory
@param path: <string> The path of the directory you want to create
@param callback: <function> Callback method
###
mkdir: (path, callback) ->
i = path.length
paths = []
while i > 0
content = path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@_rmkdir paths, callback
###
@private
Create directories recursively
###
_rmkdir: (paths, callback) ->
path = paths.pop()
@connection.opendir path, (error, handle) =>
if error
@connection.mkdir path, (error) =>
return callback.apply(this, [error]) if error or paths.length == 0
@_rmkdir paths, callback
else
return callback.apply(this, [undefined]) if paths.length == 0
@_rmkdir paths, callback | true | ssh2 = require "ssh2"
Signal = require "signals"
fs = require "fs"
module.exports = class SFTP
sftp : null
connection : null
connected : null
failed : null
closed : null
closing : null
constructor: ->
@connected = new Signal()
@failed = new Signal()
@closed = new Signal()
@closing = false
# Create a new instance of the FTP
@sftp = new ssh2()
@sftp.on "error", => @failed.dispatch() unless @closing
@sftp.on "close", (hadError) =>
if @hadError
@failed.dispatch() unless @closing
@sftp.on "ready", =>
@sftp.sftp (error, connection) =>
return @failed.dispatch() if error
@connection = connection
@connected.dispatch()
###
Connect to the FTP
@param config <object> Configuration file for your connection
###
connect: (config) ->
@sftp.connect
host : config.host
port : config.port
username : config.user
password : PI:PASSWORD:<PASSWORD>END_PI
privateKey : config.privateKey
publicKey : config.publicKey
passphrase : config.passphrase
###
Close the connection
###
close: (callback) ->
return if @closing
@closing = true
@sftp.on "end", => @closed.dispatch()
@sftp.end()
###
Dispose
###
dispose: ->
if @connected
@connected.dispose()
@connected = null
if @failed
@failed.dispose()
@failed = null
if @closed
@closed.dispose()
@closed = null
###
Retrieve a file on the server
@param path: <string> The path of your file
@param callback: <function> Callback method
###
get: (path, callback) ->
@connection.readFile path, "utf-8", callback
###
Upload a file to the server
@param local_path: <string> The local path of your file
@param remote_path: <string> The remote path where you want your file to be uploaded at
@param callback: <function> Callback method
###
upload: (local_path, remote_path, callback) ->
@connection.fastPut local_path, remote_path, callback
###
Delete a file from the server
@param remote_path: <string> The remote path you want to delete
@param callback: <function> Callback method
###
delete: (remote_path, callback) ->
# Split the path of the file
i = remote_path.lastIndexOf "/"
paths = []
while i > 0
content = remote_path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@connection.unlink remote_path, (error) =>
return callback.apply(this, [error]) if error
@_rdelete paths, callback
###
@private
Delete directories recursively
###
_rdelete: (paths, callback) ->
path = paths.shift()
@connection.opendir path, (error, handle) => # Open the directory
return callback.apply(this, [error]) if error
@connection.readdir handle, (error, list) => # Read the directory
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
if list.length <= 2 # 2 because it includes the "." and ".."
@connection.rmdir path, (error) => # Remove the directory if the directory is empty
return callback.apply(this, [error]) if error or paths.length == 0 # If any errors reading the folder, just call the callback
@_rdelete paths, callback # Keep cleaning the rest
else
return callback.apply(this, [error])
###
Create a directory
@param path: <string> The path of the directory you want to create
@param callback: <function> Callback method
###
mkdir: (path, callback) ->
i = path.length
paths = []
while i > 0
content = path.slice 0, i
paths.push content
i = content.lastIndexOf "/"
@_rmkdir paths, callback
###
@private
Create directories recursively
###
_rmkdir: (paths, callback) ->
path = paths.pop()
@connection.opendir path, (error, handle) =>
if error
@connection.mkdir path, (error) =>
return callback.apply(this, [error]) if error or paths.length == 0
@_rmkdir paths, callback
else
return callback.apply(this, [undefined]) if paths.length == 0
@_rmkdir paths, callback |
[
{
"context": "e bus <text> - responds with image\n#\n# Author:\n# Nick Peelman <nick@peelman.us>\n\nmodule.exports = (robot) ->\n ",
"end": 159,
"score": 0.9998360872268677,
"start": 147,
"tag": "NAME",
"value": "Nick Peelman"
},
{
"context": "responds with image\n#\n# Author:\n# ... | src/underthebus.coffee | peelman/hubot-underthebus | 0 | # Description
# Sometimes you need to quickly redirect blame
#
# Commands:
# <text> under the bus <text> - responds with image
#
# Author:
# Nick Peelman <nick@peelman.us>
module.exports = (robot) ->
robot.hear /.*(under the bus).*/i, (msg) ->
msg.send('http://i.imgur.com/1tph6Wf.jpg')
| 101389 | # Description
# Sometimes you need to quickly redirect blame
#
# Commands:
# <text> under the bus <text> - responds with image
#
# Author:
# <NAME> <<EMAIL>>
module.exports = (robot) ->
robot.hear /.*(under the bus).*/i, (msg) ->
msg.send('http://i.imgur.com/1tph6Wf.jpg')
| true | # Description
# Sometimes you need to quickly redirect blame
#
# Commands:
# <text> under the bus <text> - responds with image
#
# Author:
# PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI>
module.exports = (robot) ->
robot.hear /.*(under the bus).*/i, (msg) ->
msg.send('http://i.imgur.com/1tph6Wf.jpg')
|
[
{
"context": "\n key =\n if wasTriggeredOnChange\n 'inProgressFly'\n else\n 'inProgress'\n if typeof va",
"end": 2988,
"score": 0.9663727879524231,
"start": 2975,
"tag": "KEY",
"value": "inProgressFly"
},
{
"context": "hange\n 'inProgressFly'\n ... | atom/packages/linter/lib/editor-linter.coffee | ericeslinger/dotfiles | 3 | {CompositeDisposable, Emitter, Range} = require 'atom'
Helpers = require './helpers'
class EditorLinter
constructor: (@linter, @editor) ->
@status = true
@messages = new Map
@inProgress = false
@inProgressFly = false
if @editor is atom.workspace.getActiveTextEditor()
@linter.views.updateLineMessages(true)
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add(
@editor.onDidSave => @lint(false)
)
@subscriptions.add(
@editor.onDidChangeCursorPosition ({oldBufferPosition, newBufferPosition}) =>
if newBufferPosition.row isnt oldBufferPosition.row
@linter.views.updateLineMessages(true)
@linter.views.renderBubble(newBufferPosition)
)
@subscriptions.add(
@editor.onDidStopChanging => @lint(true) if @linter.lintOnFly
)
toggleStatus: ->
@setStatus !@status
getStatus: ->
@status
setStatus: (status) ->
@status = status
if not status
@messages.clear()
@linter.views.render()
onShouldUpdate: (callback) ->
@emitter.on 'should-update', callback
onDidDestroy: (callback) ->
@emitter.on 'did-destroy', callback
lint: (wasTriggeredOnChange) ->
return unless @status
return unless @editor is atom.workspace.getActiveTextEditor()
return unless @editor.getPath()
return if @lock(wasTriggeredOnChange)
scopes = @editor.scopeDescriptorForBufferPosition(@editor.getCursorBufferPosition()).scopes
scopes.push '*' # To allow global linters
@triggerLinters(true, wasTriggeredOnChange, scopes).then( =>
return Promise.all(@triggerLinters(false, wasTriggeredOnChange, scopes))
).then =>
@lock(wasTriggeredOnChange, false)
# This method returns an array of promises to be used in lint
triggerLinters: (bufferModifying, wasTriggeredOnChange, scopes) ->
ToReturn = if bufferModifying then Promise.resolve() else []
@linter.getLinters().forEach (linter) =>
return if linter.modifiesBuffer isnt bufferModifying
return unless Helpers.shouldTriggerLinter(linter, wasTriggeredOnChange, scopes)
currentLinter = =>
return new Promise((resolve) =>
resolve(linter.lint(@editor, Helpers))
).then((results) =>
if linter.scope is 'project'
@linter.setMessages(linter, results)
else
# Trigger event instead of updating on purpose, because
# we want to make MessageRegistry the central message repo
@emitter.emit('should-update', {linter, results})
).catch (error) ->
atom.notifications.addError error.message, {detail: error.stack, dismissable: true}
if bufferModifying
ToReturn.then -> currentLinter()
else
ToReturn.push(currentLinter())
ToReturn
# This method sets or gets the lock status of given type
lock: (wasTriggeredOnChange, value) ->
key =
if wasTriggeredOnChange
'inProgressFly'
else
'inProgress'
if typeof value is 'undefined'
@[key]
else
@[key] = value
# Called on package deactivate
destroy: ->
@emitter.emit 'did-destroy'
@emitter.dispose()
@subscriptions.dispose()
module.exports = EditorLinter
| 175745 | {CompositeDisposable, Emitter, Range} = require 'atom'
Helpers = require './helpers'
class EditorLinter
constructor: (@linter, @editor) ->
@status = true
@messages = new Map
@inProgress = false
@inProgressFly = false
if @editor is atom.workspace.getActiveTextEditor()
@linter.views.updateLineMessages(true)
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add(
@editor.onDidSave => @lint(false)
)
@subscriptions.add(
@editor.onDidChangeCursorPosition ({oldBufferPosition, newBufferPosition}) =>
if newBufferPosition.row isnt oldBufferPosition.row
@linter.views.updateLineMessages(true)
@linter.views.renderBubble(newBufferPosition)
)
@subscriptions.add(
@editor.onDidStopChanging => @lint(true) if @linter.lintOnFly
)
toggleStatus: ->
@setStatus !@status
getStatus: ->
@status
setStatus: (status) ->
@status = status
if not status
@messages.clear()
@linter.views.render()
onShouldUpdate: (callback) ->
@emitter.on 'should-update', callback
onDidDestroy: (callback) ->
@emitter.on 'did-destroy', callback
lint: (wasTriggeredOnChange) ->
return unless @status
return unless @editor is atom.workspace.getActiveTextEditor()
return unless @editor.getPath()
return if @lock(wasTriggeredOnChange)
scopes = @editor.scopeDescriptorForBufferPosition(@editor.getCursorBufferPosition()).scopes
scopes.push '*' # To allow global linters
@triggerLinters(true, wasTriggeredOnChange, scopes).then( =>
return Promise.all(@triggerLinters(false, wasTriggeredOnChange, scopes))
).then =>
@lock(wasTriggeredOnChange, false)
# This method returns an array of promises to be used in lint
triggerLinters: (bufferModifying, wasTriggeredOnChange, scopes) ->
ToReturn = if bufferModifying then Promise.resolve() else []
@linter.getLinters().forEach (linter) =>
return if linter.modifiesBuffer isnt bufferModifying
return unless Helpers.shouldTriggerLinter(linter, wasTriggeredOnChange, scopes)
currentLinter = =>
return new Promise((resolve) =>
resolve(linter.lint(@editor, Helpers))
).then((results) =>
if linter.scope is 'project'
@linter.setMessages(linter, results)
else
# Trigger event instead of updating on purpose, because
# we want to make MessageRegistry the central message repo
@emitter.emit('should-update', {linter, results})
).catch (error) ->
atom.notifications.addError error.message, {detail: error.stack, dismissable: true}
if bufferModifying
ToReturn.then -> currentLinter()
else
ToReturn.push(currentLinter())
ToReturn
# This method sets or gets the lock status of given type
lock: (wasTriggeredOnChange, value) ->
key =
if wasTriggeredOnChange
'<KEY>'
else
'<KEY>'
if typeof value is 'undefined'
@[key]
else
@[key] = value
# Called on package deactivate
destroy: ->
@emitter.emit 'did-destroy'
@emitter.dispose()
@subscriptions.dispose()
module.exports = EditorLinter
| true | {CompositeDisposable, Emitter, Range} = require 'atom'
Helpers = require './helpers'
class EditorLinter
constructor: (@linter, @editor) ->
@status = true
@messages = new Map
@inProgress = false
@inProgressFly = false
if @editor is atom.workspace.getActiveTextEditor()
@linter.views.updateLineMessages(true)
@emitter = new Emitter
@subscriptions = new CompositeDisposable
@subscriptions.add(
@editor.onDidSave => @lint(false)
)
@subscriptions.add(
@editor.onDidChangeCursorPosition ({oldBufferPosition, newBufferPosition}) =>
if newBufferPosition.row isnt oldBufferPosition.row
@linter.views.updateLineMessages(true)
@linter.views.renderBubble(newBufferPosition)
)
@subscriptions.add(
@editor.onDidStopChanging => @lint(true) if @linter.lintOnFly
)
toggleStatus: ->
@setStatus !@status
getStatus: ->
@status
setStatus: (status) ->
@status = status
if not status
@messages.clear()
@linter.views.render()
onShouldUpdate: (callback) ->
@emitter.on 'should-update', callback
onDidDestroy: (callback) ->
@emitter.on 'did-destroy', callback
lint: (wasTriggeredOnChange) ->
return unless @status
return unless @editor is atom.workspace.getActiveTextEditor()
return unless @editor.getPath()
return if @lock(wasTriggeredOnChange)
scopes = @editor.scopeDescriptorForBufferPosition(@editor.getCursorBufferPosition()).scopes
scopes.push '*' # To allow global linters
@triggerLinters(true, wasTriggeredOnChange, scopes).then( =>
return Promise.all(@triggerLinters(false, wasTriggeredOnChange, scopes))
).then =>
@lock(wasTriggeredOnChange, false)
# This method returns an array of promises to be used in lint
triggerLinters: (bufferModifying, wasTriggeredOnChange, scopes) ->
ToReturn = if bufferModifying then Promise.resolve() else []
@linter.getLinters().forEach (linter) =>
return if linter.modifiesBuffer isnt bufferModifying
return unless Helpers.shouldTriggerLinter(linter, wasTriggeredOnChange, scopes)
currentLinter = =>
return new Promise((resolve) =>
resolve(linter.lint(@editor, Helpers))
).then((results) =>
if linter.scope is 'project'
@linter.setMessages(linter, results)
else
# Trigger event instead of updating on purpose, because
# we want to make MessageRegistry the central message repo
@emitter.emit('should-update', {linter, results})
).catch (error) ->
atom.notifications.addError error.message, {detail: error.stack, dismissable: true}
if bufferModifying
ToReturn.then -> currentLinter()
else
ToReturn.push(currentLinter())
ToReturn
# This method sets or gets the lock status of given type
lock: (wasTriggeredOnChange, value) ->
key =
if wasTriggeredOnChange
'PI:KEY:<KEY>END_PI'
else
'PI:KEY:<KEY>END_PI'
if typeof value is 'undefined'
@[key]
else
@[key] = value
# Called on package deactivate
destroy: ->
@emitter.emit 'did-destroy'
@emitter.dispose()
@subscriptions.dispose()
module.exports = EditorLinter
|
[
{
"context": "ld not cause a syntax error.\n=>\n\n\nobj: {\n name: \"Fred\"\n\n bound: =>\n (==> print(this.name is \"Fred\")",
"end": 191,
"score": 0.9998264312744141,
"start": 187,
"tag": "NAME",
"value": "Fred"
},
{
"context": " \"Fred\"\n\n bound: =>\n (==> print(this.na... | test/fixtures/execution/test_functions.coffee | tlrobinson/coffee-script | 1 | x: 1
y: {}
y.x: => 3
print(x is 1)
print(typeof(y.x) is 'function')
print(y.x() is 3)
print(y.x.name is 'x')
# The empty function should not cause a syntax error.
=>
obj: {
name: "Fred"
bound: =>
(==> print(this.name is "Fred"))()
unbound: =>
(=> print(!this.name?))()
}
obj.unbound()
obj.bound()
# The named function should be cleared out before a call occurs:
# Python decorator style wrapper that memoizes any function
memoize: fn =>
cache: {}
self: this
args... =>
key: args.toString()
return cache[key] if cache[key]
cache[key] = fn.apply(self, args)
Math: {
Add: a, b => a + b
AnonymousAdd: (a, b => a + b)
FastAdd: memoize() a, b => a + b
}
print(Math.Add(5, 5) is 10)
print(Math.AnonymousAdd(10, 10) is 20)
print(Math.FastAdd(20, 20) is 40)
| 3079 | x: 1
y: {}
y.x: => 3
print(x is 1)
print(typeof(y.x) is 'function')
print(y.x() is 3)
print(y.x.name is 'x')
# The empty function should not cause a syntax error.
=>
obj: {
name: "<NAME>"
bound: =>
(==> print(this.name is "<NAME>"))()
unbound: =>
(=> print(!this.name?))()
}
obj.unbound()
obj.bound()
# The named function should be cleared out before a call occurs:
# Python decorator style wrapper that memoizes any function
memoize: fn =>
cache: {}
self: this
args... =>
key: args.toString()
return cache[key] if cache[key]
cache[key] = fn.apply(self, args)
Math: {
Add: a, b => a + b
AnonymousAdd: (a, b => a + b)
FastAdd: memoize() a, b => a + b
}
print(Math.Add(5, 5) is 10)
print(Math.AnonymousAdd(10, 10) is 20)
print(Math.FastAdd(20, 20) is 40)
| true | x: 1
y: {}
y.x: => 3
print(x is 1)
print(typeof(y.x) is 'function')
print(y.x() is 3)
print(y.x.name is 'x')
# The empty function should not cause a syntax error.
=>
obj: {
name: "PI:NAME:<NAME>END_PI"
bound: =>
(==> print(this.name is "PI:NAME:<NAME>END_PI"))()
unbound: =>
(=> print(!this.name?))()
}
obj.unbound()
obj.bound()
# The named function should be cleared out before a call occurs:
# Python decorator style wrapper that memoizes any function
memoize: fn =>
cache: {}
self: this
args... =>
key: args.toString()
return cache[key] if cache[key]
cache[key] = fn.apply(self, args)
Math: {
Add: a, b => a + b
AnonymousAdd: (a, b => a + b)
FastAdd: memoize() a, b => a + b
}
print(Math.Add(5, 5) is 10)
print(Math.AnonymousAdd(10, 10) is 20)
print(Math.FastAdd(20, 20) is 40)
|
[
{
"context": "ema = new Schema DBENGINE, database: '', username: DBUSER, password: DBPASS\nschema.log = (q) -> console.log",
"end": 320,
"score": 0.8037506937980652,
"start": 314,
"tag": "USERNAME",
"value": "DBUSER"
},
{
"context": "BENGINE, database: '', username: DBUSER, password:... | node_modules/resources/persistence/vendor/jugglingdb/test/migration_test.coffee | manecz/storytail | 0 | juggling = require('../index')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = process.env.DBNAME || 'myapp_test'
DBUSER = process.env.DBUSER || 'root'
DBPASS = ''
DBENGINE = process.env.DBENGINE || 'mysql'
require('./spec_helper').init module.exports
schema = new Schema DBENGINE, database: '', username: DBUSER, password: DBPASS
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
password: String
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
cb err
else
indexes = {}
res.forEach (index) -> indexes[index.Key_name] = index if index.Seq_in_index == 1
cb err, indexes
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: ''
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: 'password'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == 'test@example.com')
User.create email: 'test@example.com', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE' # default
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
console.log ixs.email
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
| 131400 | juggling = require('../index')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = process.env.DBNAME || 'myapp_test'
DBUSER = process.env.DBUSER || 'root'
DBPASS = ''
DBENGINE = process.env.DBENGINE || 'mysql'
require('./spec_helper').init module.exports
schema = new Schema DBENGINE, database: '', username: DBUSER, password: <PASSWORD>
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
password: <PASSWORD>
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
cb err
else
indexes = {}
res.forEach (index) -> indexes[index.Key_name] = index if index.Seq_in_index == 1
cb err, indexes
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: ''
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: '<PASSWORD>'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == '<EMAIL>')
User.create email: '<EMAIL>', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE' # default
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
console.log ixs.email
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
| true | juggling = require('../index')
Schema = juggling.Schema
Text = Schema.Text
DBNAME = process.env.DBNAME || 'myapp_test'
DBUSER = process.env.DBUSER || 'root'
DBPASS = ''
DBENGINE = process.env.DBENGINE || 'mysql'
require('./spec_helper').init module.exports
schema = new Schema DBENGINE, database: '', username: DBUSER, password: PI:PASSWORD:<PASSWORD>END_PI
schema.log = (q) -> console.log q
query = (sql, cb) ->
schema.adapter.query sql, cb
User = schema.define 'User',
email: { type: String, null: false, index: true }
name: String
bio: Text
password: PI:PASSWORD:<PASSWORD>END_PI
birthDate: Date
pendingPeriod: Number
createdByAdmin: Boolean
, indexes:
index1:
columns: 'email, createdByAdmin'
withBlankDatabase = (cb) ->
db = schema.settings.database = DBNAME
query 'DROP DATABASE IF EXISTS ' + db, (err) ->
query 'CREATE DATABASE ' + db, (err) ->
query 'USE '+ db, cb
getFields = (model, cb) ->
query 'SHOW FIELDS FROM ' + model, (err, res) ->
if err
cb err
else
fields = {}
res.forEach (field) -> fields[field.Field] = field
cb err, fields
getIndexes = (model, cb) ->
query 'SHOW INDEXES FROM ' + model, (err, res) ->
if err
cb err
else
indexes = {}
res.forEach (index) -> indexes[index.Key_name] = index if index.Seq_in_index == 1
cb err, indexes
it 'should run migration', (test) ->
withBlankDatabase (err) ->
schema.automigrate ->
getFields 'User', (err, fields) ->
test.deepEqual fields,
id:
Field: 'id'
Type: 'int(11)'
Null: 'NO'
Key: 'PRI'
Default: null
Extra: 'auto_increment'
email:
Field: 'email'
Type: 'varchar(255)'
Null: 'NO'
Key: ''
Default: null
Extra: ''
name:
Field: 'name'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
bio:
Field: 'bio'
Type: 'text'
Null: 'YES'
Key: ''
Default: null
Extra: ''
password:
Field: 'PI:PASSWORD:<PASSWORD>END_PI'
Type: 'varchar(255)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
birthDate:
Field: 'birthDate'
Type: 'datetime'
Null: 'YES'
Key: ''
Default: null
Extra: ''
pendingPeriod:
Field: 'pendingPeriod'
Type: 'int(11)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
createdByAdmin:
Field: 'createdByAdmin'
Type: 'tinyint(1)'
Null: 'YES'
Key: ''
Default: null
Extra: ''
test.done()
it 'should autoupgrade', (test) ->
userExists = (cb) ->
query 'SELECT * FROM User', (err, res) ->
cb(not err and res[0].email == 'PI:EMAIL:<EMAIL>END_PI')
User.create email: 'PI:EMAIL:<EMAIL>END_PI', (err, user) ->
test.ok not err
userExists (yep) ->
test.ok yep
User.defineProperty 'email', type: String
User.defineProperty 'name', type: String, limit: 50
User.defineProperty 'newProperty', type: Number
User.defineProperty 'pendingPeriod', false
schema.autoupdate (err) ->
getFields 'User', (err, fields) ->
# change nullable for email
test.equal fields.email.Null, 'YES', 'Email is not null'
# change type of name
test.equal fields.name.Type, 'varchar(50)', 'Name is not varchar(50)'
# add new column
test.ok fields.newProperty, 'New column was not added'
if fields.newProperty
test.equal fields.newProperty.Type, 'int(11)', 'New column type is not int(11)'
# drop column
test.ok not fields.pendingPeriod, 'drop column'
# user still exists
userExists (yep) ->
test.ok yep
test.done()
it 'should check actuality of schema', (test) ->
# drop column
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.defineProperty 'email', false
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
test.done()
it 'should add single-column index', (test) ->
User.defineProperty 'email', type: String, index: { kind: 'FULLTEXT', type: 'HASH'}
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok ixs.email && ixs.email.Column_name == 'email'
console.log(ixs)
test.equal ixs.email.Index_type, 'BTREE' # default
test.done()
it 'should change type of single-column index', (test) ->
User.defineProperty 'email', type: String, index: { type: 'BTREE' }
User.schema.isActual (err, ok) ->
test.ok ok, 'schema is actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
console.log ixs.email
test.ok ixs.email && ixs.email.Column_name == 'email'
test.equal ixs.email.Index_type, 'BTREE'
test.done()
it 'should remove single-column index', (test) ->
User.defineProperty 'email', type: String, index: false
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.ok !ixs.email
test.done()
it 'should update multi-column index when order of columns changed', (test) ->
User.schema.adapter._models.User.settings.indexes.index1.columns = 'createdByAdmin, email'
User.schema.isActual (err, ok) ->
test.ok not ok, 'schema is not actual'
User.schema.autoupdate (err) ->
return console.log(err) if err
getIndexes 'User', (err, ixs) ->
test.equals ixs.index1.Column_name, 'createdByAdmin'
test.done()
it 'test', (test) ->
User.defineProperty 'email', type: String, index: true
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
User.schema.autoupdate (err) ->
test.done()
it 'should disconnect when done', (test) ->
schema.disconnect()
test.done()
|
[
{
"context": "low weebs?\n ) and (\n msg.author?.id is \"456207047482933251\"\n # sadbot#3862\n ) and",
"end": 221,
"score": 0.893251359462738,
"start": 220,
"tag": "USERNAME",
"value": "4"
},
{
"context": "ow weebs?\n ) and (\n msg.author?.id is \"45620... | src/specials/who-up.coffee | MindfulMinun/discord-haruka | 2 | #! ========================================
#! who up
handler = (msg, Haruka) ->
tests = (
msg.guild?.id is "443094449233592325"
# how do you do, fellow weebs?
) and (
msg.author?.id is "456207047482933251"
# sadbot#3862
) and (
msg.content.startsWith 'who up'
# "who up" and that dumb awoo meme
)
if not tests then return no
msg.channel.send [
'awoo'
'awoooo!'
'*achoo*'
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "who up"
handler: handler
}
| 125840 | #! ========================================
#! who up
handler = (msg, Haruka) ->
tests = (
msg.guild?.id is "443094449233592325"
# how do you do, fellow weebs?
) and (
msg.author?.id is "4<PASSWORD>"
# sadbot#3862
) and (
msg.content.startsWith 'who up'
# "who up" and that dumb awoo meme
)
if not tests then return no
msg.channel.send [
'awoo'
'awoooo!'
'*achoo*'
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "who up"
handler: handler
}
| true | #! ========================================
#! who up
handler = (msg, Haruka) ->
tests = (
msg.guild?.id is "443094449233592325"
# how do you do, fellow weebs?
) and (
msg.author?.id is "4PI:PASSWORD:<PASSWORD>END_PI"
# sadbot#3862
) and (
msg.content.startsWith 'who up'
# "who up" and that dumb awoo meme
)
if not tests then return no
msg.channel.send [
'awoo'
'awoooo!'
'*achoo*'
].choose()
# Message doesn't call Haruka, exit prematurely
yes
module.exports = {
name: "who up"
handler: handler
}
|
[
{
"context": " exec = Npm.require('child_process').exec\n\n pwd = process.env.PWD\n mongo_path = Meteor.settings.private?.mongo_pat",
"end": 127,
"score": 0.8762305378913879,
"start": 112,
"tag": "PASSWORD",
"value": "process.env.PWD"
},
{
"context": "go_host = Meteor.settings.priv... | packages/_tests/fixtures.coffee | ecohealthalliance/eidr-connect | 1 | if Meteor.isAppTest
#import { exec } from 'child_process'
exec = Npm.require('child_process').exec
pwd = process.env.PWD
mongo_path = Meteor.settings.private?.mongo_path || "#{pwd}/node_modules/mongodb-prebuilt/binjs"
mongo_host = Meteor.settings.private?.mongo_host || '127.0.0.1'
mongo_port = Meteor.settings.private?.mongo_port || '27017'
test_db = Meteor.settings.private?.test_db || 'eidr-connect-test'
syncExec = Meteor.wrapAsync(exec)
locations1 = [
id: '5165418'
name: 'Ohio'
admin1Name: 'Ohio'
admin2Name: null
latitude: 40.25034
longitude: -83.00018
countryName: 'United States'
countryCode: 'US'
population: 11467123
featureClass: 'A'
featureCode: 'ADM1'
alternateNames: [
'\'Ohaio'
'Buckeye State'
]
]
locations2 = [
id: '2419472'
name: 'Kissidougou'
admin1Name: 'Faranah Region'
admin2Name: 'Kissidougou'
latitude: 9.1848
longitude: -10.09987
countryName: 'Republic of Guinea'
countryCode: 'GN'
population: 47099
featureClass: 'P'
featureCode: 'PPLA2'
alternateNames: [
'KSI'
]
]
testEvent =
eventName: 'Test Event 1'
summary: 'Test summary'
testSource =
title: 'Test Article',
url: 'http://promedmail.org/post/418162'
publishDate: new Date()
publishDateTZ: 'EST'
testSource2 =
title: 'Test Article 2',
url: 'http://promedmail.org/post/5220233'
publishDate: new Date()
publishDateTZ: 'EST'
testIncident =
species:
id: "tsn:180092"
text: "Homo sapiens"
cases: 375
locations: locations1
dateRange:
cumulative: false
type: 'day'
Meteor.methods
###
# load the database from a dump file
#
# @note this may periodically fail using mongodb-prebuilt JavaScript bridge,
# using the operating system package manager for the mongorestore binary
# has been the most stable option.
# e.g. `apt-get install mongodb` or `brew install mongodb`
# then setttings-dev.json under private
# mongo_path: '/usr/local/bin'
# @see http://stackoverflow.com/questions/39719882/mongorestore-random-crash-fatal-error
# @see https://github.com/golang/go/issues/17492
# @see https://github.com/golang/go/issues/17490
###
load: ->
try
# Loading test data into database
Meteor.call 'createTestingAdmin'
console.log "created admin"
{ insertedId } = Meteor.call('upsertUserEvent', testEvent)
eventId = insertedId
console.log 'UserEvent created', eventId
testSource.userEventIds = [eventId]
articleId = Meteor.call('addEventSource', testSource, eventId)
console.log 'Article created', articleId
testIncident.dateRange.start = new Date()
testIncident.dateRange.end = new Date()
testIncident.articleId = articleId
incidentId = Meteor.call('addIncidentReport', testIncident)
console.log 'Incident created', incidentId
Meteor.call 'addIncidentToEvent', eventId, incidentId
catch error
console.log "error loading data", error
Meteor.call('reset')
###
# reset - removes all data from the database
###
reset: ->
allUsers = Meteor.users.find({}).fetch()
for user in allUsers
Roles.removeUsersFromRoles(user._id, 'admin')
Package['xolvio:cleaner'].resetDatabase()
###
# createTestingAdmin - will create an admin account for testing
###
createTestingAdmin: ->
email = 'chimp@testing1234.com'
try
newId = Accounts.createUser({
email: email
password: 'Pa55w0rd!'
profile:
name: 'Chimp'
})
@setUserId newId
Roles.addUsersToRoles(newId, ['admin'])
catch error
# this user shouldn't belong in the production database
console.warn("TestingAdmin user '#{email}' exists")
addIncidents: (eventId, incidentCount) ->
articleId = Meteor.call('addEventSource', testSource2, eventId)
for num in [1...incidentCount + 1]
incident = Object.assign({}, testIncident)
date = new Date()
if num > 1
date.setDate(date.getDate() - 14 * num)
incident.cases = num * 100
else
delete incident.cases
incident.deaths = 200
incident.travelRelated = true
incident.locations = locations2
if num > 2
incident.status = 'confirmed'
incident.dateRange.start = date
incident.dateRange.end = date
incident.articleId = articleId
console.log incident
incidentId = Meteor.call('addIncidentReport', incident)
console.log incidentId
Meteor.call('addIncidentToEvent', eventId, incidentId)
| 222602 | if Meteor.isAppTest
#import { exec } from 'child_process'
exec = Npm.require('child_process').exec
pwd = <PASSWORD>
mongo_path = Meteor.settings.private?.mongo_path || "#{pwd}/node_modules/mongodb-prebuilt/binjs"
mongo_host = Meteor.settings.private?.mongo_host || '127.0.0.1'
mongo_port = Meteor.settings.private?.mongo_port || '27017'
test_db = Meteor.settings.private?.test_db || 'eidr-connect-test'
syncExec = Meteor.wrapAsync(exec)
locations1 = [
id: '5165418'
name: '<NAME>'
admin1Name: '<NAME>'
admin2Name: null
latitude: 40.25034
longitude: -83.00018
countryName: 'United States'
countryCode: 'US'
population: 11467123
featureClass: 'A'
featureCode: 'ADM1'
alternateNames: [
'\'O<NAME>io'
'Buckeye State'
]
]
locations2 = [
id: '2419472'
name: '<NAME>'
admin1Name: '<NAME>'
admin2Name: '<NAME>'
latitude: 9.1848
longitude: -10.09987
countryName: 'Republic of Guinea'
countryCode: 'GN'
population: 47099
featureClass: 'P'
featureCode: 'PPLA2'
alternateNames: [
'KSI'
]
]
testEvent =
eventName: 'Test Event 1'
summary: 'Test summary'
testSource =
title: 'Test Article',
url: 'http://promedmail.org/post/418162'
publishDate: new Date()
publishDateTZ: 'EST'
testSource2 =
title: 'Test Article 2',
url: 'http://promedmail.org/post/5220233'
publishDate: new Date()
publishDateTZ: 'EST'
testIncident =
species:
id: "tsn:180092"
text: "Homo sapiens"
cases: 375
locations: locations1
dateRange:
cumulative: false
type: 'day'
Meteor.methods
###
# load the database from a dump file
#
# @note this may periodically fail using mongodb-prebuilt JavaScript bridge,
# using the operating system package manager for the mongorestore binary
# has been the most stable option.
# e.g. `apt-get install mongodb` or `brew install mongodb`
# then setttings-dev.json under private
# mongo_path: '/usr/local/bin'
# @see http://stackoverflow.com/questions/39719882/mongorestore-random-crash-fatal-error
# @see https://github.com/golang/go/issues/17492
# @see https://github.com/golang/go/issues/17490
###
load: ->
try
# Loading test data into database
Meteor.call 'createTestingAdmin'
console.log "created admin"
{ insertedId } = Meteor.call('upsertUserEvent', testEvent)
eventId = insertedId
console.log 'UserEvent created', eventId
testSource.userEventIds = [eventId]
articleId = Meteor.call('addEventSource', testSource, eventId)
console.log 'Article created', articleId
testIncident.dateRange.start = new Date()
testIncident.dateRange.end = new Date()
testIncident.articleId = articleId
incidentId = Meteor.call('addIncidentReport', testIncident)
console.log 'Incident created', incidentId
Meteor.call 'addIncidentToEvent', eventId, incidentId
catch error
console.log "error loading data", error
Meteor.call('reset')
###
# reset - removes all data from the database
###
reset: ->
allUsers = Meteor.users.find({}).fetch()
for user in allUsers
Roles.removeUsersFromRoles(user._id, 'admin')
Package['xolvio:cleaner'].resetDatabase()
###
# createTestingAdmin - will create an admin account for testing
###
createTestingAdmin: ->
email = '<EMAIL>'
try
newId = Accounts.createUser({
email: email
password: '<PASSWORD>!'
profile:
name: 'Chimp'
})
@setUserId newId
Roles.addUsersToRoles(newId, ['admin'])
catch error
# this user shouldn't belong in the production database
console.warn("TestingAdmin user '#{email}' exists")
addIncidents: (eventId, incidentCount) ->
articleId = Meteor.call('addEventSource', testSource2, eventId)
for num in [1...incidentCount + 1]
incident = Object.assign({}, testIncident)
date = new Date()
if num > 1
date.setDate(date.getDate() - 14 * num)
incident.cases = num * 100
else
delete incident.cases
incident.deaths = 200
incident.travelRelated = true
incident.locations = locations2
if num > 2
incident.status = 'confirmed'
incident.dateRange.start = date
incident.dateRange.end = date
incident.articleId = articleId
console.log incident
incidentId = Meteor.call('addIncidentReport', incident)
console.log incidentId
Meteor.call('addIncidentToEvent', eventId, incidentId)
| true | if Meteor.isAppTest
#import { exec } from 'child_process'
exec = Npm.require('child_process').exec
pwd = PI:PASSWORD:<PASSWORD>END_PI
mongo_path = Meteor.settings.private?.mongo_path || "#{pwd}/node_modules/mongodb-prebuilt/binjs"
mongo_host = Meteor.settings.private?.mongo_host || '127.0.0.1'
mongo_port = Meteor.settings.private?.mongo_port || '27017'
test_db = Meteor.settings.private?.test_db || 'eidr-connect-test'
syncExec = Meteor.wrapAsync(exec)
locations1 = [
id: '5165418'
name: 'PI:NAME:<NAME>END_PI'
admin1Name: 'PI:NAME:<NAME>END_PI'
admin2Name: null
latitude: 40.25034
longitude: -83.00018
countryName: 'United States'
countryCode: 'US'
population: 11467123
featureClass: 'A'
featureCode: 'ADM1'
alternateNames: [
'\'OPI:NAME:<NAME>END_PIio'
'Buckeye State'
]
]
locations2 = [
id: '2419472'
name: 'PI:NAME:<NAME>END_PI'
admin1Name: 'PI:NAME:<NAME>END_PI'
admin2Name: 'PI:NAME:<NAME>END_PI'
latitude: 9.1848
longitude: -10.09987
countryName: 'Republic of Guinea'
countryCode: 'GN'
population: 47099
featureClass: 'P'
featureCode: 'PPLA2'
alternateNames: [
'KSI'
]
]
testEvent =
eventName: 'Test Event 1'
summary: 'Test summary'
testSource =
title: 'Test Article',
url: 'http://promedmail.org/post/418162'
publishDate: new Date()
publishDateTZ: 'EST'
testSource2 =
title: 'Test Article 2',
url: 'http://promedmail.org/post/5220233'
publishDate: new Date()
publishDateTZ: 'EST'
testIncident =
species:
id: "tsn:180092"
text: "Homo sapiens"
cases: 375
locations: locations1
dateRange:
cumulative: false
type: 'day'
Meteor.methods
###
# load the database from a dump file
#
# @note this may periodically fail using mongodb-prebuilt JavaScript bridge,
# using the operating system package manager for the mongorestore binary
# has been the most stable option.
# e.g. `apt-get install mongodb` or `brew install mongodb`
# then setttings-dev.json under private
# mongo_path: '/usr/local/bin'
# @see http://stackoverflow.com/questions/39719882/mongorestore-random-crash-fatal-error
# @see https://github.com/golang/go/issues/17492
# @see https://github.com/golang/go/issues/17490
###
load: ->
try
# Loading test data into database
Meteor.call 'createTestingAdmin'
console.log "created admin"
{ insertedId } = Meteor.call('upsertUserEvent', testEvent)
eventId = insertedId
console.log 'UserEvent created', eventId
testSource.userEventIds = [eventId]
articleId = Meteor.call('addEventSource', testSource, eventId)
console.log 'Article created', articleId
testIncident.dateRange.start = new Date()
testIncident.dateRange.end = new Date()
testIncident.articleId = articleId
incidentId = Meteor.call('addIncidentReport', testIncident)
console.log 'Incident created', incidentId
Meteor.call 'addIncidentToEvent', eventId, incidentId
catch error
console.log "error loading data", error
Meteor.call('reset')
###
# reset - removes all data from the database
###
reset: ->
allUsers = Meteor.users.find({}).fetch()
for user in allUsers
Roles.removeUsersFromRoles(user._id, 'admin')
Package['xolvio:cleaner'].resetDatabase()
###
# createTestingAdmin - will create an admin account for testing
###
createTestingAdmin: ->
email = 'PI:EMAIL:<EMAIL>END_PI'
try
newId = Accounts.createUser({
email: email
password: 'PI:PASSWORD:<PASSWORD>END_PI!'
profile:
name: 'Chimp'
})
@setUserId newId
Roles.addUsersToRoles(newId, ['admin'])
catch error
# this user shouldn't belong in the production database
console.warn("TestingAdmin user '#{email}' exists")
addIncidents: (eventId, incidentCount) ->
articleId = Meteor.call('addEventSource', testSource2, eventId)
for num in [1...incidentCount + 1]
incident = Object.assign({}, testIncident)
date = new Date()
if num > 1
date.setDate(date.getDate() - 14 * num)
incident.cases = num * 100
else
delete incident.cases
incident.deaths = 200
incident.travelRelated = true
incident.locations = locations2
if num > 2
incident.status = 'confirmed'
incident.dateRange.start = date
incident.dateRange.end = date
incident.articleId = articleId
console.log incident
incidentId = Meteor.call('addIncidentReport', incident)
console.log incidentId
Meteor.call('addIncidentToEvent', eventId, incidentId)
|
[
{
"context": "seio.com').child('riders');\n#ref.push({\n# nick: 'Jake',\n# capacity: 0\n#})\n#\n#ref.on('child_added', fun",
"end": 423,
"score": 0.9967777729034424,
"start": 419,
"tag": "NAME",
"value": "Jake"
}
] | client/js/lib/app.coffee | jaketrent/takemycar | 0 | App = Ember.Application.create()
App.Store = FP.Store.extend
firebaseRoot: window.env.firebaseRoot
App.Router.map ->
@route 'welcome', { path: '/' }
@route 'match', { path: '/match' }
@route 'drive', { path: '/drive' }
Ember.TEMPLATES = {}
Ember.TextField.reopen
attributeBindings: ['autofocus']
#ref = new Firebase('https://incandescent-fire-231.firebaseio.com').child('riders');
#ref.push({
# nick: 'Jake',
# capacity: 0
#})
#
#ref.on('child_added', function (snapshot) {
# var msg = snapshot.val()
# console.log('added ' + msg.name + ' (driver: ' + msg.driver + ')')
#}) | 175885 | App = Ember.Application.create()
App.Store = FP.Store.extend
firebaseRoot: window.env.firebaseRoot
App.Router.map ->
@route 'welcome', { path: '/' }
@route 'match', { path: '/match' }
@route 'drive', { path: '/drive' }
Ember.TEMPLATES = {}
Ember.TextField.reopen
attributeBindings: ['autofocus']
#ref = new Firebase('https://incandescent-fire-231.firebaseio.com').child('riders');
#ref.push({
# nick: '<NAME>',
# capacity: 0
#})
#
#ref.on('child_added', function (snapshot) {
# var msg = snapshot.val()
# console.log('added ' + msg.name + ' (driver: ' + msg.driver + ')')
#}) | true | App = Ember.Application.create()
App.Store = FP.Store.extend
firebaseRoot: window.env.firebaseRoot
App.Router.map ->
@route 'welcome', { path: '/' }
@route 'match', { path: '/match' }
@route 'drive', { path: '/drive' }
Ember.TEMPLATES = {}
Ember.TextField.reopen
attributeBindings: ['autofocus']
#ref = new Firebase('https://incandescent-fire-231.firebaseio.com').child('riders');
#ref.push({
# nick: 'PI:NAME:<NAME>END_PI',
# capacity: 0
#})
#
#ref.on('child_added', function (snapshot) {
# var msg = snapshot.val()
# console.log('added ' + msg.name + ' (driver: ' + msg.driver + ')')
#}) |
[
{
"context": "med.load._async = true\nP.src.pubmed.load._auth = 'root'\n\n\nP.src.pubmed.changes = () ->\n return @src.pub",
"end": 11022,
"score": 0.9324471354484558,
"start": 11018,
"tag": "USERNAME",
"value": "root"
},
{
"context": "anges._async = true\nP.src.pubmed.changes._auth... | server/src/src/pubmed.coffee | oaworks/paradigm | 1 |
# https://www.nlm.nih.gov/databases/download/pubmed_medline.html
# https://www.nlm.nih.gov/bsd/licensee/2021_stats/2021_LO.html
# in case the medline data does not include all PMCs or PMIDs, there is a converter API
# and/or PMC sources that could be used to map things (with just over 6 million PMC IDs in the pubmed
# data, looks like probably all PMC articles were in the data dump anyway)
# https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/
# https://www.ncbi.nlm.nih.gov/pmc/tools/ftp/
# annual files published each December, listed at: https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/
# lists files such as https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed21n0001.xml.gz
# up to 1062 for 2020. Contains other files including .md5 files for each gz file
# Managed to load 31847922
# PMID 30036026 failed with a “published” value of 1-01-01
# daily update files listed at https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/
# such as https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/pubmed21n1063.xml.gz
# can contain one or more files for each day since the last annual file dump
P.src.pubmed.load = (changes) ->
# there are 30k or less records per pubmed file so tried batching by file, but streaming more than one file at a time caused OOM
# so reduce batch size if necessary. default node heap size is 1400M I think, so increased to 3072M and try again
# check if increasing heap that machine running it has enough - AND note that on production if using PM2 to run as cluster, then
# need enough memory for each process to max out. Running 3 with 15k batch size was stable but reaching almost 3000M at times and
# didn't seem much faster, so now set to do whole files as batches with two streamers at a time, see how that goes
batchsize = -1 # how many records to batch upload at a time
streamers = 1 # how many files to stream at a time
howmany = @params.howmany ? -1 # max number of lines to process. set to -1 to keep going...
await @src.pubmed('') if @refresh and not changes
addr = if changes then 'https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/' else 'https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/'
files = []
listing = await @fetch addr
for a in listing.split 'href="'
f = a.split('"')[0]
if f.startsWith('pubmed') and f.endsWith('.gz') and ((@refresh and not changes) or not exists = await @src.pubmed.count 'srcfile:"' + addr + f + '"')
files.push addr + f
running = 0
total = 0
_loop = (fn) =>
console.log 'Pubmed loading' + (if changes then ' changes' else ''), fn, files.length, running
# stream them, unzip, and parse line by line, processing each record once a full record has been parsed out
# the first 2020 gz file for example is 19M, uncompressed it is 182M. 30k records or so per file
batch = []
rec = {}
published = false
ininv = false
for await line from readline.createInterface input: (await fetch fn).body.pipe zlib.createGunzip()
if batchsize > 0 and batch.length >= batchsize
await @src.pubmed batch
batch = []
console.log fn, total
line = line.trim().replace('&', '&')
if line is '</PubmedArticle>' # <PubmedArticle>...</PubmedArticle> is a total article record
total += 1
if published isnt false and published.year
rec.year = parseInt published.year
if published.month and published.month.length > 2
published.month = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'].indexOf published.month.toLowerCase().substr(0, 3)
published.month = published.month.toString() if typeof published.month is 'number'
published.month = '0' + published.month if published.month and published.month.length is 1
published.day = published.day.toString() if typeof published.day is 'number'
published.day = '0' + published.day if published.day and published.day.length is 1
rec.published = published.year + '-' + (published.month ? '01') + '-' + (published.day ? '01')
rec.publishedAt = await @epoch rec.published
rec.srcfile = fn
rec._id = rec.PMID
batch.push rec
rec = {}
published = false
ininv = false
break if total is howmany
else
km =
'<ArticleTitle>': 'title'
'<AbstractText>': 'abstract'
'<ISOAbbreviation>': 'iso'
'<Issue>': 'issue'
'<Title>': 'journal'
'<Language>': 'language'
'<NlmUniqueID>': 'NLMID'
'<PMID>': 'PMID'
'<Volume>': 'volume'
'<CopyrightInformation>': 'copyright'
'<NumberOfReferences>': 'references_count'
'<PublicationStatus>': 'status'
'<SpaceFlightMission>': 'spaceflightmission'
for k of km
rec[km[k]] ?= line.split('>')[1].split('</')[0] if line.includes(k) or line.includes k.replace '>', ' '
if line.includes '<MedlinePgn>'
# do this because something like 1345-56 makes ES attempt to interpret a date, then others that don't look like a date will fail
rec.pages = line.split('>')[1].split('</')[0].replace(' - ',' to ').replace('-', ' to ')
if line.includes('<ISSN>') or line.includes('<ISSN ') or line.includes '<ISSNLinking>'
rec.ISSN ?= []
v = line.split('>')[1].split('</')[0]
rec.ISSN.push(v) if v not in rec.ISSN
if line.includes '<Keyword>'
rec.keyword ?= []
v = line.split('>')[1].split('</')[0]
rec.keyword.push(v) if v not in rec.keyword
if line.includes '<GeneSymbol>'
rec.gene ?= []
v = line.split('>')[1].split('</')[0]
rec.gene.push(v) if v not in rec.gene
if line.includes('<PublicationType>') or line.includes '<PublicationType '
rec.type ?= []
v = line.split('>')[1].split('</')[0]
rec.type.push(v) if v not in rec.type
if line.includes '<Chemical>'
rec.chemical ?= []
rec.chemical.push {}
if line.includes('<NameOfSubstance>') or line.includes '<NameOfSubstance '
rec.chemical[rec.chemical.length - 1].name = line.split('>')[1].split('</')[0]
rec.chemical[rec.chemical.length - 1].nameID = line.split('UI="')[1].split('"')[0]
if line.includes '<RegistryNumber>'
rec.chemical[rec.chemical.length - 1].registry = line.split('>')[1].split('</')[0]
if line.includes('<DataBank>') or line.includes '<DataBank '
rec.databank ?= []
rec.databank.push {}
if line.includes '<DataBankName>'
rec.databank[rec.databank.length - 1].name = line.split('>')[1].split('</')[0]
if line.includes '<AccessionNumber>'
rec.databank[rec.databank.length - 1].accession ?= []
rec.databank[rec.databank.length - 1].accession.push line.split('>')[1].split('</')[0]
if line.includes('<Grant>') or line.includes '<Grant '
rec.grant ?= []
rec.grant.push {}
if line.includes '<GrantID>'
rec.grant[rec.grant.length - 1].id = line.split('>')[1].split('</')[0]
if line.includes '<Acronym>'
rec.grant[rec.grant.length - 1].acronym = line.split('>')[1].split('</')[0]
if line.includes '<Agency>'
rec.grant[rec.grant.length - 1].agency = line.split('>')[1].split('</')[0]
if line.includes '<Country>'
if (not rec.grant or rec.grant[rec.grant.length - 1].country) and not rec.country
rec.country = line.split('>')[1].split('</')[0]
else
rec.grant[rec.grant.length - 1].country = line.split('>')[1].split('</')[0]
if line.includes('<MeshHeading>') or line.includes '<MeshHeading '
rec.mesh ?= []
rec.mesh.push {}
if line.includes('<DescriptorName>') or line.includes('<DescriptorName ')
rec.mesh[rec.mesh.length - 1].description = line.split('>')[1].split('</')[0]
rec.mesh[rec.mesh.length - 1].descriptionID = line.split('UI="')[1].split('"')[0]
if line.includes('<QualifierName>') or line.includes('<QualifierName ')
rec.mesh[rec.mesh.length - 1].qualifier ?= []
rec.mesh[rec.mesh.length - 1].qualifier.push name: line.split('>')[1].split('</')[0], id: line.split('UI="')[1].split('"')[0]
if line.includes('<Investigator>') or line.includes '<Investigator '
rec.author ?= []
rec.author.push {}
ininv = true
if line.includes('<Author>') or line.includes '<Author '
rec.author ?= []
rec.author.push {}
ininv = false
try # some fields called PersonalNameSubjectList can cause a problem but don't know what they are so not including them
if line.includes '<LastName>'
rec.author[rec.author.length - 1].lastname = line.split('>')[1].split('</')[0]
rec.author[rec.author.length - 1].investigator = true if ininv
if line.includes '<ForeName>' # skip <Initials>
rec.author[rec.author.length - 1].firstname = line.split('>')[1].split('</')[0]
if line.includes '<Affiliation>'
rec.author[rec.author.length - 1].affiliation = line.split('>')[1].split('</')[0]
if line.includes '<Identifier>'
rec.author[rec.author.length - 1].identifier = line.split('>')[1].split('</')[0]
if line.includes('<Note>') or line.includes('<Note ') or line.includes('<GeneralNote>') or line.includes '<GeneralNote '
try
rec.notes ?= []
rec.notes.push line.split('>')[1].split('</')[0]
if line.includes('<DeleteCitation>') or line.includes '<DeleteCitation '
rec.deletedFromMedline = true # this indicates Medline deleted the record, we should prob just remove all these too, but let's see how many there are
if line.includes('<ArticleId>') or line.includes '<ArticleId '
rec.identifier ?= {}
idt = line.split('IdType="')[1].split('"')[0]
rec.identifier[idt] ?= line.split('>')[1].split('</')[0]
if line.includes('<ArticleDate>') or line.includes('ArticleDate ') or line.includes('<PubDate>') or line.includes '<PubDate '
published = {}
if published isnt false and (line.includes('<Year>') or line.includes('<Month>') or line.includes('<Day>'))
published[line.split('>')[0].replace('<', '').toLowerCase()] = line.split('>')[1].split('</')[0]
if batch.length
await @src.pubmed batch
batch = []
console.log fn, total
running -= 1
while files.length
break if howmany > 0 and total >= howmany
await @sleep 1000
if running < streamers
running += 1
_loop files.shift()
console.log total
#if not changes
# total += await @src.pubmed.changes true
# console.log total
return total
P.src.pubmed.load._async = true
P.src.pubmed.load._auth = 'root'
P.src.pubmed.changes = () ->
return @src.pubmed.load true
P.src.pubmed.changes._async = true
P.src.pubmed.changes._auth = 'root'
P.src.pubmed.changes._notify = false
# https://www.nlm.nih.gov/bsd/serfile_addedinfo.html
# listing of all journals in pubmed, might be useful
#P.src.pubmed.journals.load = () ->
# https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html
'''
<Abstract>
<AbstractText> found in <Abstract>; uses Label and NlmCategory attributes
<AccessionNumber> found in <DatabankList>
<AccessionNumberList> found in <DatabankList>
<Acronym> found in <GrantList>
<Affiliation> found in <AuthorList> and <InvestigatorList>
<AffiliationInfo> found in <AuthorList> and <InvestigatorList>; includes <Affiliation> and <Identifier>
<Agency> found in <GrantList>
<Article> uses PubModel attribute
<ArticleDate> uses DateType attribute
<ArticleId> found in <ArticleIdList>
<ArticleTitle>
<Author> found in <AuthorList>
<AuthorList> uses CompleteYN attribute
<Chemical> found in <ChemicalList>
<ChemicalList>
<CitationSubset>
CitedMedium attribute for <JournalIssue>
<CollectiveName> found in <Authorlist>
<CoiStatement>
<CommentsCorrections>
CompleteYN attribute for <AuthorList>, <DataBankList> and <GrantList>
<CopyrightInformation> found in <Abstract>, <OtherAbstract>
<Country>
<DataBank> found in <DataBankList>
<DataBankList> uses CompleteYN attribute
<DataBankName> found in <DataBankList>
<DateCompleted>
<DateCreated>
<DateRevised>
DateType attribute for <ArticleDate>
<Day> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
<DeleteCitation>
<DescriptorName> found in <MeshHeadingList>; uses MajorTopicYN, Type and UI attributes
<ELocationID>
<ForeName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<GeneralNote> uses Owner attribute
<GeneSymbol> found in <GeneSymbolList>
<GeneSymbolList>
<Grant> found in <GrantList>
<GrantID> found in <GrantList>
<GrantList> uses CompleteYN attribute
<History>
<Identifier> found in <AuthorList> and <InvestigatorList>
<Initials> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<Investigator> found in <InvestigatorList>
<InvestigatorList>
<ISOAbbreviation>
<ISSN> uses ISSNType attribute
<ISSNLinking>
ISSNType attribute for <ISSN>
<Issue>
<Journal>
<JournalIssue> uses CitedMedium attribute
<Keyword> found in <KeywordList>; uses MajorTopicYN attribute
<KeywordList> uses Owner attribute
Label attribute for <AbstractText>
<Language>
<LastName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
MajorTopicYN attribute for <DescriptorName> and <QualiferName>
<MedlineCitation> uses Owner, Status, VersionID, and VersionDate attributes
<MedlineDate> found in <PubDate>
<MedlinePgn> found in <Pagination>
<MedlineTA>
<MeshHeading> found in <MeshHeadingList>
<MeshHeadingList>
<Month> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>, <PubDate>
<NameOfSubstance> found in <ChemicalList>; uses UI attribute
NlmCategory attribute for <AbstractText>
<NlmUniqueID>
<Note> found in <CommentsCorrections>
<NumberOfReferences>
<OtherAbstract> uses Type and Language attributes
<OtherID> uses Source attribute
Owner attribute for <GeneralNote>, <KeywordList> and <MedlineCitation>
<Pagination>
<PersonalNameSubject> found in <PersonalNameSubjectList>
<PersonalNameSubjectList>
<PMID> also found in <CommentsCorrections>; uses Version attribute
PrintYN attribute for <JournalIssue>
<PubDate>
<PublicationStatus>
<PublicationType> found in <PublicationTypeList>; uses UI attribute
<PublicationTypeList>
<PubmedArticle>
<PubmedData>
<PubmedPubDate>
PubModel attribute for <Article>
<QualifierName> found in <MeshHeadingList>; uses MajorTopicYN and UI attributes
<RefSource> found in <CommentsCorrections>
<RefType> attribute for <CommentsCorrections>
<RegistryNumber> found in <ChemicalList>
<SpaceFlightMission>
Source attribute for <OtherID>
Status attribute for <MedineCitation>
<Suffix> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<SupplMeshList>
<SupplMeshName> found in <SupplMeshList>; uses Type and UI attributes
<Title>
Type attribute for <Descriptor Name>, <OtherAbstract>, and <SupplMeshName>
<VernacularTitle>
VersionDate attribute for <MedlineCitation>
VersionID attribute for <MedlineCitation>
<Volume>
<Year> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
'''
'''
<PubmedArticle>
<MedlineCitation Status="MEDLINE" Owner="NLM">
<PMID Version="1">1</PMID>
<DateCompleted>
<Year>1976</Year>
<Month>01</Month>
<Day>16</Day>
</DateCompleted>
<DateRevised>
<Year>2019</Year>
<Month>02</Month>
<Day>08</Day>
</DateRevised>
<Article PubModel="Print">
<Journal>
<ISSN IssnType="Print">0006-2944</ISSN>
<JournalIssue CitedMedium="Print">
<Volume>13</Volume>
<Issue>2</Issue>
<PubDate>
<Year>1975</Year>
<Month>Jun</Month>
</PubDate>
</JournalIssue>
<Title>Biochemical medicine</Title>
<ISOAbbreviation>Biochem Med</ISOAbbreviation>
</Journal>
<ArticleTitle>Formate assay in body fluids: application in methanol poisoning.</ArticleTitle>
<Pagination>
<MedlinePgn>117-26</MedlinePgn>
</Pagination>
<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>Makar</LastName>
<ForeName>A B</ForeName>
<Initials>AB</Initials>
</Author>
<Author ValidYN="Y">
<LastName>McMartin</LastName>
<ForeName>K E</ForeName>
<Initials>KE</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Palese</LastName>
<ForeName>M</ForeName>
<Initials>M</Initials>
</Author>
<Author ValidYN="Y">
<LastName>Tephly</LastName>
<ForeName>T R</ForeName>
<Initials>TR</Initials>
</Author>
</AuthorList>
<Language>eng</Language>
<GrantList CompleteYN="Y">
<Grant>
<GrantID>MC_UU_12013/5</GrantID>
<Agency>MRC</Agency>
<Country>United Kingdom</Country>
</Grant>
</GrantList>
<PublicationTypeList>
<PublicationType UI="D016428">Journal Article</PublicationType>
<PublicationType UI="D013487">Research Support, U.S. Gov't, P.H.S.</PublicationType>
</PublicationTypeList>
</Article>
<MedlineJournalInfo>
<Country>United States</Country>
<MedlineTA>Biochem Med</MedlineTA>
<NlmUniqueID>0151424</NlmUniqueID>
<ISSNLinking>0006-2944</ISSNLinking>
</MedlineJournalInfo>
<ChemicalList>
<Chemical>
<RegistryNumber>0</RegistryNumber>
<NameOfSubstance UI="D005561">Formates</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>142M471B3J</RegistryNumber>
<NameOfSubstance UI="D002245">Carbon Dioxide</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>EC 1.2.-</RegistryNumber>
<NameOfSubstance UI="D000445">Aldehyde Oxidoreductases</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>Y4S76JWI15</RegistryNumber>
<NameOfSubstance UI="D000432">Methanol</NameOfSubstance>
</Chemical>
</ChemicalList>
<CitationSubset>IM</CitationSubset>
<MeshHeadingList>
<MeshHeading>
<DescriptorName UI="D000445" MajorTopicYN="N">Aldehyde Oxidoreductases</DescriptorName>
<QualifierName UI="Q000378" MajorTopicYN="N">metabolism</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000818" MajorTopicYN="N">Animals</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D001826" MajorTopicYN="N">Body Fluids</DescriptorName>
<QualifierName UI="Q000032" MajorTopicYN="Y">analysis</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D002245" MajorTopicYN="N">Carbon Dioxide</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D005561" MajorTopicYN="N">Formates</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
<QualifierName UI="Q000506" MajorTopicYN="Y">poisoning</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000882" MajorTopicYN="N">Haplorhini</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006801" MajorTopicYN="N">Humans</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006863" MajorTopicYN="N">Hydrogen-Ion Concentration</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D007700" MajorTopicYN="N">Kinetics</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000432" MajorTopicYN="N">Methanol</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D008722" MajorTopicYN="N">Methods</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D011549" MajorTopicYN="N">Pseudomonas</DescriptorName>
<QualifierName UI="Q000201" MajorTopicYN="N">enzymology</QualifierName>
</MeshHeading>
</MeshHeadingList>
</MedlineCitation>
<PubmedData>
<History>
<PubMedPubDate PubStatus="pubmed">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
</PubMedPubDate>
<PubMedPubDate PubStatus="medline">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>1</Minute>
</PubMedPubDate>
<PubMedPubDate PubStatus="entrez">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>0</Minute>
</PubMedPubDate>
</History>
<PublicationStatus>ppublish</PublicationStatus>
<ArticleIdList>
<ArticleId IdType="pubmed">1</ArticleId>
<ArticleId IdType="doi">10.1016/0006-2944(75)90147-7</ArticleId>
</ArticleIdList>
</PubmedData>
</PubmedArticle>
'''
| 30367 |
# https://www.nlm.nih.gov/databases/download/pubmed_medline.html
# https://www.nlm.nih.gov/bsd/licensee/2021_stats/2021_LO.html
# in case the medline data does not include all PMCs or PMIDs, there is a converter API
# and/or PMC sources that could be used to map things (with just over 6 million PMC IDs in the pubmed
# data, looks like probably all PMC articles were in the data dump anyway)
# https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/
# https://www.ncbi.nlm.nih.gov/pmc/tools/ftp/
# annual files published each December, listed at: https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/
# lists files such as https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed21n0001.xml.gz
# up to 1062 for 2020. Contains other files including .md5 files for each gz file
# Managed to load 31847922
# PMID 30036026 failed with a “published” value of 1-01-01
# daily update files listed at https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/
# such as https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/pubmed21n1063.xml.gz
# can contain one or more files for each day since the last annual file dump
P.src.pubmed.load = (changes) ->
# there are 30k or less records per pubmed file so tried batching by file, but streaming more than one file at a time caused OOM
# so reduce batch size if necessary. default node heap size is 1400M I think, so increased to 3072M and try again
# check if increasing heap that machine running it has enough - AND note that on production if using PM2 to run as cluster, then
# need enough memory for each process to max out. Running 3 with 15k batch size was stable but reaching almost 3000M at times and
# didn't seem much faster, so now set to do whole files as batches with two streamers at a time, see how that goes
batchsize = -1 # how many records to batch upload at a time
streamers = 1 # how many files to stream at a time
howmany = @params.howmany ? -1 # max number of lines to process. set to -1 to keep going...
await @src.pubmed('') if @refresh and not changes
addr = if changes then 'https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/' else 'https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/'
files = []
listing = await @fetch addr
for a in listing.split 'href="'
f = a.split('"')[0]
if f.startsWith('pubmed') and f.endsWith('.gz') and ((@refresh and not changes) or not exists = await @src.pubmed.count 'srcfile:"' + addr + f + '"')
files.push addr + f
running = 0
total = 0
_loop = (fn) =>
console.log 'Pubmed loading' + (if changes then ' changes' else ''), fn, files.length, running
# stream them, unzip, and parse line by line, processing each record once a full record has been parsed out
# the first 2020 gz file for example is 19M, uncompressed it is 182M. 30k records or so per file
batch = []
rec = {}
published = false
ininv = false
for await line from readline.createInterface input: (await fetch fn).body.pipe zlib.createGunzip()
if batchsize > 0 and batch.length >= batchsize
await @src.pubmed batch
batch = []
console.log fn, total
line = line.trim().replace('&', '&')
if line is '</PubmedArticle>' # <PubmedArticle>...</PubmedArticle> is a total article record
total += 1
if published isnt false and published.year
rec.year = parseInt published.year
if published.month and published.month.length > 2
published.month = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'].indexOf published.month.toLowerCase().substr(0, 3)
published.month = published.month.toString() if typeof published.month is 'number'
published.month = '0' + published.month if published.month and published.month.length is 1
published.day = published.day.toString() if typeof published.day is 'number'
published.day = '0' + published.day if published.day and published.day.length is 1
rec.published = published.year + '-' + (published.month ? '01') + '-' + (published.day ? '01')
rec.publishedAt = await @epoch rec.published
rec.srcfile = fn
rec._id = rec.PMID
batch.push rec
rec = {}
published = false
ininv = false
break if total is howmany
else
km =
'<ArticleTitle>': 'title'
'<AbstractText>': 'abstract'
'<ISOAbbreviation>': 'iso'
'<Issue>': 'issue'
'<Title>': 'journal'
'<Language>': 'language'
'<NlmUniqueID>': 'NLMID'
'<PMID>': 'PMID'
'<Volume>': 'volume'
'<CopyrightInformation>': 'copyright'
'<NumberOfReferences>': 'references_count'
'<PublicationStatus>': 'status'
'<SpaceFlightMission>': 'spaceflightmission'
for k of km
rec[km[k]] ?= line.split('>')[1].split('</')[0] if line.includes(k) or line.includes k.replace '>', ' '
if line.includes '<MedlinePgn>'
# do this because something like 1345-56 makes ES attempt to interpret a date, then others that don't look like a date will fail
rec.pages = line.split('>')[1].split('</')[0].replace(' - ',' to ').replace('-', ' to ')
if line.includes('<ISSN>') or line.includes('<ISSN ') or line.includes '<ISSNLinking>'
rec.ISSN ?= []
v = line.split('>')[1].split('</')[0]
rec.ISSN.push(v) if v not in rec.ISSN
if line.includes '<Keyword>'
rec.keyword ?= []
v = line.split('>')[1].split('</')[0]
rec.keyword.push(v) if v not in rec.keyword
if line.includes '<GeneSymbol>'
rec.gene ?= []
v = line.split('>')[1].split('</')[0]
rec.gene.push(v) if v not in rec.gene
if line.includes('<PublicationType>') or line.includes '<PublicationType '
rec.type ?= []
v = line.split('>')[1].split('</')[0]
rec.type.push(v) if v not in rec.type
if line.includes '<Chemical>'
rec.chemical ?= []
rec.chemical.push {}
if line.includes('<NameOfSubstance>') or line.includes '<NameOfSubstance '
rec.chemical[rec.chemical.length - 1].name = line.split('>')[1].split('</')[0]
rec.chemical[rec.chemical.length - 1].nameID = line.split('UI="')[1].split('"')[0]
if line.includes '<RegistryNumber>'
rec.chemical[rec.chemical.length - 1].registry = line.split('>')[1].split('</')[0]
if line.includes('<DataBank>') or line.includes '<DataBank '
rec.databank ?= []
rec.databank.push {}
if line.includes '<DataBankName>'
rec.databank[rec.databank.length - 1].name = line.split('>')[1].split('</')[0]
if line.includes '<AccessionNumber>'
rec.databank[rec.databank.length - 1].accession ?= []
rec.databank[rec.databank.length - 1].accession.push line.split('>')[1].split('</')[0]
if line.includes('<Grant>') or line.includes '<Grant '
rec.grant ?= []
rec.grant.push {}
if line.includes '<GrantID>'
rec.grant[rec.grant.length - 1].id = line.split('>')[1].split('</')[0]
if line.includes '<Acronym>'
rec.grant[rec.grant.length - 1].acronym = line.split('>')[1].split('</')[0]
if line.includes '<Agency>'
rec.grant[rec.grant.length - 1].agency = line.split('>')[1].split('</')[0]
if line.includes '<Country>'
if (not rec.grant or rec.grant[rec.grant.length - 1].country) and not rec.country
rec.country = line.split('>')[1].split('</')[0]
else
rec.grant[rec.grant.length - 1].country = line.split('>')[1].split('</')[0]
if line.includes('<MeshHeading>') or line.includes '<MeshHeading '
rec.mesh ?= []
rec.mesh.push {}
if line.includes('<DescriptorName>') or line.includes('<DescriptorName ')
rec.mesh[rec.mesh.length - 1].description = line.split('>')[1].split('</')[0]
rec.mesh[rec.mesh.length - 1].descriptionID = line.split('UI="')[1].split('"')[0]
if line.includes('<QualifierName>') or line.includes('<QualifierName ')
rec.mesh[rec.mesh.length - 1].qualifier ?= []
rec.mesh[rec.mesh.length - 1].qualifier.push name: line.split('>')[1].split('</')[0], id: line.split('UI="')[1].split('"')[0]
if line.includes('<Investigator>') or line.includes '<Investigator '
rec.author ?= []
rec.author.push {}
ininv = true
if line.includes('<Author>') or line.includes '<Author '
rec.author ?= []
rec.author.push {}
ininv = false
try # some fields called PersonalNameSubjectList can cause a problem but don't know what they are so not including them
if line.includes '<LastName>'
rec.author[rec.author.length - 1].lastname = line.split('>')[1].split('</')[0]
rec.author[rec.author.length - 1].investigator = true if ininv
if line.includes '<ForeName>' # skip <Initials>
rec.author[rec.author.length - 1].firstname = line.split('>')[1].split('</')[0]
if line.includes '<Affiliation>'
rec.author[rec.author.length - 1].affiliation = line.split('>')[1].split('</')[0]
if line.includes '<Identifier>'
rec.author[rec.author.length - 1].identifier = line.split('>')[1].split('</')[0]
if line.includes('<Note>') or line.includes('<Note ') or line.includes('<GeneralNote>') or line.includes '<GeneralNote '
try
rec.notes ?= []
rec.notes.push line.split('>')[1].split('</')[0]
if line.includes('<DeleteCitation>') or line.includes '<DeleteCitation '
rec.deletedFromMedline = true # this indicates Medline deleted the record, we should prob just remove all these too, but let's see how many there are
if line.includes('<ArticleId>') or line.includes '<ArticleId '
rec.identifier ?= {}
idt = line.split('IdType="')[1].split('"')[0]
rec.identifier[idt] ?= line.split('>')[1].split('</')[0]
if line.includes('<ArticleDate>') or line.includes('ArticleDate ') or line.includes('<PubDate>') or line.includes '<PubDate '
published = {}
if published isnt false and (line.includes('<Year>') or line.includes('<Month>') or line.includes('<Day>'))
published[line.split('>')[0].replace('<', '').toLowerCase()] = line.split('>')[1].split('</')[0]
if batch.length
await @src.pubmed batch
batch = []
console.log fn, total
running -= 1
while files.length
break if howmany > 0 and total >= howmany
await @sleep 1000
if running < streamers
running += 1
_loop files.shift()
console.log total
#if not changes
# total += await @src.pubmed.changes true
# console.log total
return total
P.src.pubmed.load._async = true
P.src.pubmed.load._auth = 'root'
P.src.pubmed.changes = () ->
return @src.pubmed.load true
P.src.pubmed.changes._async = true
P.src.pubmed.changes._auth = 'root'
P.src.pubmed.changes._notify = false
# https://www.nlm.nih.gov/bsd/serfile_addedinfo.html
# listing of all journals in pubmed, might be useful
#P.src.pubmed.journals.load = () ->
# https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html
'''
<Abstract>
<AbstractText> found in <Abstract>; uses Label and NlmCategory attributes
<AccessionNumber> found in <DatabankList>
<AccessionNumberList> found in <DatabankList>
<Acronym> found in <GrantList>
<Affiliation> found in <AuthorList> and <InvestigatorList>
<AffiliationInfo> found in <AuthorList> and <InvestigatorList>; includes <Affiliation> and <Identifier>
<Agency> found in <GrantList>
<Article> uses PubModel attribute
<ArticleDate> uses DateType attribute
<ArticleId> found in <ArticleIdList>
<ArticleTitle>
<Author> found in <AuthorList>
<AuthorList> uses CompleteYN attribute
<Chemical> found in <ChemicalList>
<ChemicalList>
<CitationSubset>
CitedMedium attribute for <JournalIssue>
<CollectiveName> found in <Authorlist>
<CoiStatement>
<CommentsCorrections>
CompleteYN attribute for <AuthorList>, <DataBankList> and <GrantList>
<CopyrightInformation> found in <Abstract>, <OtherAbstract>
<Country>
<DataBank> found in <DataBankList>
<DataBankList> uses CompleteYN attribute
<DataBankName> found in <DataBankList>
<DateCompleted>
<DateCreated>
<DateRevised>
DateType attribute for <ArticleDate>
<Day> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
<DeleteCitation>
<DescriptorName> found in <MeshHeadingList>; uses MajorTopicYN, Type and UI attributes
<ELocationID>
<ForeName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<GeneralNote> uses Owner attribute
<GeneSymbol> found in <GeneSymbolList>
<GeneSymbolList>
<Grant> found in <GrantList>
<GrantID> found in <GrantList>
<GrantList> uses CompleteYN attribute
<History>
<Identifier> found in <AuthorList> and <InvestigatorList>
<Initials> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<Investigator> found in <InvestigatorList>
<InvestigatorList>
<ISOAbbreviation>
<ISSN> uses ISSNType attribute
<ISSNLinking>
ISSNType attribute for <ISSN>
<Issue>
<Journal>
<JournalIssue> uses CitedMedium attribute
<Keyword> found in <KeywordList>; uses MajorTopicYN attribute
<KeywordList> uses Owner attribute
Label attribute for <AbstractText>
<Language>
<LastName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
MajorTopicYN attribute for <DescriptorName> and <QualiferName>
<MedlineCitation> uses Owner, Status, VersionID, and VersionDate attributes
<MedlineDate> found in <PubDate>
<MedlinePgn> found in <Pagination>
<MedlineTA>
<MeshHeading> found in <MeshHeadingList>
<MeshHeadingList>
<Month> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>, <PubDate>
<NameOfSubstance> found in <ChemicalList>; uses UI attribute
NlmCategory attribute for <AbstractText>
<NlmUniqueID>
<Note> found in <CommentsCorrections>
<NumberOfReferences>
<OtherAbstract> uses Type and Language attributes
<OtherID> uses Source attribute
Owner attribute for <GeneralNote>, <KeywordList> and <MedlineCitation>
<Pagination>
<PersonalNameSubject> found in <PersonalNameSubjectList>
<PersonalNameSubjectList>
<PMID> also found in <CommentsCorrections>; uses Version attribute
PrintYN attribute for <JournalIssue>
<PubDate>
<PublicationStatus>
<PublicationType> found in <PublicationTypeList>; uses UI attribute
<PublicationTypeList>
<PubmedArticle>
<PubmedData>
<PubmedPubDate>
PubModel attribute for <Article>
<QualifierName> found in <MeshHeadingList>; uses MajorTopicYN and UI attributes
<RefSource> found in <CommentsCorrections>
<RefType> attribute for <CommentsCorrections>
<RegistryNumber> found in <ChemicalList>
<SpaceFlightMission>
Source attribute for <OtherID>
Status attribute for <MedineCitation>
<Suffix> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<SupplMeshList>
<SupplMeshName> found in <SupplMeshList>; uses Type and UI attributes
<Title>
Type attribute for <Descriptor Name>, <OtherAbstract>, and <SupplMeshName>
<VernacularTitle>
VersionDate attribute for <MedlineCitation>
VersionID attribute for <MedlineCitation>
<Volume>
<Year> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
'''
'''
<PubmedArticle>
<MedlineCitation Status="MEDLINE" Owner="NLM">
<PMID Version="1">1</PMID>
<DateCompleted>
<Year>1976</Year>
<Month>01</Month>
<Day>16</Day>
</DateCompleted>
<DateRevised>
<Year>2019</Year>
<Month>02</Month>
<Day>08</Day>
</DateRevised>
<Article PubModel="Print">
<Journal>
<ISSN IssnType="Print">0006-2944</ISSN>
<JournalIssue CitedMedium="Print">
<Volume>13</Volume>
<Issue>2</Issue>
<PubDate>
<Year>1975</Year>
<Month>Jun</Month>
</PubDate>
</JournalIssue>
<Title>Biochemical medicine</Title>
<ISOAbbreviation>Biochem Med</ISOAbbreviation>
</Journal>
<ArticleTitle>Formate assay in body fluids: application in methanol poisoning.</ArticleTitle>
<Pagination>
<MedlinePgn>117-26</MedlinePgn>
</Pagination>
<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName><NAME></LastName>
<ForeName>A B</ForeName>
<Initials>AB</Initials>
</Author>
<Author ValidYN="Y">
<LastName><NAME></LastName>
<ForeName>K E</ForeName>
<Initials>KE</Initials>
</Author>
<Author ValidYN="Y">
<LastName><NAME></LastName>
<ForeName>M</ForeName>
<Initials>M</Initials>
</Author>
<Author ValidYN="Y">
<LastName><NAME></LastName>
<ForeName>T R</ForeName>
<Initials>TR</Initials>
</Author>
</AuthorList>
<Language>eng</Language>
<GrantList CompleteYN="Y">
<Grant>
<GrantID>MC_UU_12013/5</GrantID>
<Agency>MRC</Agency>
<Country>United Kingdom</Country>
</Grant>
</GrantList>
<PublicationTypeList>
<PublicationType UI="D016428">Journal Article</PublicationType>
<PublicationType UI="D013487">Research Support, U.S. Gov't, P.H.S.</PublicationType>
</PublicationTypeList>
</Article>
<MedlineJournalInfo>
<Country>United States</Country>
<MedlineTA>Biochem Med</MedlineTA>
<NlmUniqueID>0151424</NlmUniqueID>
<ISSNLinking>0006-2944</ISSNLinking>
</MedlineJournalInfo>
<ChemicalList>
<Chemical>
<RegistryNumber>0</RegistryNumber>
<NameOfSubstance UI="D005561">Formates</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>142M471B3J</RegistryNumber>
<NameOfSubstance UI="D002245">Carbon Dioxide</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>EC 1.2.-</RegistryNumber>
<NameOfSubstance UI="D000445">Aldehyde Oxidoreductases</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>Y4S76JWI15</RegistryNumber>
<NameOfSubstance UI="D000432">Methanol</NameOfSubstance>
</Chemical>
</ChemicalList>
<CitationSubset>IM</CitationSubset>
<MeshHeadingList>
<MeshHeading>
<DescriptorName UI="D000445" MajorTopicYN="N">Aldehyde Oxidoreductases</DescriptorName>
<QualifierName UI="Q000378" MajorTopicYN="N">metabolism</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000818" MajorTopicYN="N">Animals</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D001826" MajorTopicYN="N">Body Fluids</DescriptorName>
<QualifierName UI="Q000032" MajorTopicYN="Y">analysis</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D002245" MajorTopicYN="N">Carbon Dioxide</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D005561" MajorTopicYN="N">Formates</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
<QualifierName UI="Q000506" MajorTopicYN="Y">poisoning</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000882" MajorTopicYN="N">Haplorhini</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006801" MajorTopicYN="N">Humans</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006863" MajorTopicYN="N">Hydrogen-Ion Concentration</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D007700" MajorTopicYN="N">Kinetics</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000432" MajorTopicYN="N">Methanol</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D008722" MajorTopicYN="N">Methods</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D011549" MajorTopicYN="N">Pseudomonas</DescriptorName>
<QualifierName UI="Q000201" MajorTopicYN="N">enzymology</QualifierName>
</MeshHeading>
</MeshHeadingList>
</MedlineCitation>
<PubmedData>
<History>
<PubMedPubDate PubStatus="pubmed">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
</PubMedPubDate>
<PubMedPubDate PubStatus="medline">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>1</Minute>
</PubMedPubDate>
<PubMedPubDate PubStatus="entrez">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>0</Minute>
</PubMedPubDate>
</History>
<PublicationStatus>ppublish</PublicationStatus>
<ArticleIdList>
<ArticleId IdType="pubmed">1</ArticleId>
<ArticleId IdType="doi">10.1016/0006-2944(75)90147-7</ArticleId>
</ArticleIdList>
</PubmedData>
</PubmedArticle>
'''
| true |
# https://www.nlm.nih.gov/databases/download/pubmed_medline.html
# https://www.nlm.nih.gov/bsd/licensee/2021_stats/2021_LO.html
# in case the medline data does not include all PMCs or PMIDs, there is a converter API
# and/or PMC sources that could be used to map things (with just over 6 million PMC IDs in the pubmed
# data, looks like probably all PMC articles were in the data dump anyway)
# https://www.ncbi.nlm.nih.gov/pmc/tools/id-converter-api/
# https://www.ncbi.nlm.nih.gov/pmc/tools/ftp/
# annual files published each December, listed at: https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/
# lists files such as https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed21n0001.xml.gz
# up to 1062 for 2020. Contains other files including .md5 files for each gz file
# Managed to load 31847922
# PMID 30036026 failed with a “published” value of 1-01-01
# daily update files listed at https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/
# such as https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/pubmed21n1063.xml.gz
# can contain one or more files for each day since the last annual file dump
P.src.pubmed.load = (changes) ->
# there are 30k or less records per pubmed file so tried batching by file, but streaming more than one file at a time caused OOM
# so reduce batch size if necessary. default node heap size is 1400M I think, so increased to 3072M and try again
# check if increasing heap that machine running it has enough - AND note that on production if using PM2 to run as cluster, then
# need enough memory for each process to max out. Running 3 with 15k batch size was stable but reaching almost 3000M at times and
# didn't seem much faster, so now set to do whole files as batches with two streamers at a time, see how that goes
batchsize = -1 # how many records to batch upload at a time
streamers = 1 # how many files to stream at a time
howmany = @params.howmany ? -1 # max number of lines to process. set to -1 to keep going...
await @src.pubmed('') if @refresh and not changes
addr = if changes then 'https://ftp.ncbi.nlm.nih.gov/pubmed/updatefiles/' else 'https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/'
files = []
listing = await @fetch addr
for a in listing.split 'href="'
f = a.split('"')[0]
if f.startsWith('pubmed') and f.endsWith('.gz') and ((@refresh and not changes) or not exists = await @src.pubmed.count 'srcfile:"' + addr + f + '"')
files.push addr + f
running = 0
total = 0
_loop = (fn) =>
console.log 'Pubmed loading' + (if changes then ' changes' else ''), fn, files.length, running
# stream them, unzip, and parse line by line, processing each record once a full record has been parsed out
# the first 2020 gz file for example is 19M, uncompressed it is 182M. 30k records or so per file
batch = []
rec = {}
published = false
ininv = false
for await line from readline.createInterface input: (await fetch fn).body.pipe zlib.createGunzip()
if batchsize > 0 and batch.length >= batchsize
await @src.pubmed batch
batch = []
console.log fn, total
line = line.trim().replace('&', '&')
if line is '</PubmedArticle>' # <PubmedArticle>...</PubmedArticle> is a total article record
total += 1
if published isnt false and published.year
rec.year = parseInt published.year
if published.month and published.month.length > 2
published.month = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'].indexOf published.month.toLowerCase().substr(0, 3)
published.month = published.month.toString() if typeof published.month is 'number'
published.month = '0' + published.month if published.month and published.month.length is 1
published.day = published.day.toString() if typeof published.day is 'number'
published.day = '0' + published.day if published.day and published.day.length is 1
rec.published = published.year + '-' + (published.month ? '01') + '-' + (published.day ? '01')
rec.publishedAt = await @epoch rec.published
rec.srcfile = fn
rec._id = rec.PMID
batch.push rec
rec = {}
published = false
ininv = false
break if total is howmany
else
km =
'<ArticleTitle>': 'title'
'<AbstractText>': 'abstract'
'<ISOAbbreviation>': 'iso'
'<Issue>': 'issue'
'<Title>': 'journal'
'<Language>': 'language'
'<NlmUniqueID>': 'NLMID'
'<PMID>': 'PMID'
'<Volume>': 'volume'
'<CopyrightInformation>': 'copyright'
'<NumberOfReferences>': 'references_count'
'<PublicationStatus>': 'status'
'<SpaceFlightMission>': 'spaceflightmission'
for k of km
rec[km[k]] ?= line.split('>')[1].split('</')[0] if line.includes(k) or line.includes k.replace '>', ' '
if line.includes '<MedlinePgn>'
# do this because something like 1345-56 makes ES attempt to interpret a date, then others that don't look like a date will fail
rec.pages = line.split('>')[1].split('</')[0].replace(' - ',' to ').replace('-', ' to ')
if line.includes('<ISSN>') or line.includes('<ISSN ') or line.includes '<ISSNLinking>'
rec.ISSN ?= []
v = line.split('>')[1].split('</')[0]
rec.ISSN.push(v) if v not in rec.ISSN
if line.includes '<Keyword>'
rec.keyword ?= []
v = line.split('>')[1].split('</')[0]
rec.keyword.push(v) if v not in rec.keyword
if line.includes '<GeneSymbol>'
rec.gene ?= []
v = line.split('>')[1].split('</')[0]
rec.gene.push(v) if v not in rec.gene
if line.includes('<PublicationType>') or line.includes '<PublicationType '
rec.type ?= []
v = line.split('>')[1].split('</')[0]
rec.type.push(v) if v not in rec.type
if line.includes '<Chemical>'
rec.chemical ?= []
rec.chemical.push {}
if line.includes('<NameOfSubstance>') or line.includes '<NameOfSubstance '
rec.chemical[rec.chemical.length - 1].name = line.split('>')[1].split('</')[0]
rec.chemical[rec.chemical.length - 1].nameID = line.split('UI="')[1].split('"')[0]
if line.includes '<RegistryNumber>'
rec.chemical[rec.chemical.length - 1].registry = line.split('>')[1].split('</')[0]
if line.includes('<DataBank>') or line.includes '<DataBank '
rec.databank ?= []
rec.databank.push {}
if line.includes '<DataBankName>'
rec.databank[rec.databank.length - 1].name = line.split('>')[1].split('</')[0]
if line.includes '<AccessionNumber>'
rec.databank[rec.databank.length - 1].accession ?= []
rec.databank[rec.databank.length - 1].accession.push line.split('>')[1].split('</')[0]
if line.includes('<Grant>') or line.includes '<Grant '
rec.grant ?= []
rec.grant.push {}
if line.includes '<GrantID>'
rec.grant[rec.grant.length - 1].id = line.split('>')[1].split('</')[0]
if line.includes '<Acronym>'
rec.grant[rec.grant.length - 1].acronym = line.split('>')[1].split('</')[0]
if line.includes '<Agency>'
rec.grant[rec.grant.length - 1].agency = line.split('>')[1].split('</')[0]
if line.includes '<Country>'
if (not rec.grant or rec.grant[rec.grant.length - 1].country) and not rec.country
rec.country = line.split('>')[1].split('</')[0]
else
rec.grant[rec.grant.length - 1].country = line.split('>')[1].split('</')[0]
if line.includes('<MeshHeading>') or line.includes '<MeshHeading '
rec.mesh ?= []
rec.mesh.push {}
if line.includes('<DescriptorName>') or line.includes('<DescriptorName ')
rec.mesh[rec.mesh.length - 1].description = line.split('>')[1].split('</')[0]
rec.mesh[rec.mesh.length - 1].descriptionID = line.split('UI="')[1].split('"')[0]
if line.includes('<QualifierName>') or line.includes('<QualifierName ')
rec.mesh[rec.mesh.length - 1].qualifier ?= []
rec.mesh[rec.mesh.length - 1].qualifier.push name: line.split('>')[1].split('</')[0], id: line.split('UI="')[1].split('"')[0]
if line.includes('<Investigator>') or line.includes '<Investigator '
rec.author ?= []
rec.author.push {}
ininv = true
if line.includes('<Author>') or line.includes '<Author '
rec.author ?= []
rec.author.push {}
ininv = false
try # some fields called PersonalNameSubjectList can cause a problem but don't know what they are so not including them
if line.includes '<LastName>'
rec.author[rec.author.length - 1].lastname = line.split('>')[1].split('</')[0]
rec.author[rec.author.length - 1].investigator = true if ininv
if line.includes '<ForeName>' # skip <Initials>
rec.author[rec.author.length - 1].firstname = line.split('>')[1].split('</')[0]
if line.includes '<Affiliation>'
rec.author[rec.author.length - 1].affiliation = line.split('>')[1].split('</')[0]
if line.includes '<Identifier>'
rec.author[rec.author.length - 1].identifier = line.split('>')[1].split('</')[0]
if line.includes('<Note>') or line.includes('<Note ') or line.includes('<GeneralNote>') or line.includes '<GeneralNote '
try
rec.notes ?= []
rec.notes.push line.split('>')[1].split('</')[0]
if line.includes('<DeleteCitation>') or line.includes '<DeleteCitation '
rec.deletedFromMedline = true # this indicates Medline deleted the record, we should prob just remove all these too, but let's see how many there are
if line.includes('<ArticleId>') or line.includes '<ArticleId '
rec.identifier ?= {}
idt = line.split('IdType="')[1].split('"')[0]
rec.identifier[idt] ?= line.split('>')[1].split('</')[0]
if line.includes('<ArticleDate>') or line.includes('ArticleDate ') or line.includes('<PubDate>') or line.includes '<PubDate '
published = {}
if published isnt false and (line.includes('<Year>') or line.includes('<Month>') or line.includes('<Day>'))
published[line.split('>')[0].replace('<', '').toLowerCase()] = line.split('>')[1].split('</')[0]
if batch.length
await @src.pubmed batch
batch = []
console.log fn, total
running -= 1
while files.length
break if howmany > 0 and total >= howmany
await @sleep 1000
if running < streamers
running += 1
_loop files.shift()
console.log total
#if not changes
# total += await @src.pubmed.changes true
# console.log total
return total
P.src.pubmed.load._async = true
P.src.pubmed.load._auth = 'root'
P.src.pubmed.changes = () ->
return @src.pubmed.load true
P.src.pubmed.changes._async = true
P.src.pubmed.changes._auth = 'root'
P.src.pubmed.changes._notify = false
# https://www.nlm.nih.gov/bsd/serfile_addedinfo.html
# listing of all journals in pubmed, might be useful
#P.src.pubmed.journals.load = () ->
# https://www.nlm.nih.gov/bsd/licensee/elements_alphabetical.html
'''
<Abstract>
<AbstractText> found in <Abstract>; uses Label and NlmCategory attributes
<AccessionNumber> found in <DatabankList>
<AccessionNumberList> found in <DatabankList>
<Acronym> found in <GrantList>
<Affiliation> found in <AuthorList> and <InvestigatorList>
<AffiliationInfo> found in <AuthorList> and <InvestigatorList>; includes <Affiliation> and <Identifier>
<Agency> found in <GrantList>
<Article> uses PubModel attribute
<ArticleDate> uses DateType attribute
<ArticleId> found in <ArticleIdList>
<ArticleTitle>
<Author> found in <AuthorList>
<AuthorList> uses CompleteYN attribute
<Chemical> found in <ChemicalList>
<ChemicalList>
<CitationSubset>
CitedMedium attribute for <JournalIssue>
<CollectiveName> found in <Authorlist>
<CoiStatement>
<CommentsCorrections>
CompleteYN attribute for <AuthorList>, <DataBankList> and <GrantList>
<CopyrightInformation> found in <Abstract>, <OtherAbstract>
<Country>
<DataBank> found in <DataBankList>
<DataBankList> uses CompleteYN attribute
<DataBankName> found in <DataBankList>
<DateCompleted>
<DateCreated>
<DateRevised>
DateType attribute for <ArticleDate>
<Day> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
<DeleteCitation>
<DescriptorName> found in <MeshHeadingList>; uses MajorTopicYN, Type and UI attributes
<ELocationID>
<ForeName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<GeneralNote> uses Owner attribute
<GeneSymbol> found in <GeneSymbolList>
<GeneSymbolList>
<Grant> found in <GrantList>
<GrantID> found in <GrantList>
<GrantList> uses CompleteYN attribute
<History>
<Identifier> found in <AuthorList> and <InvestigatorList>
<Initials> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<Investigator> found in <InvestigatorList>
<InvestigatorList>
<ISOAbbreviation>
<ISSN> uses ISSNType attribute
<ISSNLinking>
ISSNType attribute for <ISSN>
<Issue>
<Journal>
<JournalIssue> uses CitedMedium attribute
<Keyword> found in <KeywordList>; uses MajorTopicYN attribute
<KeywordList> uses Owner attribute
Label attribute for <AbstractText>
<Language>
<LastName> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
MajorTopicYN attribute for <DescriptorName> and <QualiferName>
<MedlineCitation> uses Owner, Status, VersionID, and VersionDate attributes
<MedlineDate> found in <PubDate>
<MedlinePgn> found in <Pagination>
<MedlineTA>
<MeshHeading> found in <MeshHeadingList>
<MeshHeadingList>
<Month> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>, <PubDate>
<NameOfSubstance> found in <ChemicalList>; uses UI attribute
NlmCategory attribute for <AbstractText>
<NlmUniqueID>
<Note> found in <CommentsCorrections>
<NumberOfReferences>
<OtherAbstract> uses Type and Language attributes
<OtherID> uses Source attribute
Owner attribute for <GeneralNote>, <KeywordList> and <MedlineCitation>
<Pagination>
<PersonalNameSubject> found in <PersonalNameSubjectList>
<PersonalNameSubjectList>
<PMID> also found in <CommentsCorrections>; uses Version attribute
PrintYN attribute for <JournalIssue>
<PubDate>
<PublicationStatus>
<PublicationType> found in <PublicationTypeList>; uses UI attribute
<PublicationTypeList>
<PubmedArticle>
<PubmedData>
<PubmedPubDate>
PubModel attribute for <Article>
<QualifierName> found in <MeshHeadingList>; uses MajorTopicYN and UI attributes
<RefSource> found in <CommentsCorrections>
<RefType> attribute for <CommentsCorrections>
<RegistryNumber> found in <ChemicalList>
<SpaceFlightMission>
Source attribute for <OtherID>
Status attribute for <MedineCitation>
<Suffix> found in <AuthorList>, <InvestigatorList>, <PersonalNameSubjectList>
<SupplMeshList>
<SupplMeshName> found in <SupplMeshList>; uses Type and UI attributes
<Title>
Type attribute for <Descriptor Name>, <OtherAbstract>, and <SupplMeshName>
<VernacularTitle>
VersionDate attribute for <MedlineCitation>
VersionID attribute for <MedlineCitation>
<Volume>
<Year> found in <ArticleDate>, <DateCompleted>, <DateCreated>, <DateRevised>,<PubDate>
'''
'''
<PubmedArticle>
<MedlineCitation Status="MEDLINE" Owner="NLM">
<PMID Version="1">1</PMID>
<DateCompleted>
<Year>1976</Year>
<Month>01</Month>
<Day>16</Day>
</DateCompleted>
<DateRevised>
<Year>2019</Year>
<Month>02</Month>
<Day>08</Day>
</DateRevised>
<Article PubModel="Print">
<Journal>
<ISSN IssnType="Print">0006-2944</ISSN>
<JournalIssue CitedMedium="Print">
<Volume>13</Volume>
<Issue>2</Issue>
<PubDate>
<Year>1975</Year>
<Month>Jun</Month>
</PubDate>
</JournalIssue>
<Title>Biochemical medicine</Title>
<ISOAbbreviation>Biochem Med</ISOAbbreviation>
</Journal>
<ArticleTitle>Formate assay in body fluids: application in methanol poisoning.</ArticleTitle>
<Pagination>
<MedlinePgn>117-26</MedlinePgn>
</Pagination>
<AuthorList CompleteYN="Y">
<Author ValidYN="Y">
<LastName>PI:NAME:<NAME>END_PI</LastName>
<ForeName>A B</ForeName>
<Initials>AB</Initials>
</Author>
<Author ValidYN="Y">
<LastName>PI:NAME:<NAME>END_PI</LastName>
<ForeName>K E</ForeName>
<Initials>KE</Initials>
</Author>
<Author ValidYN="Y">
<LastName>PI:NAME:<NAME>END_PI</LastName>
<ForeName>M</ForeName>
<Initials>M</Initials>
</Author>
<Author ValidYN="Y">
<LastName>PI:NAME:<NAME>END_PI</LastName>
<ForeName>T R</ForeName>
<Initials>TR</Initials>
</Author>
</AuthorList>
<Language>eng</Language>
<GrantList CompleteYN="Y">
<Grant>
<GrantID>MC_UU_12013/5</GrantID>
<Agency>MRC</Agency>
<Country>United Kingdom</Country>
</Grant>
</GrantList>
<PublicationTypeList>
<PublicationType UI="D016428">Journal Article</PublicationType>
<PublicationType UI="D013487">Research Support, U.S. Gov't, P.H.S.</PublicationType>
</PublicationTypeList>
</Article>
<MedlineJournalInfo>
<Country>United States</Country>
<MedlineTA>Biochem Med</MedlineTA>
<NlmUniqueID>0151424</NlmUniqueID>
<ISSNLinking>0006-2944</ISSNLinking>
</MedlineJournalInfo>
<ChemicalList>
<Chemical>
<RegistryNumber>0</RegistryNumber>
<NameOfSubstance UI="D005561">Formates</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>142M471B3J</RegistryNumber>
<NameOfSubstance UI="D002245">Carbon Dioxide</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>EC 1.2.-</RegistryNumber>
<NameOfSubstance UI="D000445">Aldehyde Oxidoreductases</NameOfSubstance>
</Chemical>
<Chemical>
<RegistryNumber>Y4S76JWI15</RegistryNumber>
<NameOfSubstance UI="D000432">Methanol</NameOfSubstance>
</Chemical>
</ChemicalList>
<CitationSubset>IM</CitationSubset>
<MeshHeadingList>
<MeshHeading>
<DescriptorName UI="D000445" MajorTopicYN="N">Aldehyde Oxidoreductases</DescriptorName>
<QualifierName UI="Q000378" MajorTopicYN="N">metabolism</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000818" MajorTopicYN="N">Animals</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D001826" MajorTopicYN="N">Body Fluids</DescriptorName>
<QualifierName UI="Q000032" MajorTopicYN="Y">analysis</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D002245" MajorTopicYN="N">Carbon Dioxide</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D005561" MajorTopicYN="N">Formates</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
<QualifierName UI="Q000506" MajorTopicYN="Y">poisoning</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000882" MajorTopicYN="N">Haplorhini</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006801" MajorTopicYN="N">Humans</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D006863" MajorTopicYN="N">Hydrogen-Ion Concentration</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D007700" MajorTopicYN="N">Kinetics</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D000432" MajorTopicYN="N">Methanol</DescriptorName>
<QualifierName UI="Q000097" MajorTopicYN="N">blood</QualifierName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D008722" MajorTopicYN="N">Methods</DescriptorName>
</MeshHeading>
<MeshHeading>
<DescriptorName UI="D011549" MajorTopicYN="N">Pseudomonas</DescriptorName>
<QualifierName UI="Q000201" MajorTopicYN="N">enzymology</QualifierName>
</MeshHeading>
</MeshHeadingList>
</MedlineCitation>
<PubmedData>
<History>
<PubMedPubDate PubStatus="pubmed">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
</PubMedPubDate>
<PubMedPubDate PubStatus="medline">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>1</Minute>
</PubMedPubDate>
<PubMedPubDate PubStatus="entrez">
<Year>1975</Year>
<Month>6</Month>
<Day>1</Day>
<Hour>0</Hour>
<Minute>0</Minute>
</PubMedPubDate>
</History>
<PublicationStatus>ppublish</PublicationStatus>
<ArticleIdList>
<ArticleId IdType="pubmed">1</ArticleId>
<ArticleId IdType="doi">10.1016/0006-2944(75)90147-7</ArticleId>
</ArticleIdList>
</PubmedData>
</PubmedArticle>
'''
|
[
{
"context": "ndow.mockedCards = [\n {\n \"id\": 1\n \"name\": \"Cellar\"\n \"cost_in_text\": \"2\"\n \"cost_in_coins\": 2\n ",
"end": 121,
"score": 0.9992427825927734,
"start": 115,
"tag": "NAME",
"value": "Cellar"
},
{
"context": "esOneCard\"\n ]\n }\n {\n \"id... | spec/javascripts/spec_helper.coffee | jonkerz/kingscourt | 2 | #= require application
#= require angular-mocks/angular-mocks
window.mockedCards = [
{
"id": 1
"name": "Cellar"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "+1 Action<br />Discard any number of cards.<br />+1 Card per card discarded."
"card_attributes": [
"isAction"
"givesActions"
"givesOneCard"
]
}
{
"id": 2
"name": "Chapel"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "Trash up to 4 cards from your hand."
"card_attributes": [
"isAction"
"trasher"
"terminal"
]
}
]
| 43745 | #= require application
#= require angular-mocks/angular-mocks
window.mockedCards = [
{
"id": 1
"name": "<NAME>"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "+1 Action<br />Discard any number of cards.<br />+1 Card per card discarded."
"card_attributes": [
"isAction"
"givesActions"
"givesOneCard"
]
}
{
"id": 2
"name": "<NAME>"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "Trash up to 4 cards from your hand."
"card_attributes": [
"isAction"
"trasher"
"terminal"
]
}
]
| true | #= require application
#= require angular-mocks/angular-mocks
window.mockedCards = [
{
"id": 1
"name": "PI:NAME:<NAME>END_PI"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "+1 Action<br />Discard any number of cards.<br />+1 Card per card discarded."
"card_attributes": [
"isAction"
"givesActions"
"givesOneCard"
]
}
{
"id": 2
"name": "PI:NAME:<NAME>END_PI"
"cost_in_text": "2"
"cost_in_coins": 2
"text": "Trash up to 4 cards from your hand."
"card_attributes": [
"isAction"
"trasher"
"terminal"
]
}
]
|
[
{
"context": " Markdown Editor\n# Last Revised: April 23, 2015 by Ben Gotow\n#\n# Markdown editor is a simple React component t",
"end": 61,
"score": 0.9996638894081116,
"start": 52,
"tag": "NAME",
"value": "Ben Gotow"
}
] | packages/client-app/internal_packages/composer-markdown/lib/main.cjsx | cnheider/nylas-mail | 24,369 | # Markdown Editor
# Last Revised: April 23, 2015 by Ben Gotow
#
# Markdown editor is a simple React component that allows you to type your
# emails in markdown and see the live preview of your email in html
#
{ExtensionRegistry, ComponentRegistry} = require 'nylas-exports'
MarkdownEditor = require './markdown-editor'
MarkdownComposerExtension = require './markdown-composer-extension'
module.exports =
activate: ->
ComponentRegistry.register MarkdownEditor,
role: 'Composer:Editor'
ExtensionRegistry.Composer.register(MarkdownComposerExtension)
serialize: ->
deactivate: ->
ComponentRegistry.unregister(MarkdownEditor)
ExtensionRegistry.Composer.unregister(MarkdownComposerExtension)
| 126739 | # Markdown Editor
# Last Revised: April 23, 2015 by <NAME>
#
# Markdown editor is a simple React component that allows you to type your
# emails in markdown and see the live preview of your email in html
#
{ExtensionRegistry, ComponentRegistry} = require 'nylas-exports'
MarkdownEditor = require './markdown-editor'
MarkdownComposerExtension = require './markdown-composer-extension'
module.exports =
activate: ->
ComponentRegistry.register MarkdownEditor,
role: 'Composer:Editor'
ExtensionRegistry.Composer.register(MarkdownComposerExtension)
serialize: ->
deactivate: ->
ComponentRegistry.unregister(MarkdownEditor)
ExtensionRegistry.Composer.unregister(MarkdownComposerExtension)
| true | # Markdown Editor
# Last Revised: April 23, 2015 by PI:NAME:<NAME>END_PI
#
# Markdown editor is a simple React component that allows you to type your
# emails in markdown and see the live preview of your email in html
#
{ExtensionRegistry, ComponentRegistry} = require 'nylas-exports'
MarkdownEditor = require './markdown-editor'
MarkdownComposerExtension = require './markdown-composer-extension'
module.exports =
activate: ->
ComponentRegistry.register MarkdownEditor,
role: 'Composer:Editor'
ExtensionRegistry.Composer.register(MarkdownComposerExtension)
serialize: ->
deactivate: ->
ComponentRegistry.unregister(MarkdownEditor)
ExtensionRegistry.Composer.unregister(MarkdownComposerExtension)
|
[
{
"context": "tsearch(\n appId: 'AJCEDEJVN8'\n apiKey: 'a79a1de365422bb69ce8b0b1af128e43'\n indexName: 'spree_products_' + rails_env\n ",
"end": 514,
"score": 0.9997512698173523,
"start": 482,
"tag": "KEY",
"value": "a79a1de365422bb69ce8b0b1af128e43"
}
] | app/assets/javascripts/spree/frontend/spree_algolia_products.coffee | ThomasBush/spree_algolia_products | 1 | $(document).on 'ready page:load', ->
if $('#product-index-main').length > 0
rails_env = $('#product-index-main').data('rails-env')
current_industry = $('#product-index-main').data('current-industry')
search_parameters = {}
if current_industry.length > 0
search_parameters = {
facets: ['industries']
facetsRefinements:
industries: [ current_industry ]
}
search = instantsearch(
appId: 'AJCEDEJVN8'
apiKey: 'a79a1de365422bb69ce8b0b1af128e43'
indexName: 'spree_products_' + rails_env
searchParameters: search_parameters
urlSync: {
threshold: 300
getHistoryState: ->
{ turbolinks: true }
})
search.on 'render', ->
$('[data-toggle="tooltip"]').tooltip()
noResultsTemplate = '<div class="text-center">No results found matching <strong>{{query}}</strong>.</div>'
hitTemplate = '<div id="product_{{id}}" data-hook="products_list_item" itemscope="" itemtype="https://schema.org/Product" class="col-lg-3 col-md-4 col-sm-6 product-list-item"><div class="panel panel-default"><div class="panel-body text-center product-body"><a itemprop="url" href="https://www.safetygloves.com{{url}}"><img itemprop="image" alt="{{name}}" src="{{image}}"></a><a class="info" itemprop="name" title="{{name}}" href="https://www.safetygloves.com{{url}}">{{name}}</a></div><div class="panel-footer text-center"><span itemprop="offers" itemscope="" itemtype="https://schema.org/Offer"><span class="price selling lead" itemprop="price">${{price}}</span></span></div></div></div>'
facetTemplateCheckbox = '<li class="facet_item {{#isRefined}}refined{{/isRefined}}"><input class="checkbox toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" type="checkbox" {{#isRefined}}checked{{/isRefined}}><a class="facet_link toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" href="#">{{ name }}</a><small class="facet_count text-muted pull-right">{{ count }}</small></li>'
search.addWidget instantsearch.widgets.searchBox(
container: '#q'
placeholder: 'Search Products...')
search.addWidget instantsearch.widgets.hits(
container: '#hits'
hitsPerPage: 24
templates:
empty: noResultsTemplate
item: hitTemplate)
search.addWidget instantsearch.widgets.pagination(
container: '#pagination-wrap'
cssClasses:
root: 'pagination'
active: 'active'
labels:
previous: '<i class="fa fa-angle-double-left" aria-hidden="true"></i> Prev'
next: 'Next <i class="fa fa-angle-double-right" aria-hidden="true"></i>'
showFirstLast: false
autoHideContainer: true)
search.addWidget instantsearch.widgets.clearAll(
container: '#clear-all'
excludeAttributes: 'industries'
templates:
link: 'Clear all filters <i class="fa fa-times" aria-hidden="true"></i>'
cssClasses:
link: 'btn btn-block btn-default clear-all-link'
autoHideContainer: true)
search.addWidget instantsearch.widgets.refinementList(
container: '#product_type'
attributeName: 'product_type'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Product Type<i class="fa fa-plus fa-minus"></i></h3>'
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: false
)
search.addWidget instantsearch.widgets.refinementList(
container: '#size'
attributeName: 'size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Size<i class="fa fa-plus"></i></h3>'
sortBy: ['count:desc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#yuleys_size'
attributeName: 'yuleys_size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Footwear Size<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#color'
attributeName: 'color'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Color<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#tint'
attributeName: 'tint'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Tint<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#lens_coating'
attributeName: 'lens_coating'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Coating<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.currentRefinedValues(
container: '#current-refined-values'
attributes: [{name: 'product_type'}, {name: 'size'}, {name: 'yuleys_size'}, {name: 'color'}, {name: 'tint'}, {name: 'lens_coating'}]
onlyListedAttributes: true
clearAll: false
templates:
item: '<li>{{ name }}<i class="fa fa-times pull-right" aria-hidden="true"></i></li>'
header: '<h3>Currently Selected</h3>'
autoHideContainer: true)
search.addWidget instantsearch.widgets.hitsPerPageSelector(
container: '#hits-per-page-selector'
cssClasses:
root: 'form-control'
options: [
{
value: 12
label: '12 Products'
}
{
value: 24
label: '24 Products'
}
{
value: 48
label: '48 Products'
}
{
value: 1000
label: 'All Products'
}
])
search.start()
$(document).on 'click', '.facet-wrapper .list-unstyled', (e) ->
this_panel = $(this).find('.panel-root')
if this_panel.hasClass('ais-root__collapsed')
this_panel.removeClass('ais-root__collapsed').find('.panel-title i').addClass('fa-minus')
else
this_panel.find('.panel-title i').removeClass('fa-minus')
$(document).on 'click', '#products.index .tint-square', (e) ->
e.preventDefault()
clicked_link = $(this)
container_item = clicked_link.closest('.search-result-item')
src = clicked_link.data('url')
if src != undefined
tint_img_wrap = container_item.find('.product-thumb')
list = container_item.find('span.active').removeClass('active')
clicked_link.addClass('active')
tint_img_wrap.fadeOut 'fast', ->
tint_img_wrap.empty().append '<img src="' + src + '" alt="">'
tint_img_wrap.fadeIn 'fast'
return
| 70864 | $(document).on 'ready page:load', ->
if $('#product-index-main').length > 0
rails_env = $('#product-index-main').data('rails-env')
current_industry = $('#product-index-main').data('current-industry')
search_parameters = {}
if current_industry.length > 0
search_parameters = {
facets: ['industries']
facetsRefinements:
industries: [ current_industry ]
}
search = instantsearch(
appId: 'AJCEDEJVN8'
apiKey: '<KEY>'
indexName: 'spree_products_' + rails_env
searchParameters: search_parameters
urlSync: {
threshold: 300
getHistoryState: ->
{ turbolinks: true }
})
search.on 'render', ->
$('[data-toggle="tooltip"]').tooltip()
noResultsTemplate = '<div class="text-center">No results found matching <strong>{{query}}</strong>.</div>'
hitTemplate = '<div id="product_{{id}}" data-hook="products_list_item" itemscope="" itemtype="https://schema.org/Product" class="col-lg-3 col-md-4 col-sm-6 product-list-item"><div class="panel panel-default"><div class="panel-body text-center product-body"><a itemprop="url" href="https://www.safetygloves.com{{url}}"><img itemprop="image" alt="{{name}}" src="{{image}}"></a><a class="info" itemprop="name" title="{{name}}" href="https://www.safetygloves.com{{url}}">{{name}}</a></div><div class="panel-footer text-center"><span itemprop="offers" itemscope="" itemtype="https://schema.org/Offer"><span class="price selling lead" itemprop="price">${{price}}</span></span></div></div></div>'
facetTemplateCheckbox = '<li class="facet_item {{#isRefined}}refined{{/isRefined}}"><input class="checkbox toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" type="checkbox" {{#isRefined}}checked{{/isRefined}}><a class="facet_link toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" href="#">{{ name }}</a><small class="facet_count text-muted pull-right">{{ count }}</small></li>'
search.addWidget instantsearch.widgets.searchBox(
container: '#q'
placeholder: 'Search Products...')
search.addWidget instantsearch.widgets.hits(
container: '#hits'
hitsPerPage: 24
templates:
empty: noResultsTemplate
item: hitTemplate)
search.addWidget instantsearch.widgets.pagination(
container: '#pagination-wrap'
cssClasses:
root: 'pagination'
active: 'active'
labels:
previous: '<i class="fa fa-angle-double-left" aria-hidden="true"></i> Prev'
next: 'Next <i class="fa fa-angle-double-right" aria-hidden="true"></i>'
showFirstLast: false
autoHideContainer: true)
search.addWidget instantsearch.widgets.clearAll(
container: '#clear-all'
excludeAttributes: 'industries'
templates:
link: 'Clear all filters <i class="fa fa-times" aria-hidden="true"></i>'
cssClasses:
link: 'btn btn-block btn-default clear-all-link'
autoHideContainer: true)
search.addWidget instantsearch.widgets.refinementList(
container: '#product_type'
attributeName: 'product_type'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Product Type<i class="fa fa-plus fa-minus"></i></h3>'
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: false
)
search.addWidget instantsearch.widgets.refinementList(
container: '#size'
attributeName: 'size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Size<i class="fa fa-plus"></i></h3>'
sortBy: ['count:desc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#yuleys_size'
attributeName: 'yuleys_size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Footwear Size<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#color'
attributeName: 'color'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Color<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#tint'
attributeName: 'tint'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Tint<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#lens_coating'
attributeName: 'lens_coating'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Coating<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.currentRefinedValues(
container: '#current-refined-values'
attributes: [{name: 'product_type'}, {name: 'size'}, {name: 'yuleys_size'}, {name: 'color'}, {name: 'tint'}, {name: 'lens_coating'}]
onlyListedAttributes: true
clearAll: false
templates:
item: '<li>{{ name }}<i class="fa fa-times pull-right" aria-hidden="true"></i></li>'
header: '<h3>Currently Selected</h3>'
autoHideContainer: true)
search.addWidget instantsearch.widgets.hitsPerPageSelector(
container: '#hits-per-page-selector'
cssClasses:
root: 'form-control'
options: [
{
value: 12
label: '12 Products'
}
{
value: 24
label: '24 Products'
}
{
value: 48
label: '48 Products'
}
{
value: 1000
label: 'All Products'
}
])
search.start()
$(document).on 'click', '.facet-wrapper .list-unstyled', (e) ->
this_panel = $(this).find('.panel-root')
if this_panel.hasClass('ais-root__collapsed')
this_panel.removeClass('ais-root__collapsed').find('.panel-title i').addClass('fa-minus')
else
this_panel.find('.panel-title i').removeClass('fa-minus')
$(document).on 'click', '#products.index .tint-square', (e) ->
e.preventDefault()
clicked_link = $(this)
container_item = clicked_link.closest('.search-result-item')
src = clicked_link.data('url')
if src != undefined
tint_img_wrap = container_item.find('.product-thumb')
list = container_item.find('span.active').removeClass('active')
clicked_link.addClass('active')
tint_img_wrap.fadeOut 'fast', ->
tint_img_wrap.empty().append '<img src="' + src + '" alt="">'
tint_img_wrap.fadeIn 'fast'
return
| true | $(document).on 'ready page:load', ->
if $('#product-index-main').length > 0
rails_env = $('#product-index-main').data('rails-env')
current_industry = $('#product-index-main').data('current-industry')
search_parameters = {}
if current_industry.length > 0
search_parameters = {
facets: ['industries']
facetsRefinements:
industries: [ current_industry ]
}
search = instantsearch(
appId: 'AJCEDEJVN8'
apiKey: 'PI:KEY:<KEY>END_PI'
indexName: 'spree_products_' + rails_env
searchParameters: search_parameters
urlSync: {
threshold: 300
getHistoryState: ->
{ turbolinks: true }
})
search.on 'render', ->
$('[data-toggle="tooltip"]').tooltip()
noResultsTemplate = '<div class="text-center">No results found matching <strong>{{query}}</strong>.</div>'
hitTemplate = '<div id="product_{{id}}" data-hook="products_list_item" itemscope="" itemtype="https://schema.org/Product" class="col-lg-3 col-md-4 col-sm-6 product-list-item"><div class="panel panel-default"><div class="panel-body text-center product-body"><a itemprop="url" href="https://www.safetygloves.com{{url}}"><img itemprop="image" alt="{{name}}" src="{{image}}"></a><a class="info" itemprop="name" title="{{name}}" href="https://www.safetygloves.com{{url}}">{{name}}</a></div><div class="panel-footer text-center"><span itemprop="offers" itemscope="" itemtype="https://schema.org/Offer"><span class="price selling lead" itemprop="price">${{price}}</span></span></div></div></div>'
facetTemplateCheckbox = '<li class="facet_item {{#isRefined}}refined{{/isRefined}}"><input class="checkbox toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" type="checkbox" {{#isRefined}}checked{{/isRefined}}><a class="facet_link toggleRefine" data-facet="{{ facet }}" data-value="{{ name }}" href="#">{{ name }}</a><small class="facet_count text-muted pull-right">{{ count }}</small></li>'
search.addWidget instantsearch.widgets.searchBox(
container: '#q'
placeholder: 'Search Products...')
search.addWidget instantsearch.widgets.hits(
container: '#hits'
hitsPerPage: 24
templates:
empty: noResultsTemplate
item: hitTemplate)
search.addWidget instantsearch.widgets.pagination(
container: '#pagination-wrap'
cssClasses:
root: 'pagination'
active: 'active'
labels:
previous: '<i class="fa fa-angle-double-left" aria-hidden="true"></i> Prev'
next: 'Next <i class="fa fa-angle-double-right" aria-hidden="true"></i>'
showFirstLast: false
autoHideContainer: true)
search.addWidget instantsearch.widgets.clearAll(
container: '#clear-all'
excludeAttributes: 'industries'
templates:
link: 'Clear all filters <i class="fa fa-times" aria-hidden="true"></i>'
cssClasses:
link: 'btn btn-block btn-default clear-all-link'
autoHideContainer: true)
search.addWidget instantsearch.widgets.refinementList(
container: '#product_type'
attributeName: 'product_type'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Product Type<i class="fa fa-plus fa-minus"></i></h3>'
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: false
)
search.addWidget instantsearch.widgets.refinementList(
container: '#size'
attributeName: 'size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Size<i class="fa fa-plus"></i></h3>'
sortBy: ['count:desc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#yuleys_size'
attributeName: 'yuleys_size'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Footwear Size<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#color'
attributeName: 'color'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Color<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#tint'
attributeName: 'tint'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Tint<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.refinementList(
container: '#lens_coating'
attributeName: 'lens_coating'
operator: 'and'
limit: 10
templates:
item: facetTemplateCheckbox
header: '<h3 class="panel-title">Eyewear Coating<i class="fa fa-plus"></i></h3>'
sortBy: ['name:asc']
autoHideContainer: true
cssClasses:
root: "panel-root"
body: "panel-body"
collapsible:
collapsed: true
)
search.addWidget instantsearch.widgets.currentRefinedValues(
container: '#current-refined-values'
attributes: [{name: 'product_type'}, {name: 'size'}, {name: 'yuleys_size'}, {name: 'color'}, {name: 'tint'}, {name: 'lens_coating'}]
onlyListedAttributes: true
clearAll: false
templates:
item: '<li>{{ name }}<i class="fa fa-times pull-right" aria-hidden="true"></i></li>'
header: '<h3>Currently Selected</h3>'
autoHideContainer: true)
search.addWidget instantsearch.widgets.hitsPerPageSelector(
container: '#hits-per-page-selector'
cssClasses:
root: 'form-control'
options: [
{
value: 12
label: '12 Products'
}
{
value: 24
label: '24 Products'
}
{
value: 48
label: '48 Products'
}
{
value: 1000
label: 'All Products'
}
])
search.start()
$(document).on 'click', '.facet-wrapper .list-unstyled', (e) ->
this_panel = $(this).find('.panel-root')
if this_panel.hasClass('ais-root__collapsed')
this_panel.removeClass('ais-root__collapsed').find('.panel-title i').addClass('fa-minus')
else
this_panel.find('.panel-title i').removeClass('fa-minus')
$(document).on 'click', '#products.index .tint-square', (e) ->
e.preventDefault()
clicked_link = $(this)
container_item = clicked_link.closest('.search-result-item')
src = clicked_link.data('url')
if src != undefined
tint_img_wrap = container_item.find('.product-thumb')
list = container_item.find('span.active').removeClass('active')
clicked_link.addClass('active')
tint_img_wrap.fadeOut 'fast', ->
tint_img_wrap.empty().append '<img src="' + src + '" alt="">'
tint_img_wrap.fadeIn 'fast'
return
|
[
{
"context": "File: (funcOpts={}) ->\n\t\tfuncOpts.mainKeyName ?= \"指标名称\"\n\t\tjson = JSONUtils.getJSON(funcOpts)\n\t\tindicator",
"end": 1509,
"score": 0.9183341860771179,
"start": 1505,
"tag": "KEY",
"value": "指标名称"
},
{
"context": " k, obj of mannual\n\t\t\t\tkey = @fixedKey k.re... | analyze/indicatorDef.coffee | Tostig0916/hqcoffee | 2 | {JSONUtils} = require './jsonUtils'
#fs = require 'fs'
#path = require 'path'
#pptxgen = require 'pptxgenjs'
#xlsx = require 'json-as-xlsx'
class IndicatorDefCategory
constructor: (funcOpts={}) ->
{@name} = funcOpts
@subs = []
addInfo: (funcOpts={}) ->
{subName} = funcOpts
@subs.push(subName) unless subName in @subs
description: ->
"#{@name},#{@subs.join(",")}"
class IndicatorDefVersion
constructor: (funcOpts={})->
{@versionName} = funcOpts
@categoryOne = {} #{name, category}
@categoryTwo = {}
addInfo: (funcOpts={}) ->
{indicatorKey,一级指标,二级指标} = funcOpts
@categoryOne[一级指标] ?= new IndicatorDefCategory({name: 一级指标})
@categoryTwo[二级指标] ?= new IndicatorDefCategory({name: 二级指标})
@categoryOne[一级指标].addInfo({subName:二级指标})
@categoryTwo[二级指标].addInfo({subName:indicatorKey})
class IndicatorDefInfoByVersion
# 无法直接加class properties,只能这样曲折设置
@addVersion: (funcOpts={}) ->
@versions ?= {}
{versionName} = funcOpts
@versions[versionName] ?= new IndicatorDefVersion(funcOpts)
@versions[versionName].addInfo(funcOpts)
@versionArray: ->
(each for key, each of @versions)
@versionCount: ->
(v for k,v of @versions).length
constructor: (funcOpts={}) ->
# 此处为可因版本而异的属性,
# 其中 评是指定量指标中,要求逐步提高或降低的指标,理论上说,这项属性应该是各版本一致的,如此设计是为防止万一
{@versionName,@indicatorKey,@序号, @计量单位, @二级指标, @一级指标, @测, @评} = funcOpts
@constructor.addVersion(this)
class IndicatorDef
@fromMannualFile: (funcOpts={}) ->
funcOpts.mainKeyName ?= "指标名称"
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for versionName, mannual of json
for k, obj of mannual
key = @fixedKey k.replace('▲','')
obj.key = key
indicators[key] ?= new this(obj)
indicators[key][versionName] = true
if obj.一级指标?
indicators[key].一级指标 ?= obj.一级指标
if obj.二级指标?
indicators[key].二级指标 ?= obj.二级指标
indicators[key]["#{versionName}监测"] = /▲$/.test(obj.指标名称)
indicators[key].versions.push(new IndicatorDefInfoByVersion({
versionName
indicatorKey: key
序号: obj.序号
二级指标: obj.二级指标
一级指标: obj.一级指标
计量单位: obj.计量单位
测: /▲$/.test(obj.指标名称)
评: /(降低|提高)/.test(obj.指标导向)
}))
# console.log key, obj
# json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成
{folder,basename,needToRewrite} = funcOpts
{data, settings} = @dataSettings4Excel({arr:(v for k, v of indicators)})
JSONUtils.write2Excel({folder,outfolder:'outputs',basename:"#{basename}Analyze", needToRewrite, data, settings})
JSONUtils.write2JSON({folder,basename:"#{basename}Dict", needToRewrite, obj:indicators})
JSONUtils.write2JSON({folder,basename:"#{basename}Versions", needToRewrite, obj: IndicatorDefInfoByVersion.versions})
return indicators
@fixedKey: (k)->
switch
when k in ["人员经费占比","人员支出占业务支出比重"]
"人员经费占比(人员支出占业务支出比重)"
when k in ["万元收入能耗占比","万元收入能耗支出"]
"万元收入能耗占比(~能耗支出)"
when k in ["国家组织药品集中采购中标药品金额占比","国家组织药品集中采购中标药品使用比例"]
"国家组织药品集中采购中标药品金额占比(~药品使用比例)"
when k in ["医疗盈余率","收支结余"]
"医疗盈余率(收支结余)"
else k
# 用于整合多个国考指标定义合并成为一个Excel文件
@dataSettings4Excel: (funcOpts={}) ->
{arr} = funcOpts
data = [
{
sheet: '国考指标体系'
columns: [
{
label:'指标名称', value: ({指标名称,key,矢量,指标导向}) ->
key1 = if 矢量 then "#{指标导向[4]}#{key}" else key
if /▲$/.test(指标名称) then key1 + '▲' else key1
}
{label:'二级指标', value: '二级指标'}
{label:'一级指标', value: '一级指标'}
{label:'指标来源', value: '指标来源'}
{label:'三级中医', value: ({三级中医监测,三级中医}) -> if 三级中医监测 then '监' else if 三级中医 then '考' else '无'}
{label:'三级综合', value: ({三级综合监测,三级综合}) -> if 三级综合监测 then '监' else if 三级综合 then '考' else '无'}
{label:'二级综合', value: ({二级综合监测,二级综合}) -> if 二级综合监测 then '监' else if 二级综合 then '考' else '无'}
{label:'计量单位', value: '计量单位'}
#{label:'指标名称', value:'指标名称'}
#{label:'指标属性', value: '指标属性'}
#{label:'指标导向', value: '指标导向'}
#{label:'矢量', value: ({矢量}) -> if 矢量 then '监' else '无'}
#{label:'三级综合', value: ({三级综合}) -> if 三级综合 then '监' else '无'}
#{label:'三级中医', value: ({三级中医}) -> if 三级中医 then '监' else '无'}
#{label:'二级综合', value: ({二级综合}) -> if 二级综合 then '监' else '无'}
]
content: arr
}
]
settings = {
extraLength: 3
writeOptions: {}
}
{data, settings}
###
# 各版本独立陈列,备考
@seperatedFromMannualFile: (funcOpts={}) ->
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for version, mannual of json
indicators[version] = {}
for key, obj of mannual
instance = new this(obj)
indicators[version][key] = instance
# console.log key, obj
return indicators
###
constructor: (funcOpts={}) ->
# 以下指标在不同的版本中都是一致的,否则应该放在 IndicatorDefInfoByVersion
{@key, @指标名称, @指标来源='', @指标属性='', @计量单位, @指标导向} = funcOpts
@矢量 = /(降低|提高)/.test(@指标导向)
@一级指标 = @二级指标 = null
@三级综合 = @二级综合 = @三级中医 = @三级综合监测 = @二级综合监测 = @三级中医监测 = false
@versions = []
isValuable: ->
/(降低|提高)/.test(@指标导向)
description: ->
arr = ("版本:#{each.versionName}, 序号:#{each.序号}, 监测:#{each.测}" for each in @versions)
return "指标:#{@指标名称}, 矢量:#{@isValuable()}, #{arr}"
module.exports = {
IndicatorDef
IndicatorDefInfoByVersion
}
| 77582 | {JSONUtils} = require './jsonUtils'
#fs = require 'fs'
#path = require 'path'
#pptxgen = require 'pptxgenjs'
#xlsx = require 'json-as-xlsx'
class IndicatorDefCategory
constructor: (funcOpts={}) ->
{@name} = funcOpts
@subs = []
addInfo: (funcOpts={}) ->
{subName} = funcOpts
@subs.push(subName) unless subName in @subs
description: ->
"#{@name},#{@subs.join(",")}"
class IndicatorDefVersion
constructor: (funcOpts={})->
{@versionName} = funcOpts
@categoryOne = {} #{name, category}
@categoryTwo = {}
addInfo: (funcOpts={}) ->
{indicatorKey,一级指标,二级指标} = funcOpts
@categoryOne[一级指标] ?= new IndicatorDefCategory({name: 一级指标})
@categoryTwo[二级指标] ?= new IndicatorDefCategory({name: 二级指标})
@categoryOne[一级指标].addInfo({subName:二级指标})
@categoryTwo[二级指标].addInfo({subName:indicatorKey})
class IndicatorDefInfoByVersion
# 无法直接加class properties,只能这样曲折设置
@addVersion: (funcOpts={}) ->
@versions ?= {}
{versionName} = funcOpts
@versions[versionName] ?= new IndicatorDefVersion(funcOpts)
@versions[versionName].addInfo(funcOpts)
@versionArray: ->
(each for key, each of @versions)
@versionCount: ->
(v for k,v of @versions).length
constructor: (funcOpts={}) ->
# 此处为可因版本而异的属性,
# 其中 评是指定量指标中,要求逐步提高或降低的指标,理论上说,这项属性应该是各版本一致的,如此设计是为防止万一
{@versionName,@indicatorKey,@序号, @计量单位, @二级指标, @一级指标, @测, @评} = funcOpts
@constructor.addVersion(this)
class IndicatorDef
@fromMannualFile: (funcOpts={}) ->
funcOpts.mainKeyName ?= "<KEY>"
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for versionName, mannual of json
for k, obj of mannual
key = @fixedKey k.replace('<KEY>','')
obj.key = key
indicators[key] ?= new this(obj)
indicators[key][versionName] = true
if obj.一级指标?
indicators[key].一级指标 ?= obj.一级指标
if obj.二级指标?
indicators[key].二级指标 ?= obj.二级指标
indicators[key]["#{versionName}监测"] = /▲$/.test(obj.指标名称)
indicators[key].versions.push(new IndicatorDefInfoByVersion({
versionName
indicatorKey: key
序号: obj.序号
二级指标: obj.二级指标
一级指标: obj.一级指标
计量单位: obj.计量单位
测: /▲$/.test(obj.指标名称)
评: /(降低|提高)/.test(obj.指标导向)
}))
# console.log key, obj
# json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成
{folder,basename,needToRewrite} = funcOpts
{data, settings} = @dataSettings4Excel({arr:(v for k, v of indicators)})
JSONUtils.write2Excel({folder,outfolder:'outputs',basename:"#{basename}Analyze", needToRewrite, data, settings})
JSONUtils.write2JSON({folder,basename:"#{basename}Dict", needToRewrite, obj:indicators})
JSONUtils.write2JSON({folder,basename:"#{basename}Versions", needToRewrite, obj: IndicatorDefInfoByVersion.versions})
return indicators
@fixedKey: (k)->
switch
when k in ["人员经费占比","人员支出占业务支出比重"]
"人员经费占比(人员支出占业务支出比重)"
when k in ["万元收入能耗占比","万元收入能耗支出"]
"万元收入能耗占比(~能耗支出)"
when k in ["国家组织药品集中采购中标药品金额占比","国家组织药品集中采购中标药品使用比例"]
"国家组织药品集中采购中标药品金额占比(~药品使用比例)"
when k in ["医疗盈余率","收支结余"]
"医疗盈余率(收支结余)"
else k
# 用于整合多个国考指标定义合并成为一个Excel文件
@dataSettings4Excel: (funcOpts={}) ->
{arr} = funcOpts
data = [
{
sheet: '国考指标体系'
columns: [
{
label:'指标名称', value: ({指标名称,key,矢量,指标导向}) ->
key1 = if 矢量 then "#{指标导向[4]}#{key}" else key
if /▲$/.test(指标名称) then key1 + '▲' else key1
}
{label:'二级指标', value: '二级指标'}
{label:'一级指标', value: '一级指标'}
{label:'指标来源', value: '指标来源'}
{label:'三级中医', value: ({三级中医监测,三级中医}) -> if 三级中医监测 then '监' else if 三级中医 then '考' else '无'}
{label:'三级综合', value: ({三级综合监测,三级综合}) -> if 三级综合监测 then '监' else if 三级综合 then '考' else '无'}
{label:'二级综合', value: ({二级综合监测,二级综合}) -> if 二级综合监测 then '监' else if 二级综合 then '考' else '无'}
{label:'计量单位', value: '计量单位'}
#{label:'指标名称', value:'指标名称'}
#{label:'指标属性', value: '指标属性'}
#{label:'指标导向', value: '指标导向'}
#{label:'矢量', value: ({矢量}) -> if 矢量 then '监' else '无'}
#{label:'三级综合', value: ({三级综合}) -> if 三级综合 then '监' else '无'}
#{label:'三级中医', value: ({三级中医}) -> if 三级中医 then '监' else '无'}
#{label:'二级综合', value: ({二级综合}) -> if 二级综合 then '监' else '无'}
]
content: arr
}
]
settings = {
extraLength: 3
writeOptions: {}
}
{data, settings}
###
# 各版本独立陈列,备考
@seperatedFromMannualFile: (funcOpts={}) ->
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for version, mannual of json
indicators[version] = {}
for key, obj of mannual
instance = new this(obj)
indicators[version][key] = instance
# console.log key, obj
return indicators
###
constructor: (funcOpts={}) ->
# 以下指标在不同的版本中都是一致的,否则应该放在 IndicatorDefInfoByVersion
{@key, @指标名称, @指标来源='', @指标属性='', @计量单位, @指标导向} = funcOpts
@矢量 = /(降低|提高)/.test(@指标导向)
@一级指标 = @二级指标 = null
@三级综合 = @二级综合 = @三级中医 = @三级综合监测 = @二级综合监测 = @三级中医监测 = false
@versions = []
isValuable: ->
/(降低|提高)/.test(@指标导向)
description: ->
arr = ("版本:#{each.versionName}, 序号:#{each.序号}, 监测:#{each.测}" for each in @versions)
return "指标:#{@指标名称}, 矢量:#{@isValuable()}, #{arr}"
module.exports = {
IndicatorDef
IndicatorDefInfoByVersion
}
| true | {JSONUtils} = require './jsonUtils'
#fs = require 'fs'
#path = require 'path'
#pptxgen = require 'pptxgenjs'
#xlsx = require 'json-as-xlsx'
class IndicatorDefCategory
constructor: (funcOpts={}) ->
{@name} = funcOpts
@subs = []
addInfo: (funcOpts={}) ->
{subName} = funcOpts
@subs.push(subName) unless subName in @subs
description: ->
"#{@name},#{@subs.join(",")}"
class IndicatorDefVersion
constructor: (funcOpts={})->
{@versionName} = funcOpts
@categoryOne = {} #{name, category}
@categoryTwo = {}
addInfo: (funcOpts={}) ->
{indicatorKey,一级指标,二级指标} = funcOpts
@categoryOne[一级指标] ?= new IndicatorDefCategory({name: 一级指标})
@categoryTwo[二级指标] ?= new IndicatorDefCategory({name: 二级指标})
@categoryOne[一级指标].addInfo({subName:二级指标})
@categoryTwo[二级指标].addInfo({subName:indicatorKey})
class IndicatorDefInfoByVersion
# 无法直接加class properties,只能这样曲折设置
@addVersion: (funcOpts={}) ->
@versions ?= {}
{versionName} = funcOpts
@versions[versionName] ?= new IndicatorDefVersion(funcOpts)
@versions[versionName].addInfo(funcOpts)
@versionArray: ->
(each for key, each of @versions)
@versionCount: ->
(v for k,v of @versions).length
constructor: (funcOpts={}) ->
# 此处为可因版本而异的属性,
# 其中 评是指定量指标中,要求逐步提高或降低的指标,理论上说,这项属性应该是各版本一致的,如此设计是为防止万一
{@versionName,@indicatorKey,@序号, @计量单位, @二级指标, @一级指标, @测, @评} = funcOpts
@constructor.addVersion(this)
class IndicatorDef
@fromMannualFile: (funcOpts={}) ->
funcOpts.mainKeyName ?= "PI:KEY:<KEY>END_PI"
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for versionName, mannual of json
for k, obj of mannual
key = @fixedKey k.replace('PI:KEY:<KEY>END_PI','')
obj.key = key
indicators[key] ?= new this(obj)
indicators[key][versionName] = true
if obj.一级指标?
indicators[key].一级指标 ?= obj.一级指标
if obj.二级指标?
indicators[key].二级指标 ?= obj.二级指标
indicators[key]["#{versionName}监测"] = /▲$/.test(obj.指标名称)
indicators[key].versions.push(new IndicatorDefInfoByVersion({
versionName
indicatorKey: key
序号: obj.序号
二级指标: obj.二级指标
一级指标: obj.一级指标
计量单位: obj.计量单位
测: /▲$/.test(obj.指标名称)
评: /(降低|提高)/.test(obj.指标导向)
}))
# console.log key, obj
# json 只是用来查看和纠错的, instance objects 则应每次从原始文件生成
{folder,basename,needToRewrite} = funcOpts
{data, settings} = @dataSettings4Excel({arr:(v for k, v of indicators)})
JSONUtils.write2Excel({folder,outfolder:'outputs',basename:"#{basename}Analyze", needToRewrite, data, settings})
JSONUtils.write2JSON({folder,basename:"#{basename}Dict", needToRewrite, obj:indicators})
JSONUtils.write2JSON({folder,basename:"#{basename}Versions", needToRewrite, obj: IndicatorDefInfoByVersion.versions})
return indicators
@fixedKey: (k)->
switch
when k in ["人员经费占比","人员支出占业务支出比重"]
"人员经费占比(人员支出占业务支出比重)"
when k in ["万元收入能耗占比","万元收入能耗支出"]
"万元收入能耗占比(~能耗支出)"
when k in ["国家组织药品集中采购中标药品金额占比","国家组织药品集中采购中标药品使用比例"]
"国家组织药品集中采购中标药品金额占比(~药品使用比例)"
when k in ["医疗盈余率","收支结余"]
"医疗盈余率(收支结余)"
else k
# 用于整合多个国考指标定义合并成为一个Excel文件
@dataSettings4Excel: (funcOpts={}) ->
{arr} = funcOpts
data = [
{
sheet: '国考指标体系'
columns: [
{
label:'指标名称', value: ({指标名称,key,矢量,指标导向}) ->
key1 = if 矢量 then "#{指标导向[4]}#{key}" else key
if /▲$/.test(指标名称) then key1 + '▲' else key1
}
{label:'二级指标', value: '二级指标'}
{label:'一级指标', value: '一级指标'}
{label:'指标来源', value: '指标来源'}
{label:'三级中医', value: ({三级中医监测,三级中医}) -> if 三级中医监测 then '监' else if 三级中医 then '考' else '无'}
{label:'三级综合', value: ({三级综合监测,三级综合}) -> if 三级综合监测 then '监' else if 三级综合 then '考' else '无'}
{label:'二级综合', value: ({二级综合监测,二级综合}) -> if 二级综合监测 then '监' else if 二级综合 then '考' else '无'}
{label:'计量单位', value: '计量单位'}
#{label:'指标名称', value:'指标名称'}
#{label:'指标属性', value: '指标属性'}
#{label:'指标导向', value: '指标导向'}
#{label:'矢量', value: ({矢量}) -> if 矢量 then '监' else '无'}
#{label:'三级综合', value: ({三级综合}) -> if 三级综合 then '监' else '无'}
#{label:'三级中医', value: ({三级中医}) -> if 三级中医 then '监' else '无'}
#{label:'二级综合', value: ({二级综合}) -> if 二级综合 then '监' else '无'}
]
content: arr
}
]
settings = {
extraLength: 3
writeOptions: {}
}
{data, settings}
###
# 各版本独立陈列,备考
@seperatedFromMannualFile: (funcOpts={}) ->
json = JSONUtils.getJSON(funcOpts)
indicators = {}
for version, mannual of json
indicators[version] = {}
for key, obj of mannual
instance = new this(obj)
indicators[version][key] = instance
# console.log key, obj
return indicators
###
constructor: (funcOpts={}) ->
# 以下指标在不同的版本中都是一致的,否则应该放在 IndicatorDefInfoByVersion
{@key, @指标名称, @指标来源='', @指标属性='', @计量单位, @指标导向} = funcOpts
@矢量 = /(降低|提高)/.test(@指标导向)
@一级指标 = @二级指标 = null
@三级综合 = @二级综合 = @三级中医 = @三级综合监测 = @二级综合监测 = @三级中医监测 = false
@versions = []
isValuable: ->
/(降低|提高)/.test(@指标导向)
description: ->
arr = ("版本:#{each.versionName}, 序号:#{each.序号}, 监测:#{each.测}" for each in @versions)
return "指标:#{@指标名称}, 矢量:#{@isValuable()}, #{arr}"
module.exports = {
IndicatorDef
IndicatorDefInfoByVersion
}
|
[
{
"context": "d to parentWidget\n setting = {}\n setting.key = \"organizations\"\n setting.isInitialized = false\n\n # initializat",
"end": 1010,
"score": 0.9922223687171936,
"start": 997,
"tag": "KEY",
"value": "organizations"
}
] | src/components/widgets-settings/organizations/organizations.directive.coffee | maestrano/impac-angular | 7 | module = angular.module('impac.components.widgets-settings.organizations',[])
module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc, ImpacMainSvc, ImpacWidgetsSvc) ->
w = $scope.parentWidget
w.selectedOrganizations = {}
$scope.mode ||= 'multiple'
$scope.multiOrgMode = -> $scope.mode == 'multiple'
$scope.singleOrgMode = -> $scope.mode == 'single'
resetSelectedOrgs = -> w.selectedOrganizations = _.mapValues(w.selectedOrganizations, -> false)
$scope.isOrganizationSelected = (orgUid) ->
!!w.selectedOrganizations[orgUid]
$scope.toggleSelectOrganization = (orgUid) ->
if $scope.multiOrgMode()
w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid]
$scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect )
else if $scope.singleOrgMode()
resetSelectedOrgs()
w.selectedOrganizations[orgUid] = true
# What will be passed to parentWidget
setting = {}
setting.key = "organizations"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.dashboardOrganizations = _.sortBy(currentDashboard.data_sources, (org) -> org.label.toLowerCase())
return unless w.metadata? && w.metadata.organization_ids?
widgetOrgIds = w.metadata.organization_ids
if $scope.singleOrgMode()
resetSelectedOrgs()
if widgetOrgIds.length > 1
currentOrganization = ImpacMainSvc.config.currentOrganization
w.selectedOrganizations[currentOrganization.uid] = true
forceReload = true
else
w.selectedOrganizations[widgetOrgIds[0]] = true
else if $scope.multiOrgMode()
for org in $scope.dashboardOrganizations
w.selectedOrganizations[org.uid] = _.contains(widgetOrgIds, org.uid)
setting.isInitialized = true
ImpacWidgetsSvc.updateWidgetSettings(w, true) if forceReload
)
setting.toMetadata = ->
newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) ->
uid if checked
))
newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations)
return { organization_ids: newOrganizations }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingOrganizations', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/organizations.tmpl.html'),
controller: 'SettingOrganizationsCtrl'
}
)
| 81727 | module = angular.module('impac.components.widgets-settings.organizations',[])
module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc, ImpacMainSvc, ImpacWidgetsSvc) ->
w = $scope.parentWidget
w.selectedOrganizations = {}
$scope.mode ||= 'multiple'
$scope.multiOrgMode = -> $scope.mode == 'multiple'
$scope.singleOrgMode = -> $scope.mode == 'single'
resetSelectedOrgs = -> w.selectedOrganizations = _.mapValues(w.selectedOrganizations, -> false)
$scope.isOrganizationSelected = (orgUid) ->
!!w.selectedOrganizations[orgUid]
$scope.toggleSelectOrganization = (orgUid) ->
if $scope.multiOrgMode()
w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid]
$scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect )
else if $scope.singleOrgMode()
resetSelectedOrgs()
w.selectedOrganizations[orgUid] = true
# What will be passed to parentWidget
setting = {}
setting.key = "<KEY>"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.dashboardOrganizations = _.sortBy(currentDashboard.data_sources, (org) -> org.label.toLowerCase())
return unless w.metadata? && w.metadata.organization_ids?
widgetOrgIds = w.metadata.organization_ids
if $scope.singleOrgMode()
resetSelectedOrgs()
if widgetOrgIds.length > 1
currentOrganization = ImpacMainSvc.config.currentOrganization
w.selectedOrganizations[currentOrganization.uid] = true
forceReload = true
else
w.selectedOrganizations[widgetOrgIds[0]] = true
else if $scope.multiOrgMode()
for org in $scope.dashboardOrganizations
w.selectedOrganizations[org.uid] = _.contains(widgetOrgIds, org.uid)
setting.isInitialized = true
ImpacWidgetsSvc.updateWidgetSettings(w, true) if forceReload
)
setting.toMetadata = ->
newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) ->
uid if checked
))
newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations)
return { organization_ids: newOrganizations }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingOrganizations', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/organizations.tmpl.html'),
controller: 'SettingOrganizationsCtrl'
}
)
| true | module = angular.module('impac.components.widgets-settings.organizations',[])
module.controller('SettingOrganizationsCtrl', ($scope, $log, ImpacDashboardsSvc, ImpacMainSvc, ImpacWidgetsSvc) ->
w = $scope.parentWidget
w.selectedOrganizations = {}
$scope.mode ||= 'multiple'
$scope.multiOrgMode = -> $scope.mode == 'multiple'
$scope.singleOrgMode = -> $scope.mode == 'single'
resetSelectedOrgs = -> w.selectedOrganizations = _.mapValues(w.selectedOrganizations, -> false)
$scope.isOrganizationSelected = (orgUid) ->
!!w.selectedOrganizations[orgUid]
$scope.toggleSelectOrganization = (orgUid) ->
if $scope.multiOrgMode()
w.selectedOrganizations[orgUid] = !w.selectedOrganizations[orgUid]
$scope.onSelect({orgs: w.selectedOrganizations}) if angular.isDefined( $scope.onSelect )
else if $scope.singleOrgMode()
resetSelectedOrgs()
w.selectedOrganizations[orgUid] = true
# What will be passed to parentWidget
setting = {}
setting.key = "PI:KEY:<KEY>END_PI"
setting.isInitialized = false
# initialization of selected organizations
setting.initialize = ->
ImpacDashboardsSvc.load().then(
(config) ->
currentDashboard = config.currentDashboard
$scope.dashboardOrganizations = _.sortBy(currentDashboard.data_sources, (org) -> org.label.toLowerCase())
return unless w.metadata? && w.metadata.organization_ids?
widgetOrgIds = w.metadata.organization_ids
if $scope.singleOrgMode()
resetSelectedOrgs()
if widgetOrgIds.length > 1
currentOrganization = ImpacMainSvc.config.currentOrganization
w.selectedOrganizations[currentOrganization.uid] = true
forceReload = true
else
w.selectedOrganizations[widgetOrgIds[0]] = true
else if $scope.multiOrgMode()
for org in $scope.dashboardOrganizations
w.selectedOrganizations[org.uid] = _.contains(widgetOrgIds, org.uid)
setting.isInitialized = true
ImpacWidgetsSvc.updateWidgetSettings(w, true) if forceReload
)
setting.toMetadata = ->
newOrganizations = _.compact(_.map(w.selectedOrganizations, (checked,uid) ->
uid if checked
))
newOrganizations = [_.first($scope.dashboardOrganizations).uid] if _.isEmpty(newOrganizations)
return { organization_ids: newOrganizations }
w.settings.push(setting)
# Setting is ready: trigger load content
# ------------------------------------
$scope.deferred.resolve($scope.parentWidget)
)
module.directive('settingOrganizations', ($templateCache) ->
return {
restrict: 'A',
scope: {
parentWidget: '='
mode: '@?'
deferred: '='
onSelect: '&?'
},
template: $templateCache.get('widgets-settings/organizations.tmpl.html'),
controller: 'SettingOrganizationsCtrl'
}
)
|
[
{
"context": " rich text editing jQuery UI widget\n# (c) 2011 Henri Bergius, IKS Consortium\n# Hallo may be freely distrib",
"end": 79,
"score": 0.9998577237129211,
"start": 66,
"tag": "NAME",
"value": "Henri Bergius"
}
] | src/plugins/table.coffee | git-j/hallo | 0 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 Henri Bergius, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallotable',
dropdownform: null
tmpid: 0
selected_row: null
selected_cell: null
html: null
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
contentId = target_id
@tmpid='mod_' + (new Date()).getTime()
return false if rangy.getSelection().rangeCount == 0
range = rangy.getSelection().getRangeAt(0)
table = $(range.startContainer).closest('table')
table = $(range.endContainer).closest('table') if !table.length
tr = $(range.startContainer).closest('tr')
tr = $(range.endContainer).closest('tr') if !tr.length
td = $(range.startContainer).closest('td')
td = $(range.endContainer).closest('td') if !td.length
td = $(range.startContainer).closest('th') if !td.length
td = $(range.endContainer).closest('th') if !td.length
table_selected = false
if ( table.length )
#modify
@options.editable.element.find('table').each (index,item) =>
if ( table[0] == item )
$(item).attr('id',@tmpid)
rows = 0
cols = 0
border = $(item).hasClass('table-border')
heading = false
$(item).find('tr').each (rindx,row) =>
@selected_row = $(row) if ( tr[0] == row )
$(row).find('th').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
heading = true
$(row).find('td').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
rows = rindx if rows < rindx
$('#' + contentId + 'cols').val(cols + 1)
$('#' + contentId + 'rows').val(rows + 1)
if ( border )
$('#' + contentId + 'border').addClass('active')
else
$('#' + contentId + 'border').removeClass('active')
if ( heading )
$('#' + contentId + 'heading').addClass('active')
else
$('#' + contentId + 'heading').removeClass('active')
table_selected = true
if !table_selected
#create
table_placeholder = '<table id="' + @tmpid + '" class="table-border"></table>'
table_placeholder_node = jQuery(table_placeholder)
selection_html = @options.editable.getSelectionHtml()
if ( selection_html == '' )
@options.editable.getSelectionNode (selection) =>
if selection[0] == @options.editable.element[0]
@options.editable.element.append(table_placeholder_node)
else
table_placeholder_node.insertAfter(selection)
else
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
range.deleteContents()
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse(false)
jQuery('body').append(table_placeholder_node)
range.insertNode(table_placeholder_node[0])
recalc = =>
@recalcHTML(target.attr('id'))
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
target.bind 'hide', =>
jQuery('table').each (index,item) =>
jQuery(item).removeAttr('id')
buttonset.append @dropdownform
toolbar.append buttonset
updateTableHTML: (contentId) ->
table = $('#' + @tmpid)
rows = $('#' + contentId + 'rows').val();
cols = $('#' + contentId + 'cols').val();
border = $('#' + contentId + 'border').hasClass('active')
heading = $('#' + contentId + 'heading').hasClass('active');
if ( rows=='' || cols == '' || parseInt(rows) == NaN || parseInt(cols) == NaN || rows < 0 || cols < 0 )
return false
if ( border )
table.attr('class','table-border')
else
table.attr('class','table-no-border')
table.removeAttr('border')
irow = 0
table.find('tr').each (rindx,row) =>
irow = rindx + 1
if irow > rows
$(row).remove()
return
icol = 0
$(row).find('th').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if ( !heading )
$(cell).contents().unwrap().wrapAll('<td></td>').parent()
$(row).find('td').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if heading && rindx == 0
$(cell).contents().unwrap().wrapAll('<th></th>').parent()
if ( icol < cols )
icol = icol + 1
for c in[icol..cols] by 1
if ( heading && irow == 1 )
$(row).append('<th>' + utils.tr('heading') + '</th>')
else
$(row).append('<td>' + utils.tr('content') + '</td>')
if ( irow < rows )
irow = irow + 1
for r in[irow..rows] by 1
row = '<tr>'
for c in[1..cols] by 1
if ( heading && r == 1)
row += '<th>' + utils.tr('heading') + '</th>'
else
row += '<td>' + utils.tr('content') + '</td>'
row+='</tr>'
table.append(row)
return table[0].outerHTML #?
recalcHTML: (contentId) ->
@html = @updateTableHTML(contentId)
@options.editable.store()
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
el.append(toggle_button)
else
recalc= =>
@recalcHTML(contentId)
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
el = jQuery "<li><button class=\"action_button\" id=\"" + @tmpid + element + "\">" + utils.tr(element) + "</button></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addInput("number", "rows","3")
contentAreaUL.append addInput("number", "cols","3")
contentAreaUL.append addInput("checkbox", "heading", true)
contentAreaUL.append addInput("checkbox", "border", true)
contentAreaUL.append addButton "apply", =>
@recalcHTML(contentId)
table = $('#' + @tmpid)
sel_cell = table.find('th:first')
if ( !sel_cell.length )
sel_cell = table.find('td:first')
@options.editable.setContentPosition(sel_cell)
table.removeAttr('id')
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append addButton "remove", =>
@options.editable.setContentPosition($('#' + @tmpid))
$('#' + @tmpid).remove()
@options.editable.restoreContentPosition()
@dropdownform.hallodropdownform('hideForm')
#requires DOM-modification
#contentAreaUL.append addButton "insertRow", =>
# cols = $('#' + contentId + 'cols').val();
# if ( cols == '' || parseInt(cols) == NaN || cols < 0 )
# new_row_html = '<tr>'
# for c in[1..cols] by 1
# html+='<td>' + utils.tr('content') + '</td>';
# new_row_html+= '</tr>'
# @selected_row.prepend()
# @dropdownform.hallodropdownform('hideForm')
#contentAreaUL.append addButton "removeRow", =>
# @selected_row.remove()
# @dropdownform.hallodropdownform('hideForm')
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'table'
if ( window.action_list && window.action_list['hallojs_table'] != undefined )
button_label = window.action_list['hallojs_table'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'table'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| 99389 | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 <NAME>, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallotable',
dropdownform: null
tmpid: 0
selected_row: null
selected_cell: null
html: null
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
contentId = target_id
@tmpid='mod_' + (new Date()).getTime()
return false if rangy.getSelection().rangeCount == 0
range = rangy.getSelection().getRangeAt(0)
table = $(range.startContainer).closest('table')
table = $(range.endContainer).closest('table') if !table.length
tr = $(range.startContainer).closest('tr')
tr = $(range.endContainer).closest('tr') if !tr.length
td = $(range.startContainer).closest('td')
td = $(range.endContainer).closest('td') if !td.length
td = $(range.startContainer).closest('th') if !td.length
td = $(range.endContainer).closest('th') if !td.length
table_selected = false
if ( table.length )
#modify
@options.editable.element.find('table').each (index,item) =>
if ( table[0] == item )
$(item).attr('id',@tmpid)
rows = 0
cols = 0
border = $(item).hasClass('table-border')
heading = false
$(item).find('tr').each (rindx,row) =>
@selected_row = $(row) if ( tr[0] == row )
$(row).find('th').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
heading = true
$(row).find('td').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
rows = rindx if rows < rindx
$('#' + contentId + 'cols').val(cols + 1)
$('#' + contentId + 'rows').val(rows + 1)
if ( border )
$('#' + contentId + 'border').addClass('active')
else
$('#' + contentId + 'border').removeClass('active')
if ( heading )
$('#' + contentId + 'heading').addClass('active')
else
$('#' + contentId + 'heading').removeClass('active')
table_selected = true
if !table_selected
#create
table_placeholder = '<table id="' + @tmpid + '" class="table-border"></table>'
table_placeholder_node = jQuery(table_placeholder)
selection_html = @options.editable.getSelectionHtml()
if ( selection_html == '' )
@options.editable.getSelectionNode (selection) =>
if selection[0] == @options.editable.element[0]
@options.editable.element.append(table_placeholder_node)
else
table_placeholder_node.insertAfter(selection)
else
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
range.deleteContents()
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse(false)
jQuery('body').append(table_placeholder_node)
range.insertNode(table_placeholder_node[0])
recalc = =>
@recalcHTML(target.attr('id'))
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
target.bind 'hide', =>
jQuery('table').each (index,item) =>
jQuery(item).removeAttr('id')
buttonset.append @dropdownform
toolbar.append buttonset
updateTableHTML: (contentId) ->
table = $('#' + @tmpid)
rows = $('#' + contentId + 'rows').val();
cols = $('#' + contentId + 'cols').val();
border = $('#' + contentId + 'border').hasClass('active')
heading = $('#' + contentId + 'heading').hasClass('active');
if ( rows=='' || cols == '' || parseInt(rows) == NaN || parseInt(cols) == NaN || rows < 0 || cols < 0 )
return false
if ( border )
table.attr('class','table-border')
else
table.attr('class','table-no-border')
table.removeAttr('border')
irow = 0
table.find('tr').each (rindx,row) =>
irow = rindx + 1
if irow > rows
$(row).remove()
return
icol = 0
$(row).find('th').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if ( !heading )
$(cell).contents().unwrap().wrapAll('<td></td>').parent()
$(row).find('td').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if heading && rindx == 0
$(cell).contents().unwrap().wrapAll('<th></th>').parent()
if ( icol < cols )
icol = icol + 1
for c in[icol..cols] by 1
if ( heading && irow == 1 )
$(row).append('<th>' + utils.tr('heading') + '</th>')
else
$(row).append('<td>' + utils.tr('content') + '</td>')
if ( irow < rows )
irow = irow + 1
for r in[irow..rows] by 1
row = '<tr>'
for c in[1..cols] by 1
if ( heading && r == 1)
row += '<th>' + utils.tr('heading') + '</th>'
else
row += '<td>' + utils.tr('content') + '</td>'
row+='</tr>'
table.append(row)
return table[0].outerHTML #?
recalcHTML: (contentId) ->
@html = @updateTableHTML(contentId)
@options.editable.store()
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
el.append(toggle_button)
else
recalc= =>
@recalcHTML(contentId)
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
el = jQuery "<li><button class=\"action_button\" id=\"" + @tmpid + element + "\">" + utils.tr(element) + "</button></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addInput("number", "rows","3")
contentAreaUL.append addInput("number", "cols","3")
contentAreaUL.append addInput("checkbox", "heading", true)
contentAreaUL.append addInput("checkbox", "border", true)
contentAreaUL.append addButton "apply", =>
@recalcHTML(contentId)
table = $('#' + @tmpid)
sel_cell = table.find('th:first')
if ( !sel_cell.length )
sel_cell = table.find('td:first')
@options.editable.setContentPosition(sel_cell)
table.removeAttr('id')
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append addButton "remove", =>
@options.editable.setContentPosition($('#' + @tmpid))
$('#' + @tmpid).remove()
@options.editable.restoreContentPosition()
@dropdownform.hallodropdownform('hideForm')
#requires DOM-modification
#contentAreaUL.append addButton "insertRow", =>
# cols = $('#' + contentId + 'cols').val();
# if ( cols == '' || parseInt(cols) == NaN || cols < 0 )
# new_row_html = '<tr>'
# for c in[1..cols] by 1
# html+='<td>' + utils.tr('content') + '</td>';
# new_row_html+= '</tr>'
# @selected_row.prepend()
# @dropdownform.hallodropdownform('hideForm')
#contentAreaUL.append addButton "removeRow", =>
# @selected_row.remove()
# @dropdownform.hallodropdownform('hideForm')
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'table'
if ( window.action_list && window.action_list['hallojs_table'] != undefined )
button_label = window.action_list['hallojs_table'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'table'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
| true | # Hallo - a rich text editing jQuery UI widget
# (c) 2011 PI:NAME:<NAME>END_PI, IKS Consortium
# Hallo may be freely distributed under the MIT license
# Plugin to minimalistic add a table to the editable
((jQuery) ->
jQuery.widget 'IKS.hallotable',
dropdownform: null
tmpid: 0
selected_row: null
selected_cell: null
html: null
options:
editable: null
toolbar: null
uuid: ''
elements: [
'rows'
'cols'
'border'
]
buttonCssClass: null
populateToolbar: (toolbar) ->
buttonset = jQuery "<span class=\"#{@widgetName}\"></span>"
contentId = "#{@options.uuid}-#{@widgetName}-data"
target = @_prepareDropdown contentId
toolbar.append target
setup= (select_target,target_id) =>
contentId = target_id
@tmpid='mod_' + (new Date()).getTime()
return false if rangy.getSelection().rangeCount == 0
range = rangy.getSelection().getRangeAt(0)
table = $(range.startContainer).closest('table')
table = $(range.endContainer).closest('table') if !table.length
tr = $(range.startContainer).closest('tr')
tr = $(range.endContainer).closest('tr') if !tr.length
td = $(range.startContainer).closest('td')
td = $(range.endContainer).closest('td') if !td.length
td = $(range.startContainer).closest('th') if !td.length
td = $(range.endContainer).closest('th') if !td.length
table_selected = false
if ( table.length )
#modify
@options.editable.element.find('table').each (index,item) =>
if ( table[0] == item )
$(item).attr('id',@tmpid)
rows = 0
cols = 0
border = $(item).hasClass('table-border')
heading = false
$(item).find('tr').each (rindx,row) =>
@selected_row = $(row) if ( tr[0] == row )
$(row).find('th').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
heading = true
$(row).find('td').each (cindx,col) =>
@selected_cell = $(col) if ( td[0] == col )
cols = cindx if ( cols < cindx )
rows = rindx if rows < rindx
$('#' + contentId + 'cols').val(cols + 1)
$('#' + contentId + 'rows').val(rows + 1)
if ( border )
$('#' + contentId + 'border').addClass('active')
else
$('#' + contentId + 'border').removeClass('active')
if ( heading )
$('#' + contentId + 'heading').addClass('active')
else
$('#' + contentId + 'heading').removeClass('active')
table_selected = true
if !table_selected
#create
table_placeholder = '<table id="' + @tmpid + '" class="table-border"></table>'
table_placeholder_node = jQuery(table_placeholder)
selection_html = @options.editable.getSelectionHtml()
if ( selection_html == '' )
@options.editable.getSelectionNode (selection) =>
if selection[0] == @options.editable.element[0]
@options.editable.element.append(table_placeholder_node)
else
table_placeholder_node.insertAfter(selection)
else
selection = rangy.getSelection()
if ( selection.rangeCount > 0 )
range = selection.getRangeAt(0)
range.deleteContents()
else
range = rangy.createRange()
range.selectNode(@options.editable.element[0])
range.collapse(false)
jQuery('body').append(table_placeholder_node)
range.insertNode(table_placeholder_node[0])
recalc = =>
@recalcHTML(target.attr('id'))
window.setTimeout recalc, 300
return true
@dropdownform = @_prepareButton setup, target
target.bind 'hide', =>
jQuery('table').each (index,item) =>
jQuery(item).removeAttr('id')
buttonset.append @dropdownform
toolbar.append buttonset
updateTableHTML: (contentId) ->
table = $('#' + @tmpid)
rows = $('#' + contentId + 'rows').val();
cols = $('#' + contentId + 'cols').val();
border = $('#' + contentId + 'border').hasClass('active')
heading = $('#' + contentId + 'heading').hasClass('active');
if ( rows=='' || cols == '' || parseInt(rows) == NaN || parseInt(cols) == NaN || rows < 0 || cols < 0 )
return false
if ( border )
table.attr('class','table-border')
else
table.attr('class','table-no-border')
table.removeAttr('border')
irow = 0
table.find('tr').each (rindx,row) =>
irow = rindx + 1
if irow > rows
$(row).remove()
return
icol = 0
$(row).find('th').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if ( !heading )
$(cell).contents().unwrap().wrapAll('<td></td>').parent()
$(row).find('td').each (cindx,cell) =>
icol = cindx + 1
if icol > cols
$(cell).remove()
return
if heading && rindx == 0
$(cell).contents().unwrap().wrapAll('<th></th>').parent()
if ( icol < cols )
icol = icol + 1
for c in[icol..cols] by 1
if ( heading && irow == 1 )
$(row).append('<th>' + utils.tr('heading') + '</th>')
else
$(row).append('<td>' + utils.tr('content') + '</td>')
if ( irow < rows )
irow = irow + 1
for r in[irow..rows] by 1
row = '<tr>'
for c in[1..cols] by 1
if ( heading && r == 1)
row += '<th>' + utils.tr('heading') + '</th>'
else
row += '<td>' + utils.tr('content') + '</td>'
row+='</tr>'
table.append(row)
return table[0].outerHTML #?
recalcHTML: (contentId) ->
@html = @updateTableHTML(contentId)
@options.editable.store()
_prepareDropdown: (contentId) ->
contentArea = jQuery "<div id=\"#{contentId}\"><ul></ul></div>"
contentAreaUL = contentArea.find('ul')
addInput = (type,element,default_value,recalc_preview) =>
elid = "#{contentId}#{element}"
el = jQuery "<li></li>"
if ( type == 'checkbox' )
toggle_button = jQuery('<button type="button" class="toggle_button" id="' + elid + '"/>')
recalc= =>
toggle_button.toggleClass('active')
@recalcHTML(contentId)
toggle_button.html(utils.tr(element))
toggle_button.bind('click', recalc)
if ( default_value == true )
toggle_button.addClass('active')
el.append(toggle_button)
else
recalc= =>
@recalcHTML(contentId)
el.append('<label for="' + elid + '">' + utils.tr(element) + '</label>')
el.append('<input type="' + type + '" id="' + elid + '"/>')
if ( default_value )
el.find('input').val(default_value)
el.find('input').bind('keyup change',recalc)
el
addButton = (element,event_handler) =>
el = jQuery "<li><button class=\"action_button\" id=\"" + @tmpid + element + "\">" + utils.tr(element) + "</button></li>"
#unless containingElement is 'div'
# el.addClass 'disabled'
el.find('button').bind 'click', event_handler
el
contentAreaUL.append addInput("number", "rows","3")
contentAreaUL.append addInput("number", "cols","3")
contentAreaUL.append addInput("checkbox", "heading", true)
contentAreaUL.append addInput("checkbox", "border", true)
contentAreaUL.append addButton "apply", =>
@recalcHTML(contentId)
table = $('#' + @tmpid)
sel_cell = table.find('th:first')
if ( !sel_cell.length )
sel_cell = table.find('td:first')
@options.editable.setContentPosition(sel_cell)
table.removeAttr('id')
@dropdownform.hallodropdownform('hideForm')
contentAreaUL.append addButton "remove", =>
@options.editable.setContentPosition($('#' + @tmpid))
$('#' + @tmpid).remove()
@options.editable.restoreContentPosition()
@dropdownform.hallodropdownform('hideForm')
#requires DOM-modification
#contentAreaUL.append addButton "insertRow", =>
# cols = $('#' + contentId + 'cols').val();
# if ( cols == '' || parseInt(cols) == NaN || cols < 0 )
# new_row_html = '<tr>'
# for c in[1..cols] by 1
# html+='<td>' + utils.tr('content') + '</td>';
# new_row_html+= '</tr>'
# @selected_row.prepend()
# @dropdownform.hallodropdownform('hideForm')
#contentAreaUL.append addButton "removeRow", =>
# @selected_row.remove()
# @dropdownform.hallodropdownform('hideForm')
contentArea
_prepareButton: (setup, target) ->
buttonElement = jQuery '<span></span>'
button_label = 'table'
if ( window.action_list && window.action_list['hallojs_table'] != undefined )
button_label = window.action_list['hallojs_table'].title
buttonElement.hallodropdownform
uuid: @options.uuid
editable: @options.editable
label: button_label
command: 'table'
icon: 'icon-text-height'
target: target
setup: setup
cssClass: @options.buttonCssClass
buttonElement
)(jQuery)
|
[
{
"context": "o.copy buf, ++i\n i += algo.length\n\n # password : string(20)\n buf[i] = 0xb4\n pass = scramble opts.passwo",
"end": 491,
"score": 0.9574483036994934,
"start": 485,
"tag": "PASSWORD",
"value": "string"
},
{
"context": "f, ++i\n i += algo.length\n\n # password : s... | src/commands/auth.coffee | aleclarson/duran | 0 | msgpack = require "msgpack-lite"
crypto = require "crypto"
ip = require "../iproto"
algo = msgpack.encode "chap-sha1"
module.exports = (opts) ->
user = msgpack.encode opts.user
buf = @alloc 44 + user.length
# map with 2 pairs
buf[i = 14] = 0x82
# username : string
buf[++i] = ip.USERNAME
user.copy buf, ++i
i += user.length
# array of 2 values
buf[i] = ip.TUPLE
buf[++i] = 0x92
# password algorithm
algo.copy buf, ++i
i += algo.length
# password : string(20)
buf[i] = 0xb4
pass = scramble opts.password or "", opts.salt
pass.copy buf, ++i
return
sha1 = (val) ->
crypto.createHash("sha1").update(val).digest()
xor = (a, b) ->
i = -1
len = Math.max a.length, b.length
buf = Buffer.allocUnsafe len
buf[i] = a[i] ^ b[i] while ++i < len
buf
scramble = (pass, salt) ->
salt = new Buffer salt, "base64"
pass = sha1 pass
xor pass, sha1 Buffer.concat [
salt.slice(0, 20)
sha1 pass
]
| 208609 | msgpack = require "msgpack-lite"
crypto = require "crypto"
ip = require "../iproto"
algo = msgpack.encode "chap-sha1"
module.exports = (opts) ->
user = msgpack.encode opts.user
buf = @alloc 44 + user.length
# map with 2 pairs
buf[i = 14] = 0x82
# username : string
buf[++i] = ip.USERNAME
user.copy buf, ++i
i += user.length
# array of 2 values
buf[i] = ip.TUPLE
buf[++i] = 0x92
# password algorithm
algo.copy buf, ++i
i += algo.length
# password : <PASSWORD>(2<PASSWORD>)
buf[i] = 0xb4
pass = scramble opts.password or "", opts.salt
pass.copy buf, ++i
return
sha1 = (val) ->
crypto.createHash("sha1").update(val).digest()
xor = (a, b) ->
i = -1
len = Math.max a.length, b.length
buf = Buffer.allocUnsafe len
buf[i] = a[i] ^ b[i] while ++i < len
buf
scramble = (pass, salt) ->
salt = new Buffer salt, "base64"
pass = sha1 pass
xor pass, sha1 Buffer.concat [
salt.slice(0, 20)
sha1 pass
]
| true | msgpack = require "msgpack-lite"
crypto = require "crypto"
ip = require "../iproto"
algo = msgpack.encode "chap-sha1"
module.exports = (opts) ->
user = msgpack.encode opts.user
buf = @alloc 44 + user.length
# map with 2 pairs
buf[i = 14] = 0x82
# username : string
buf[++i] = ip.USERNAME
user.copy buf, ++i
i += user.length
# array of 2 values
buf[i] = ip.TUPLE
buf[++i] = 0x92
# password algorithm
algo.copy buf, ++i
i += algo.length
# password : PI:PASSWORD:<PASSWORD>END_PI(2PI:PASSWORD:<PASSWORD>END_PI)
buf[i] = 0xb4
pass = scramble opts.password or "", opts.salt
pass.copy buf, ++i
return
sha1 = (val) ->
crypto.createHash("sha1").update(val).digest()
xor = (a, b) ->
i = -1
len = Math.max a.length, b.length
buf = Buffer.allocUnsafe len
buf[i] = a[i] ^ b[i] while ++i < len
buf
scramble = (pass, salt) ->
salt = new Buffer salt, "base64"
pass = sha1 pass
xor pass, sha1 Buffer.concat [
salt.slice(0, 20)
sha1 pass
]
|
[
{
"context": "# Author: Thinh Pham\n# Email: nhim175@gmail.com\n\nScorpion = require '.",
"end": 20,
"score": 0.9998495578765869,
"start": 10,
"tag": "NAME",
"value": "Thinh Pham"
},
{
"context": "# Author: Thinh Pham\n# Email: nhim175@gmail.com\n\nScorpion = require './scorpion.coff... | src/lib/fast_scorpion.coffee | nhim175/scorpionsmasher | 0 | # Author: Thinh Pham
# Email: nhim175@gmail.com
Scorpion = require './scorpion.coffee'
class FastScorpion extends Scorpion
runFrames: Phaser.Animation.generateFrameNames('x', 1, 5, '.png', 0)
dieFrames: ['x6.png']
speed: 5
module.exports = FastScorpion | 98928 | # Author: <NAME>
# Email: <EMAIL>
Scorpion = require './scorpion.coffee'
class FastScorpion extends Scorpion
runFrames: Phaser.Animation.generateFrameNames('x', 1, 5, '.png', 0)
dieFrames: ['x6.png']
speed: 5
module.exports = FastScorpion | true | # Author: PI:NAME:<NAME>END_PI
# Email: PI:EMAIL:<EMAIL>END_PI
Scorpion = require './scorpion.coffee'
class FastScorpion extends Scorpion
runFrames: Phaser.Animation.generateFrameNames('x', 1, 5, '.png', 0)
dieFrames: ['x6.png']
speed: 5
module.exports = FastScorpion |
[
{
"context": "\n new Element\n key: parentName = \"myParent\"\n e = new Element\n size: 50\n ",
"end": 11034,
"score": 0.9994440674781799,
"start": 11026,
"tag": "USERNAME",
"value": "myParent"
},
{
"context": "ew Element\n size: 50\n ... | test/tests/Art.Engine/ZAnimation/PersistantAnimator.coffee | Imikimi-LLC/art.engine | 4 | {log, isPlainObject, currentSecond} = require 'art-foundation'
{point} = require 'art-atomic'
{Element, RectangleElement, PersistantAnimator} = require 'art-engine'
module.exports = suite:
"legal values": ->
test "animators: 'opacity'", ->
e = new Element animators: 'opacity'
e.onNextReady ->
log animators: e.animators
assert.ok e.animators._opacity instanceof PersistantAnimator
test "animators: opacity: null", ->
e = new Element animators: opacity: null
e.onNextReady -> assert.doesNotExist e.animators
test "animators: opacity: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: (animator) ->
log arguments: arguments
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: animate: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: animate: (animator) ->
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: d: 1", ->
e = new Element animators: opacity: d: 1
e.onNextReady ->
assert.ok e.animators._opacity instanceof PersistantAnimator
assert.eq e.animators._opacity.duration, 1
"custom animators": ->
test "animator.element is set", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({stop, element}) ->
assert.ok element instanceof Element
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state starts out as {}", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop}) ->
assert.eq state, {}
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.options are the options passed to animators:", ->
new Promise (resolve) ->
e = new Element animators:
opacity:
foo: 123
animate: ({options, stop}) ->
assert.eq options.foo, 123
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state persists", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop, toValue}) ->
state.count ||= 0
state.count++
if state.count > 1
assert.eq state.count, 2
resolve()
stop()
toValue
e._register()
e.onNextReady -> e.opacity = 0
test "return value is preprocessed", ->
new Promise (resolve) ->
e = new RectangleElement animators: location: ({stop}) ->
stop()
e.onNextReady ->
assert.eq e.location.toString(), "pointLayout(10)"
resolve()
10
e._register()
e.onNextReady -> e.location = 20
"works": ->
test "animators property doesnt have an effect for initial properties", ->
e1 = new Element opacity: .5
e2 = new Element opacity: .5, animators: "opacity"
e1.onNextReady ->
assert.eq e1.opacity, e2.opacity
test "basic animation test", ->
e = new Element animators: "opacity"
e._register()
e.onNextReady ->
e.opacity = 0
e.onNextReady()
.then ->
assert.ok e.opacity > 0, "opacity should not be zero yet: #{e.opacity}"
test "animation triggers on every change", ->
new Promise (resolve) ->
doneOnce = false
e = new Element animators: opacity: d: 0, on: done: ->
if doneOnce
assert.eq e.opacity, .5
resolve()
else
assert.eq e.opacity, 0
doneOnce = true
e.opacity = .5
e._register()
e.onNextReady -> e.opacity = 0
test "animation updates to new target value", ->
new Promise (resolve) ->
updatedOnce = false
e = new Element animators: opacity: on:
update: ->
unless updatedOnce
updatedOnce = true
e.opacity = .5
done: ->
assert.eq e.opacity, .5
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"events": ->
test "start", ->
e = null
new Promise (resolve) ->
e = new Element animators:
opacity: on: start: ->
assert.eq e.animators._opacity.animationPos, 0
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "animator does not trigger on init", ->
e = new Element animators:
opacity: on: start: ->
log "triggered on init!!!"
assert.fail()
e._register()
e.onNextEpoch().then -> e.onNextEpoch()
test "done", ->
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on: done: ->
assert.eq e.animators._opacity.animationPos, 1
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "update only gets called inbetween", ->
testedUpdate = testedStart = false
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on:
start: ->
testedStart = true
assert.eq e.animators._opacity.animationPos, 0
update: ->
testedUpdate = true
assert.neq e.animators._opacity.animationPos, 0
assert.neq e.animators._opacity.animationPos, 1
done: ->
assert.eq e.animators._opacity.animationPos, 1
assert.eq testedUpdate, true
assert.eq testedStart, true
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"location": ->
test "location is animatable", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
e = new Element
location: 10
animators: location: on:
start: ->
testedStart = true
assert.eq e.location.toString(), "pointLayout(10)"
update: ->
testedUpdate = true
assert.neq e.location.toString(), "pointLayout(10)"
assert.neq e.location.toString(), "pointLayout(20)"
done: ->
assert.eq testedStart, true
assert.eq testedUpdate, true
assert.eq e.location.toString(), "pointLayout(20)"
resolve()
._register()
e.onNextReady -> e.location = 20
test "from constant to dynamic", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
start: -> assert.eq e.currentLocation, point 10
done: ->
assert.eq e.currentLocation, point 50
resolve()
._register()
.onNextReady ->
e.location = ps: .5
test "from constant to dynamic and back", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
update: ->
assert.ok e.currentLocation.gt point 10
assert.ok e.currentLocation.lt point 50
done: ->
if e.currentLocation.eq point 50
e.location = 10
else if e.currentLocation.eq point 10
resolve()
._register().onNextReady -> e.location = ps: .5
test "from dynamic to constant", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: ps: .5
animators: location: on:
start: -> assert.eq e.currentLocation, point 50
done: ->
assert.eq e.currentLocation, point 10
resolve()
._register().onNextReady -> e.location = 10
"voidProps": ->
test "fromVoid opacity", ->
new Promise (resolve) ->
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
assert.eq e.opacity, 0, "0 at start"
done: ->
assert.eq e.opacity, 1, "1 at done"
resolve()
update: ->
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
test "fromVoid not triggered when added with parent", ->
new Promise (resolve) ->
p = new Element {},
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
reject "should not trigger animation"
._register()
.onNextReady resolve
test "toVoid", ->
animationDone = false
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
key: "child with toVoid"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: opacity:
to: 0
on:
start: ->
assert.eq e.opacity, 1, "1 at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.opacity, 0, "0 at done"
update: ->
assert.eq e.parent.key, parentName
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
.onNextReady (p) =>
p.children = []
"voidProps.size requires preprocessing": ->
test "fromVoid size", ->
updateCount = 0
startTime = null
new Promise (resolve) ->
top = new Element()
._register()
top.onNextReady()
.then =>
e = new Element
size: 50
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(10), "at start"
done: ->
assert.eq e.size.layout(), point(50), "at start"
resolve()
update: ->
updateCount++
top.children = [e]
test "toVoid size", ->
animationDone = false
updateCount = 0
startTime = null
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
size: 50
key: "child with toVoid"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(50), "at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.size.layout(), point(10), "at start"
update: ->
updateCount++
assert.eq e.parent.key, parentName
._register()
.onNextReady (p) =>
p.children = []
"continuous animation": ->
test "start immediately", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
start: ({target:{element}}) ->
element._unregister()
resolve()
update: -> reject "update without start"
._register()
test "unregister stops animation", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
update: (event) ->
{element} = event.target
reject "not registered, but still animating!" unless element.isRegistered
element._unregister()
done: -> resolve()
._register()
| 12793 | {log, isPlainObject, currentSecond} = require 'art-foundation'
{point} = require 'art-atomic'
{Element, RectangleElement, PersistantAnimator} = require 'art-engine'
module.exports = suite:
"legal values": ->
test "animators: 'opacity'", ->
e = new Element animators: 'opacity'
e.onNextReady ->
log animators: e.animators
assert.ok e.animators._opacity instanceof PersistantAnimator
test "animators: opacity: null", ->
e = new Element animators: opacity: null
e.onNextReady -> assert.doesNotExist e.animators
test "animators: opacity: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: (animator) ->
log arguments: arguments
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: animate: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: animate: (animator) ->
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: d: 1", ->
e = new Element animators: opacity: d: 1
e.onNextReady ->
assert.ok e.animators._opacity instanceof PersistantAnimator
assert.eq e.animators._opacity.duration, 1
"custom animators": ->
test "animator.element is set", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({stop, element}) ->
assert.ok element instanceof Element
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state starts out as {}", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop}) ->
assert.eq state, {}
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.options are the options passed to animators:", ->
new Promise (resolve) ->
e = new Element animators:
opacity:
foo: 123
animate: ({options, stop}) ->
assert.eq options.foo, 123
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state persists", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop, toValue}) ->
state.count ||= 0
state.count++
if state.count > 1
assert.eq state.count, 2
resolve()
stop()
toValue
e._register()
e.onNextReady -> e.opacity = 0
test "return value is preprocessed", ->
new Promise (resolve) ->
e = new RectangleElement animators: location: ({stop}) ->
stop()
e.onNextReady ->
assert.eq e.location.toString(), "pointLayout(10)"
resolve()
10
e._register()
e.onNextReady -> e.location = 20
"works": ->
test "animators property doesnt have an effect for initial properties", ->
e1 = new Element opacity: .5
e2 = new Element opacity: .5, animators: "opacity"
e1.onNextReady ->
assert.eq e1.opacity, e2.opacity
test "basic animation test", ->
e = new Element animators: "opacity"
e._register()
e.onNextReady ->
e.opacity = 0
e.onNextReady()
.then ->
assert.ok e.opacity > 0, "opacity should not be zero yet: #{e.opacity}"
test "animation triggers on every change", ->
new Promise (resolve) ->
doneOnce = false
e = new Element animators: opacity: d: 0, on: done: ->
if doneOnce
assert.eq e.opacity, .5
resolve()
else
assert.eq e.opacity, 0
doneOnce = true
e.opacity = .5
e._register()
e.onNextReady -> e.opacity = 0
test "animation updates to new target value", ->
new Promise (resolve) ->
updatedOnce = false
e = new Element animators: opacity: on:
update: ->
unless updatedOnce
updatedOnce = true
e.opacity = .5
done: ->
assert.eq e.opacity, .5
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"events": ->
test "start", ->
e = null
new Promise (resolve) ->
e = new Element animators:
opacity: on: start: ->
assert.eq e.animators._opacity.animationPos, 0
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "animator does not trigger on init", ->
e = new Element animators:
opacity: on: start: ->
log "triggered on init!!!"
assert.fail()
e._register()
e.onNextEpoch().then -> e.onNextEpoch()
test "done", ->
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on: done: ->
assert.eq e.animators._opacity.animationPos, 1
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "update only gets called inbetween", ->
testedUpdate = testedStart = false
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on:
start: ->
testedStart = true
assert.eq e.animators._opacity.animationPos, 0
update: ->
testedUpdate = true
assert.neq e.animators._opacity.animationPos, 0
assert.neq e.animators._opacity.animationPos, 1
done: ->
assert.eq e.animators._opacity.animationPos, 1
assert.eq testedUpdate, true
assert.eq testedStart, true
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"location": ->
test "location is animatable", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
e = new Element
location: 10
animators: location: on:
start: ->
testedStart = true
assert.eq e.location.toString(), "pointLayout(10)"
update: ->
testedUpdate = true
assert.neq e.location.toString(), "pointLayout(10)"
assert.neq e.location.toString(), "pointLayout(20)"
done: ->
assert.eq testedStart, true
assert.eq testedUpdate, true
assert.eq e.location.toString(), "pointLayout(20)"
resolve()
._register()
e.onNextReady -> e.location = 20
test "from constant to dynamic", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
start: -> assert.eq e.currentLocation, point 10
done: ->
assert.eq e.currentLocation, point 50
resolve()
._register()
.onNextReady ->
e.location = ps: .5
test "from constant to dynamic and back", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
update: ->
assert.ok e.currentLocation.gt point 10
assert.ok e.currentLocation.lt point 50
done: ->
if e.currentLocation.eq point 50
e.location = 10
else if e.currentLocation.eq point 10
resolve()
._register().onNextReady -> e.location = ps: .5
test "from dynamic to constant", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: ps: .5
animators: location: on:
start: -> assert.eq e.currentLocation, point 50
done: ->
assert.eq e.currentLocation, point 10
resolve()
._register().onNextReady -> e.location = 10
"voidProps": ->
test "fromVoid opacity", ->
new Promise (resolve) ->
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
assert.eq e.opacity, 0, "0 at start"
done: ->
assert.eq e.opacity, 1, "1 at done"
resolve()
update: ->
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
test "fromVoid not triggered when added with parent", ->
new Promise (resolve) ->
p = new Element {},
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
reject "should not trigger animation"
._register()
.onNextReady resolve
test "toVoid", ->
animationDone = false
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
key: "child with toVoid"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: opacity:
to: 0
on:
start: ->
assert.eq e.opacity, 1, "1 at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.opacity, 0, "0 at done"
update: ->
assert.eq e.parent.key, parentName
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
.onNextReady (p) =>
p.children = []
"voidProps.size requires preprocessing": ->
test "fromVoid size", ->
updateCount = 0
startTime = null
new Promise (resolve) ->
top = new Element()
._register()
top.onNextReady()
.then =>
e = new Element
size: 50
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(10), "at start"
done: ->
assert.eq e.size.layout(), point(50), "at start"
resolve()
update: ->
updateCount++
top.children = [e]
test "toVoid size", ->
animationDone = false
updateCount = 0
startTime = null
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
size: 50
key: "<KEY>"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(50), "at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.size.layout(), point(10), "at start"
update: ->
updateCount++
assert.eq e.parent.key, parentName
._register()
.onNextReady (p) =>
p.children = []
"continuous animation": ->
test "start immediately", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
start: ({target:{element}}) ->
element._unregister()
resolve()
update: -> reject "update without start"
._register()
test "unregister stops animation", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
update: (event) ->
{element} = event.target
reject "not registered, but still animating!" unless element.isRegistered
element._unregister()
done: -> resolve()
._register()
| true | {log, isPlainObject, currentSecond} = require 'art-foundation'
{point} = require 'art-atomic'
{Element, RectangleElement, PersistantAnimator} = require 'art-engine'
module.exports = suite:
"legal values": ->
test "animators: 'opacity'", ->
e = new Element animators: 'opacity'
e.onNextReady ->
log animators: e.animators
assert.ok e.animators._opacity instanceof PersistantAnimator
test "animators: opacity: null", ->
e = new Element animators: opacity: null
e.onNextReady -> assert.doesNotExist e.animators
test "animators: opacity: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: (animator) ->
log arguments: arguments
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: animate: ->", ->
new Promise (resolve) ->
e = new Element animators: opacity: animate: (animator) ->
e.onNextReady ->
assert.eq e.opacity, 0
resolve()
animator.stop()
animator.toValue
e._register()
e.onNextReady -> e.opacity = 0
test "animators: opacity: d: 1", ->
e = new Element animators: opacity: d: 1
e.onNextReady ->
assert.ok e.animators._opacity instanceof PersistantAnimator
assert.eq e.animators._opacity.duration, 1
"custom animators": ->
test "animator.element is set", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({stop, element}) ->
assert.ok element instanceof Element
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state starts out as {}", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop}) ->
assert.eq state, {}
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.options are the options passed to animators:", ->
new Promise (resolve) ->
e = new Element animators:
opacity:
foo: 123
animate: ({options, stop}) ->
assert.eq options.foo, 123
resolve();stop()
e._register()
e.onNextReady -> e.opacity = 0
test "animator.state persists", ->
new Promise (resolve) ->
e = new Element animators: opacity: ({state, stop, toValue}) ->
state.count ||= 0
state.count++
if state.count > 1
assert.eq state.count, 2
resolve()
stop()
toValue
e._register()
e.onNextReady -> e.opacity = 0
test "return value is preprocessed", ->
new Promise (resolve) ->
e = new RectangleElement animators: location: ({stop}) ->
stop()
e.onNextReady ->
assert.eq e.location.toString(), "pointLayout(10)"
resolve()
10
e._register()
e.onNextReady -> e.location = 20
"works": ->
test "animators property doesnt have an effect for initial properties", ->
e1 = new Element opacity: .5
e2 = new Element opacity: .5, animators: "opacity"
e1.onNextReady ->
assert.eq e1.opacity, e2.opacity
test "basic animation test", ->
e = new Element animators: "opacity"
e._register()
e.onNextReady ->
e.opacity = 0
e.onNextReady()
.then ->
assert.ok e.opacity > 0, "opacity should not be zero yet: #{e.opacity}"
test "animation triggers on every change", ->
new Promise (resolve) ->
doneOnce = false
e = new Element animators: opacity: d: 0, on: done: ->
if doneOnce
assert.eq e.opacity, .5
resolve()
else
assert.eq e.opacity, 0
doneOnce = true
e.opacity = .5
e._register()
e.onNextReady -> e.opacity = 0
test "animation updates to new target value", ->
new Promise (resolve) ->
updatedOnce = false
e = new Element animators: opacity: on:
update: ->
unless updatedOnce
updatedOnce = true
e.opacity = .5
done: ->
assert.eq e.opacity, .5
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"events": ->
test "start", ->
e = null
new Promise (resolve) ->
e = new Element animators:
opacity: on: start: ->
assert.eq e.animators._opacity.animationPos, 0
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "animator does not trigger on init", ->
e = new Element animators:
opacity: on: start: ->
log "triggered on init!!!"
assert.fail()
e._register()
e.onNextEpoch().then -> e.onNextEpoch()
test "done", ->
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on: done: ->
assert.eq e.animators._opacity.animationPos, 1
resolve()
e._register()
e.onNextReady -> e.opacity = 0
test "update only gets called inbetween", ->
testedUpdate = testedStart = false
new Promise (resolve) ->
e = new Element animators:
opacity: duration: .1, on:
start: ->
testedStart = true
assert.eq e.animators._opacity.animationPos, 0
update: ->
testedUpdate = true
assert.neq e.animators._opacity.animationPos, 0
assert.neq e.animators._opacity.animationPos, 1
done: ->
assert.eq e.animators._opacity.animationPos, 1
assert.eq testedUpdate, true
assert.eq testedStart, true
resolve()
e._register()
e.onNextReady -> e.opacity = 0
"location": ->
test "location is animatable", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
e = new Element
location: 10
animators: location: on:
start: ->
testedStart = true
assert.eq e.location.toString(), "pointLayout(10)"
update: ->
testedUpdate = true
assert.neq e.location.toString(), "pointLayout(10)"
assert.neq e.location.toString(), "pointLayout(20)"
done: ->
assert.eq testedStart, true
assert.eq testedUpdate, true
assert.eq e.location.toString(), "pointLayout(20)"
resolve()
._register()
e.onNextReady -> e.location = 20
test "from constant to dynamic", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
start: -> assert.eq e.currentLocation, point 10
done: ->
assert.eq e.currentLocation, point 50
resolve()
._register()
.onNextReady ->
e.location = ps: .5
test "from constant to dynamic and back", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: 10
animators: location: on:
update: ->
assert.ok e.currentLocation.gt point 10
assert.ok e.currentLocation.lt point 50
done: ->
if e.currentLocation.eq point 50
e.location = 10
else if e.currentLocation.eq point 10
resolve()
._register().onNextReady -> e.location = ps: .5
test "from dynamic to constant", ->
testedStart = testedUpdate = false
new Promise (resolve) ->
new Element
size: 100
e = new Element
location: ps: .5
animators: location: on:
start: -> assert.eq e.currentLocation, point 50
done: ->
assert.eq e.currentLocation, point 10
resolve()
._register().onNextReady -> e.location = 10
"voidProps": ->
test "fromVoid opacity", ->
new Promise (resolve) ->
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
assert.eq e.opacity, 0, "0 at start"
done: ->
assert.eq e.opacity, 1, "1 at done"
resolve()
update: ->
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
test "fromVoid not triggered when added with parent", ->
new Promise (resolve) ->
p = new Element {},
e = new Element
animators: opacity:
fromVoid: 0
on:
start: ->
reject "should not trigger animation"
._register()
.onNextReady resolve
test "toVoid", ->
animationDone = false
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
key: "child with toVoid"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: opacity:
to: 0
on:
start: ->
assert.eq e.opacity, 1, "1 at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.opacity, 0, "0 at done"
update: ->
assert.eq e.parent.key, parentName
assert.ok e.opacity > 0
assert.ok e.opacity < 1
._register()
.onNextReady (p) =>
p.children = []
"voidProps.size requires preprocessing": ->
test "fromVoid size", ->
updateCount = 0
startTime = null
new Promise (resolve) ->
top = new Element()
._register()
top.onNextReady()
.then =>
e = new Element
size: 50
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(10), "at start"
done: ->
assert.eq e.size.layout(), point(50), "at start"
resolve()
update: ->
updateCount++
top.children = [e]
test "toVoid size", ->
animationDone = false
updateCount = 0
startTime = null
new Promise (resolve) ->
new Element
key: parentName = "myParent"
e = new Element
size: 50
key: "PI:KEY:<KEY>END_PI"
on: parentChanged: ->
unless e.parent
assert.eq true, animationDone
resolve()
animators: size:
voidValue: 10
on:
start: ->
startTime = currentSecond()
assert.eq e.size.layout(), point(50), "at start"
assert.eq e.parent.key, parentName
done: ->
animationDone = true
assert.eq e.size.layout(), point(10), "at start"
update: ->
updateCount++
assert.eq e.parent.key, parentName
._register()
.onNextReady (p) =>
p.children = []
"continuous animation": ->
test "start immediately", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
start: ({target:{element}}) ->
element._unregister()
resolve()
update: -> reject "update without start"
._register()
test "unregister stops animation", ->
new Promise (resolve, reject) ->
new Element
animators:
opacity:
animate: ({animationSeconds}) -> animationSeconds % 1
continuous: true # animation starts immediately
on:
update: (event) ->
{element} = event.target
reject "not registered, but still animating!" unless element.isRegistered
element._unregister()
done: -> resolve()
._register()
|
[
{
"context": "rn fn()\n firebase.initializeApp\n apiKey: \"AIzaSyAXxUJr9p5lMcN8_XXsn-ugsKUTQvXKoRc\",\n authDomain: \"js-play-cd3d8.firebaseapp.co",
"end": 202,
"score": 0.9997667074203491,
"start": 163,
"tag": "KEY",
"value": "AIzaSyAXxUJr9p5lMcN8_XXsn-ugsKUTQvXKoRc"
}
] | src/scripts/services/database.coffee | jpillora/js-play | 11 | App.factory 'database', () ->
#init and auth
db = null
user = null
prepare = (fn) ->
if db
return fn()
firebase.initializeApp
apiKey: "AIzaSyAXxUJr9p5lMcN8_XXsn-ugsKUTQvXKoRc",
authDomain: "js-play-cd3d8.firebaseapp.com",
databaseURL: "https://js-play-cd3d8.firebaseio.com",
storageBucket: ""
db = window.database = firebase.database()
success = null
int = setInterval ->
u = firebase.auth().currentUser
if u and success is null
success = true
user = u
fn()
clearInterval int
, 100
setTimeout ->
if success is null
success = false
fn()
, 3000
auth = (fn) ->
#has user
if user
return fn()
#create account and fetch user
firebase.auth().signInAnonymously().catch (error) ->
fn(error)
firebase.auth().onAuthStateChanged (u) ->
user = u
fn()
return null
#api
database =
init: (k, fn) ->
prepare (error) ->
if error
return fn(error)
auth (error) ->
if error
return fn(error)
database.get k, (val) ->
fn(null, val)
set: (k,v) ->
db.ref(k).set(v)
get: (k, fn) ->
db.ref(k).once "value", (snap) -> fn(snap.val())
on: (k, fn) ->
db.ref(k).on "value", (snap) -> fn(snap.val())
off: (k) ->
db.ref(k).off "value"
return database
| 16235 | App.factory 'database', () ->
#init and auth
db = null
user = null
prepare = (fn) ->
if db
return fn()
firebase.initializeApp
apiKey: "<KEY>",
authDomain: "js-play-cd3d8.firebaseapp.com",
databaseURL: "https://js-play-cd3d8.firebaseio.com",
storageBucket: ""
db = window.database = firebase.database()
success = null
int = setInterval ->
u = firebase.auth().currentUser
if u and success is null
success = true
user = u
fn()
clearInterval int
, 100
setTimeout ->
if success is null
success = false
fn()
, 3000
auth = (fn) ->
#has user
if user
return fn()
#create account and fetch user
firebase.auth().signInAnonymously().catch (error) ->
fn(error)
firebase.auth().onAuthStateChanged (u) ->
user = u
fn()
return null
#api
database =
init: (k, fn) ->
prepare (error) ->
if error
return fn(error)
auth (error) ->
if error
return fn(error)
database.get k, (val) ->
fn(null, val)
set: (k,v) ->
db.ref(k).set(v)
get: (k, fn) ->
db.ref(k).once "value", (snap) -> fn(snap.val())
on: (k, fn) ->
db.ref(k).on "value", (snap) -> fn(snap.val())
off: (k) ->
db.ref(k).off "value"
return database
| true | App.factory 'database', () ->
#init and auth
db = null
user = null
prepare = (fn) ->
if db
return fn()
firebase.initializeApp
apiKey: "PI:KEY:<KEY>END_PI",
authDomain: "js-play-cd3d8.firebaseapp.com",
databaseURL: "https://js-play-cd3d8.firebaseio.com",
storageBucket: ""
db = window.database = firebase.database()
success = null
int = setInterval ->
u = firebase.auth().currentUser
if u and success is null
success = true
user = u
fn()
clearInterval int
, 100
setTimeout ->
if success is null
success = false
fn()
, 3000
auth = (fn) ->
#has user
if user
return fn()
#create account and fetch user
firebase.auth().signInAnonymously().catch (error) ->
fn(error)
firebase.auth().onAuthStateChanged (u) ->
user = u
fn()
return null
#api
database =
init: (k, fn) ->
prepare (error) ->
if error
return fn(error)
auth (error) ->
if error
return fn(error)
database.get k, (val) ->
fn(null, val)
set: (k,v) ->
db.ref(k).set(v)
get: (k, fn) ->
db.ref(k).once "value", (snap) -> fn(snap.val())
on: (k, fn) ->
db.ref(k).on "value", (snap) -> fn(snap.val())
off: (k) ->
db.ref(k).off "value"
return database
|
[
{
"context": "lating framework in ~400 bytes gzipped\n\n @author Jason Mooberry <jasonmoo@me.com> (ported by David Rekow <david a",
"end": 256,
"score": 0.9998924136161804,
"start": 242,
"tag": "NAME",
"value": "Jason Mooberry"
},
{
"context": "in ~400 bytes gzipped\n\n @author J... | t.coffee | davidrekow/t.coffee | 2 | ###
_ __ __
| |_ __ ___ / _|/ _|___ ___
| _|_/ _/ _ \ _| _/ -_) -_)
\__(_)__\___/_| |_| \___\___|
t.coffee - CoffeeScript port of t.js,
a micro-templating framework in ~400 bytes gzipped
@author Jason Mooberry <jasonmoo@me.com> (ported by David Rekow <david at davidrekow.com>)
@license MIT
@version 0.1.3
###
blockregex = /\{\{\s*?(([@!>]?)(.+?))\s*?\}\}(([\s\S]+?)(\{\{\s*?:\1\s*?\}\}([\s\S]+?))?)\{\{\s*?\/(?:\1|\s*?\3\s*?)\s*?\}\}/g
valregex = /\{\{\s*?([=%])\s*?(.+?)\s*?\}\}/g
t = (template) ->
@t = template
return
scrub = (val) ->
return new Option(val).innerHTML.replace(/["']/g, '"')
get_value = (vars, key) ->
parts = key.split('.')
while parts.length
return false if parts[0] not of vars
vars = vars[parts.shift()]
return vars
render = (fragment, vars) ->
if not vars?
vars = fragment
fragment = @t
return fragment.replace(blockregex, (_, __, meta, key, inner, if_true, has_else, if_false) ->
val = get_value(vars, key)
temp = ''
if not val
return (if meta is '!' then render(inner, vars) else (if has_else then render(if_false, vars) else ''))
if not meta
return (if has_else then render(if_true, vars) else render(inner, vars))
if meta is '@'
for k, v of val
if val.hasOwnProperty(k)
temp += render(inner, {_key: k, _val: v})
if meta is '>'
if Array.isArray(val)
temp += render(inner, item) for item in val
else temp += render(inner, val)
return temp
).replace(valregex, (_, meta, key) ->
val = get_value(vars, key)
return (if val? then (if meta is '%' then scrub(val) else val) else '')
)
t::render = (vars) ->
return render(@t, vars)
window.t = t
| 207068 | ###
_ __ __
| |_ __ ___ / _|/ _|___ ___
| _|_/ _/ _ \ _| _/ -_) -_)
\__(_)__\___/_| |_| \___\___|
t.coffee - CoffeeScript port of t.js,
a micro-templating framework in ~400 bytes gzipped
@author <NAME> <<EMAIL>> (ported by <NAME> <david at davidrekow.com>)
@license MIT
@version 0.1.3
###
blockregex = /\{\{\s*?(([@!>]?)(.+?))\s*?\}\}(([\s\S]+?)(\{\{\s*?:\1\s*?\}\}([\s\S]+?))?)\{\{\s*?\/(?:\1|\s*?\3\s*?)\s*?\}\}/g
valregex = /\{\{\s*?([=%])\s*?(.+?)\s*?\}\}/g
t = (template) ->
@t = template
return
scrub = (val) ->
return new Option(val).innerHTML.replace(/["']/g, '"')
get_value = (vars, key) ->
parts = key.split('.')
while parts.length
return false if parts[0] not of vars
vars = vars[parts.shift()]
return vars
render = (fragment, vars) ->
if not vars?
vars = fragment
fragment = @t
return fragment.replace(blockregex, (_, __, meta, key, inner, if_true, has_else, if_false) ->
val = get_value(vars, key)
temp = ''
if not val
return (if meta is '!' then render(inner, vars) else (if has_else then render(if_false, vars) else ''))
if not meta
return (if has_else then render(if_true, vars) else render(inner, vars))
if meta is '@'
for k, v of val
if val.hasOwnProperty(k)
temp += render(inner, {_key: k, _val: v})
if meta is '>'
if Array.isArray(val)
temp += render(inner, item) for item in val
else temp += render(inner, val)
return temp
).replace(valregex, (_, meta, key) ->
val = get_value(vars, key)
return (if val? then (if meta is '%' then scrub(val) else val) else '')
)
t::render = (vars) ->
return render(@t, vars)
window.t = t
| true | ###
_ __ __
| |_ __ ___ / _|/ _|___ ___
| _|_/ _/ _ \ _| _/ -_) -_)
\__(_)__\___/_| |_| \___\___|
t.coffee - CoffeeScript port of t.js,
a micro-templating framework in ~400 bytes gzipped
@author PI:NAME:<NAME>END_PI <PI:EMAIL:<EMAIL>END_PI> (ported by PI:NAME:<NAME>END_PI <david at davidrekow.com>)
@license MIT
@version 0.1.3
###
blockregex = /\{\{\s*?(([@!>]?)(.+?))\s*?\}\}(([\s\S]+?)(\{\{\s*?:\1\s*?\}\}([\s\S]+?))?)\{\{\s*?\/(?:\1|\s*?\3\s*?)\s*?\}\}/g
valregex = /\{\{\s*?([=%])\s*?(.+?)\s*?\}\}/g
t = (template) ->
@t = template
return
scrub = (val) ->
return new Option(val).innerHTML.replace(/["']/g, '"')
get_value = (vars, key) ->
parts = key.split('.')
while parts.length
return false if parts[0] not of vars
vars = vars[parts.shift()]
return vars
render = (fragment, vars) ->
if not vars?
vars = fragment
fragment = @t
return fragment.replace(blockregex, (_, __, meta, key, inner, if_true, has_else, if_false) ->
val = get_value(vars, key)
temp = ''
if not val
return (if meta is '!' then render(inner, vars) else (if has_else then render(if_false, vars) else ''))
if not meta
return (if has_else then render(if_true, vars) else render(inner, vars))
if meta is '@'
for k, v of val
if val.hasOwnProperty(k)
temp += render(inner, {_key: k, _val: v})
if meta is '>'
if Array.isArray(val)
temp += render(inner, item) for item in val
else temp += render(inner, val)
return temp
).replace(valregex, (_, meta, key) ->
val = get_value(vars, key)
return (if val? then (if meta is '%' then scrub(val) else val) else '')
)
t::render = (vars) ->
return render(@t, vars)
window.t = t
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.