Framework

- About
- Guides
- Community
- API
- Code
- Download

# Kanso API Documentation

Index | View on single page

## actions

Implementation of widget actions. These are procedures that can be referenced by widgets to present/collect information, manipulate the DOM, or otherwise affect the application state when a widget is acted upon.

## cookies

Functions related to the manipulation and reading of cookies.

### readBrowserCookies()

Read cookies currently stored in the browser, returning an object keyed by cookie name.

Returns: Object

### readBrowserCookie(name)

Reads browser cookies and returned the value of the named cookie.

Returns: String

### cookieString(req, opt)

Creates a string for storing a cookie on the browser.

#### Parameters

req | Request Object |
opt | Object |

Returns: String

### setBrowserCookie(req, opt)

Sets a cookie on the browser, for use client-side only.

#### Parameters

req | Request Object |
opt | Object |

### setResponseCookie(req, res, opt)

Creates a Set-Cookie header on a response object.

#### Parameters

req | Request Object |
res | Response Object |
opt | Object |

## core

The core module contains functions used by kanso to facilitate the running of your app. You shouldn't need to use any of the functions here directly unless you're messing with the internals of Kanso.

### rewriteGroups(pattern, url)

Extracts groups from a url, eg: '/some/path' with pattern '/some/:name' -> {name: 'path'}

#### Parameters

pattern | String |
url | String |

Returns: Object

### rewriteSplat(pattern, url)

Extracts a splat value from a rewrite pattern and matching URL.

#### Parameters

pattern | String |
url | String |

Returns: String

### matchURL(method, url)

Attempts to match rewrite from patterns to a URL, returning the matching rewrite object if successful.

#### Parameters

method | String |
url | String |

Returns: Object

### replaceGroups(val, groups, splat)

Replace group names in a string with the value of that group eg: "/:name" with groups {name: 'test'} -> "/test"

#### Parameters

val | String |
groups | Object |
splat | String |

Returns: String

### createRequest(method, url, data, match, callback)

Creates a new request object from a url and matching rewrite object. Query parameters are automatically populated from rewrite pattern.

#### Parameters

method | String |
url | String |
data | Object |
match | Object |
callback | Function |

### runShowBrowser(req, name, docid, callback)

Fetches the relevant document and calls the named show function.

#### Parameters

req | Object |
name | String |
docid | String |
callback | Function |

### parseResponse(req, res)

Helper for runShow/runList.

#### Parameters

req | Object |
res | Object |

### runShow(fn, doc, req)

Runs a show function with the given document and request object, emitting relevant events. This function runs both server and client-side.

#### Parameters

fn | Function |
doc | Object |
req | Object |

### runUpdateBrowser(req, name, docid, callback)

Fetches the relevant document and calls the named update function.

#### Parameters

req | Object |
name | String |
docid | String |
callback | Function |

### runUpdate(fn, doc, req)

Runs a update function with the given document and request object, emitting relevant events. This function runs both server and client-side.

#### Parameters

fn | Function |
doc | Object |
req | Object |

### createHead(data)

Creates a fake head object from view results for passing to a list function being run client-side.

#### Parameters

data | Object |

Returns: Object

### runListBrowser(req, name, view, callback)

Fetches the relevant view and calls the named list function with the results.

#### Parameters

req | Object |
name | String |
view | String |
callback | Function |

### runList(fn, head, req)

Runs a list function with the given document and request object, emitting relevant events. This function runs both server and client-side.

#### Parameters

fn | Function |
head | Object |
req | Object |

### handle(method, url, data)

Creates a request object for the url and runs appropriate show, list or update functions.

#### Parameters

method | String |
url | String |
data | Object |

### setURL(method, url, data)

Add a history entry for the given url, prefixed with the baseURL for the app.

#### Parameters

method | String |
url | String |
data | Object | (optional)

### getURL()

Gets the current app-level URL (without baseURL prefix).

Returns: String

### sameOrigin(a, b)

Tests is two urls are of the same origin. Accepts parsed url objects or strings as arguments.

#### Parameters

a |  |
b |  |

Returns: Boolean

### appPath(p)

Converts a full url to an app-level url (without baseURL prefix). example: {baseURL}/some/path -> /some/path

#### Parameters

p | String |

Returns: String

### isAppURL(url)

Used to decide whether to handle a link or not. Should detect app vs. external urls.

#### Parameters

url | String |

Returns: Boolean

## db

Contains functions for querying and storing data in CouchDB.

### encode(str)

Encodes a document id or view, list or show name.

#### Parameters

str | String |

Returns: String

### request(options, callback)

Make a request, with some default settings and proper callback handling. Used behind-the-scenes by most other DB module functions.

#### Parameters

options | Object |
callback | Function |

### getRewrite(path, [q], callback)

Fetches a rewrite from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

path | String |
q | Object | (optional)
callback | Function |

### getDoc(id, [q, options], callback)

Fetches a document from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

id | String |
q | Object | (optional)
options | Object | (optional)
callback | Function |

### saveDoc(doc, [options], callback)

Saves a document to the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

doc | Object |
options | Object | (optional)
callback | Function |

### removeDoc(doc, [options], callback)

Deletes a document from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

doc | Object |
callback | Function |

### getView(view, [q], callback)

Fetches a view from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

view | String |
q | Object | (optional)
callback | Function |

### getList(list, view, [q], callback)

Transforms and fetches a view through a list from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

list | String |
view | String |
q | Object | (optional)
callback | Function |

### getShow(show, docid, [q], callback)

Transforms and fetches a document through a show from the database the app is running on. Results are passed to the callback, with the first argument of the callback reserved for any exceptions that occurred (node.js style).

#### Parameters

show | String |
docid | String |
q | Object | (optional)
callback | Function |

### all([q], callback)

Get all documents (including design docs).

#### Parameters

q | Object | (optional)
callback | Function |

### stringifyQuery(query)

Properly encodes query parameters to CouchDB views etc. Handle complex keys and other non-string parameters by passing through JSON.stringify. Returns a shallow-copied clone of the original query after complex values have been stringified.

#### Parameters

query | Object |

Returns: Object

### newUUID(cacheNum, callback)

Returns a new UUID generated by CouchDB. Its possible to cache multiple UUIDs for later use, to avoid making too many requests.

#### Parameters

cacheNum | Number | (optional, default: 1)
callback | Function |

### createDatabase(name, callback)

Creates a CouchDB database.

If you're running behind a virtual host you'll need to set up appropriate rewrites for a PUT request to '/' and turn off safe rewrites.

#### Parameters

name | String |
callback | Function |

### deleteDatabase(name, callback)

Deletes a CouchDB database.

If you're running behind a virtual host you'll need to set up appropriate rewrites for a DELETE request to '/' and turn off safe rewrites.

#### Parameters

name | String |
callback | Function |

### getReplication(id, callback)

Fetches the most recent revision of the replication document referred to by the id parameter.

If you're running behind a virtual host you'll need to set up appropriate rewrites to /_replicator, which will also mean turning off safe rewrites.

This function only works with CouchDB >= 1.1, since it uses the _replicator database.

#### Parameters

id | String |
callback | Function |

### startReplication(options, callback)

Replicates options.source to options.target. The strings options.source and options.target are each either a CouchDB database name or a CouchDB database URI.

If you're running behind a virtual host you'll need to set up appropriate rewrites to /_replicator, which will also mean turning off safe rewrites.

This function only works with CouchDB >= 1.1, since it uses the _replicator database.

#### Parameters

options | Object |
callback | Function |

### waitReplication(doc, [options, state_function], callback)

Waits for a replication operation to enter a specific state. waitReplication polls the _replication database using the doc provided, and evaluates state_function(doc) at each iteration. This function stops polling and invokes callback when the state_function evaluates to true. If state_function is not provided, waitReplication waits for the doc's _replication_state to change from 'triggered' to 'completed' (or 'error').

If you're running behind a virtual host you'll need to set up appropriate rewrites to /_replicator, which will also mean turning off safe rewrites.

This function only works with CouchDB >= 1.1, since it uses the _replicator database.

#### Parameters

doc | Object |
state_function | Function | (optional)
callback | Function |

### stopReplication(doc, callback, [options])

Stops a replication operation already in progress. The doc parameter can be obtained by calling getReplication.

If you're running behind a virtual host you'll need to set up appropriate rewrites to /_replicator, which will also mean turning off safe rewrites.

This function only works with CouchDB >= 1.1, since it uses the _replicator database.

#### Parameters

id | String |
callback | Function |
options | Function |

### deleteUser(username, callback)

Deletes an existing user document, given its username. You must be logged in as an administrative user for this function to succeed.

#### Parameters

username | String |
callback | Function |

### getDesignDoc(name, callback, no_cache)

Fetch a design document from CouchDB. By default, the results of this function are cached within the javascript engine. To avoid this, pass true for the no_cache argument.

#### Parameters

name |  | The name of (i.e. path to) the design document.
callback |  | The callback to invoke when the request completes.
no_cache |  | optional; true to force a cache miss for this request.

## events

The events module handles events emitted by Kanso as well as custom events defined by a Kanso app. These events can be used client-side or server-side. Although you are limited to synchronous operation on the server, so events are less likely to be useful there.

### on(name, listener)

Adds a listener function for the given event name.

#### Parameters

name | String |
listener | Function |

### once(name, listener)

Binds an event listener to the given event name, but unbinds it after its first invocation.

#### Parameters

name | String |
listener | Function |

### emit(name, [...])

Triggers any event listeners bound to the given event name. Listeners are called in the order they were bound. If a listener returns false subsequent event listeners in the chain are not called.

The first argument is the event name to emit any additional arguments are used as arguments to the bound event listeners.

#### Parameters

name | String |
... |  |

### listeners(name)

Returns an array of the bound event listeners for the given event name. If no events are bound, an empty array is returned.

#### Parameters

name | String |

Returns: Array

### removeAllListeners(name)

Removes all bound event listeners for a given event name.

#### Parameters

name | String |

### removeListener(name, listener)

Removes a specific event listener for a given event name.

#### Parameters

name | String |
listener | Function |

## fields

The building blocks of Types and Forms, Fields help to validate and authorize changes to docuemnt values.

### Field

Field objects are used when constructing content types and forms.

#### Options

- omit_empty Boolean - whether to omit the field from a document when the field is empty
- permissions Object - a permissions check function or an object containing separate functions to run on create, edit and update operations.
- validators Array - an array of validation functions (default: [])
- required Boolean - whether the field is required (default: true)

#### Parameters

options | Object |

### Field.parse(raw)

Parses a raw value returning the correct JavaScript type for this field. This will usually be overridden by other field types.

#### Parameters

raw |  |

### Field.isEmpty(value, raw)

Test values to see if field is considered empty.

This function accepts the raw value even though by default it only checks the parsed value, so that other field types overridding this method have the raw data available.

#### Parameters

value |  | the parsed value for the field
raw |  | the raw value for this field

Returns: Boolean

### Field.validate(doc, value, raw)

Run the field's validation functions against a value. Returns an array of validation errors, or an empty array if valid.

#### Parameters

doc | Object |
value |  |
raw |  |

Returns: Array

### Field.authorize(newDoc, oldDoc, newVal, oldVal, userCtx)

Check relevant field permissions to see if user is authorised to make changes. Returns an array of permissions errors, or an empty array if the changes are permissible.

#### Parameters

newDoc | Object |
oldDoc | Object |
newVal |  |
oldVal |  |
userCtx | Object |

Returns: Array

### Embedded

Embedded objects represent a Type embedded within another Type or set of Fields. Its not a true field, but like the Field constructor it acts as a marker when walking through the sub-objects that make up a schema.

Exposes the same methods as Field objects.

#### Options

- type Type Object - Required, the Type definition to embed
- omit_empty Boolean - whether to omit the field from a document when the field is empty
- permissions Object - a permissions check function or an object containing separate functions to run on create, edit and update operations.
- validators Array - an array of validation functions (default: [])
- required Boolean - whether the field is required (default: true)

#### Parameters

options | Object |

### Embedded.isEmpty(value, raw)

Test values to see if field is considered empty.

This function accepts the raw value even though by default it only checks the parsed value, so that other field types overridding this method have the raw data available.

#### Parameters

value |  | the parsed value for the field
raw |  | the raw value for this field

### Embedded.validate(doc, value, raw)

Run the type's validate function against a value. Returns an array of validation errors, or an empty array if valid.

#### Parameters

doc | Object |
value |  |
raw |  |

Returns: Array

### Embedded.authorize(newDoc, oldDoc, newVal, oldVal, user)

Check relevant type permissions to see if user is authorised to make changes. Returns an array of permissions errors, or an empty array if the changes are permissible.

#### Parameters

newDoc | Object |
oldDoc | Object |
newVal |  |
oldVal |  |
user | Object |

Returns: Array

### EmbeddedList

EmbeddedList objects represent multiple instances of a Type embedded within another Type or set of Fields. Its not a true field, but like the Field constructor it acts as a marker when walking through the sub-objects that make up a schema.

Exposes the same methods as Field objects.

#### Options

- type Type Object - Required, the Type definition to embed
- omit_empty Boolean - whether to omit the field from a document when the field is empty
- permissions Object - a permissions check function or an object containing separate functions to run on create, edit and update operations.
- validators Array - an array of validation functions (default: [])
- required Boolean - whether the field is required (default: true)

#### Parameters

options | Object |

### EmbeddedList.isEmpty(value, raw)

Test values to see if field is considered empty.

This function accepts the raw value even though by default it only checks the parsed value, so that other field types overridding this method have the raw data available.

#### Parameters

value |  | the parsed value for the field
raw |  | the raw value for this field

### EmbeddedList.missingIDs(list)

Detects embedded documents with missing _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a populated _id property.

#### Parameters

list | Array |

Returns: Array

### EmbeddedList.duplicateIDs(list)

Detects embedded documents with duplicate _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a unique _id property.

#### Parameters

list | Array |

Returns: Array

### EmbeddedList.validate(doc, value, raw)

Checks for missing or duplicate _ids then runs the type's validate function against each embedded document. Returns an array of validation errors, or an empty array if valid.

#### Parameters

doc | Object |
value |  |
raw |  |

Returns: Array

### EmbeddedList.authorize(nDoc, oDoc, nVal, oVal, user)

Check relevant type permissions to see if user is authorised to make changes. Returns an array of permissions errors, or an empty array if the changes are permissible.

#### Parameters

nDoc | Object |
oDoc | Object |
nVal |  |
oVal |  |
user | Object |

Returns: Array

### string([options])

Creates a new string Field

#### Parameters

options | Object |

### number([options])

Creates a new number Field

#### Parameters

options | Object |

### boolean([options])

Creates a new boolean Field

#### Parameters

options | Object |

### url([options])

Creates a URL Field

#### Parameters

options | Object |

### email([options])

Creates an email Field

#### Parameters

options | Object |

### creator([options])

Creates a creator Field

#### Parameters

options | Object |

### createdTime([options])

Creates a createdTime timestamp Field

#### Parameters

options | Object |

### choice([options])

Creates a choice Field

Required option: values - an array of possible choices, each an array with the first item as the value and the second as its label.

#### Parameters

options | Object |

### numberChoice([options])

Creates a number choice Field

#### Parameters

options | Object |

### embed([options])

Creates an Embedded Field

Required option: type - the Type definition to embed

#### Parameters

options | Object |

### embedList([options])

Creates an EmbeddedList Field

Required option: type - the Type definition to embed

#### Parameters

options | Object |

### array([options])

Creates a array Field. The default parse function expects a single row of comma separated values.

To accept an array of values other than strings, add a function to options called parseEach which accepts the string value for each item and performs the transformation.

#### Parameters

options | Object |

### numberArray([options])

Creates a number array Field, same as the array field only each value is parsed as a number instead of a string.

#### Parameters

options | Object |

## fieldset

Functions for dealing with collections of fields. Used by both the types and forms modules.

### createDefaults(fields, req)

Returns a hierachy of default values for a given set of Field objects

#### Parameters

fields | Object |
req | Object | the request object to pass to default_value functions

Returns: Object

### validateField(field, doc, value, raw, path)

Validate a specific field, returning all validation errors as an array with each error's field property prefixed by the current path.

#### Parameters

field | Field |
doc | Object |
value |  |
raw |  |
path | Array |

Returns: Array

### validate(fields, doc, values, raw, path, extra)

Validates an object containing fields or other sub-objects, iterating over each property and recursing through sub-objects to find all Fields.

Returns an array of validation errors, each with a field property set to the path of the field which caused the error.

#### Parameters

fields | Object |
doc | Object |
values | Object |
raw | Object |
path | Array |
extra | Boolean | whether to allow extra values not covered by a field

Returns: Array

### authField(f, nDoc, oDoc, nVal, oVal, user, path)

Authorize a specific field, returning all permissions errors as an array with each error's field property prefixed by the current path.

#### Parameters

f | Field | field object
nDoc | Object | new document
oDoc | Object | old document
nVal |  | new field value
oVal |  | old field value
user | Object | user context object
path | Array | current path

Returns: Array

### authFieldSet(f, nDoc, oDoc, nVal, oVal, user, path)

Authorizes an object containing fields or other sub-objects, iterating over each property and recursing through sub-objects to find all Fields.

Returns an array of permissions errors, each with a field property set to the path of the field which caused the error.

#### Parameters

f | Field | field object
nDoc | Object | new document
oDoc | Object | old document
nVal |  | new field value
oVal |  | old field value
user | Object | user context object
path | Array | current path
extra | Boolean | whether to raise an error on additional fields

Returns: Array

## flashmessages

Flash messages help you store state between requests, such as reporting a successful or failed operation after a redirect.

The flash message implementation in this module handles both fallback couchdb mode, using cookies to persist state between requests, as well as supporting client-side operation, correctly handling new messages even inside the callbacks of async functions.

Flash messages only persist for the next request or the next template render! That means 2 redirects without explicitly currying the flash messages will cause the messages to be lost.

### readRequestCookie(req)

Reads the flash messages cookie from a request object, returning an array of incoming messages.

#### Parameters

req | Object |

Returns: Array

### readBrowserCookie()

Reads the flash messages cookie from the browser, returning an array of incoming messages.

Returns: Array

### updateRequest(req)

Adds a flash_messages property to a request containing all incoming messages.

#### Parameters

req | Object |

Returns: Request Object

### getMessages(req)

Get's all current flash messages, stopping them from being outgoing on the next request so they're not repeated.

#### Parameters

req | Object |

Returns: Array

### getOutgoingMessages(req)

Filters all available messages on a request object, returning only those flagged as outgoing (sending in the response to be made available to the next request).

#### Parameters

req | Object |

Returns: Array

### updateResponse(req, res)

Updates a response object after a list, show or update function has returned, setting the flash messages cookie to include the outgoing messages.

#### Parameters

req | Object |
res | Object |

Returns: Response Object

### createMessage(req, msg)

Creates a new flash message object, associating it with the given request.

#### Parameters

req | Object |
msg | String |

Returns: Object

### setBrowserCookie(req, messages)

Stores a list of messages in the flash messages cookie. This function is for client-side use.

#### Parameters

req | Object |
messages | Array |

### addMessage(req, msg)

Adds a new flash message for the current request. If the list, show or update function has not returned, it's added to the response Set-Cookie header, otherwise (if its the result of a client-side async operation) it's added directly to the browsers cookies.

#### Parameters

req | Object |
msg | String |

## forms

Functions for the rendering, parsing and validation of forms.

### Form(fields | type, [doc])

Form object, presents fields and parses responses.

#### Options

exclude | Array | a list of field names to exclude
fields | Array | a subset of fields to use (inverse of excluded)

#### Parameters

fields | Object | an object literal containing fields or a Type
doc | Object | (optional) the original document being edited
options | Object | (optional) see available options above

### override(excludes, field_subset, fields, doc_a, doc_b, path)

Overrides values in doc_a with values in doc_b, only when a field is present for that value. This means properties not in fields (or in excluded fields) are retained, while properties which are covered by the fieldset are replaced.

This is used when updating the form's values with a request when its been initiated with a previous document. You shouldn't normally need to call this directly.

Returns the updated doc_a object.

#### Parameters

excludes | Array | null |
field_subset | Array | null |
Fields | Object |
doc_a | Object |
doc_b | Object |
path | Array |

Returns: Object

### Form.validate(req)

Parses a request and validates the result, binding values and errors to the form instance.

#### Parameters

req | Object |

Returns: Form

### Form.isValid()

After a form has called validate, this function will return true if the form is valid, false otherwise.

Returns: Boolean

### Form.toHTML(req, [RendererClass])

Converts current form to a HTML string, using an optional renderer class.

#### Parameters

req | Object | Kanso request object; null for most recent. (optional),{Renderer} RendererClass (optional),{Object} options An object containing widget options, whichwill ultimately be provided to each widget's toHTML method.,{Boolean} create_defaults (optional) Set this to true if you'veprovided a document in {doc}, but would still like defaultvalues to be merged in to it via createDefaults. For a field f,the default value is added to {doc} if and only if doc[f]is undefined, null, or not present. Defaults to off.

Returns: String

### Form.renderFields(renderer, fields, values, raw, err, path)

Iterates over fields and sub-objects calling the correct renderer function on each. Returns a HTML representation of the fields. Used internally by the toHTML method, you should not need to call this function directly.

#### Parameters

renderer,{Object} | Object | fields,{Object} values,{Array} errs,{Array} path,{Object} options An object containing widget options, whichwill ultimately be provided to each widget's toHTML method.

Returns: String

### formValuesToTree(form)

Transforms a flat object from a request query to a proper hierarchy of properties.

    {'one.two': 'val'} --> {one: {two: 'val'}}

#### Parameters

query | Object |

### parseRaw(fields, raw)

Transforms a raw query object from formValuesToTree to a document which follows the schema for the given type.

#### Parameters

fields | Object |
raw | Object |

Returns: Object

## path

Path functions ported from node.js to work in CouchDB and the browser. This module is used internally by Kanso, although you can use it in your apps too if you find the functions useful.

### join(path, [...])

Joins multiple paths together using '/'. Accepts a arbitrary number of strings as arguments, returning the joined result as a single string.

Returns: String

### normalizeArray(parts, [keepBlanks])

Normalizes a path split into an array, taking care of '..' and '.' parts.

#### Parameters

parts | Array |
keepBlanks | Boolean |

Returns: Array

### normalize(path, [keepBlanks])

Normalize a string path, taking care of '..' and '.' parts.

#### Parameters

path | String |
keepBlanks | Boolean |

Returns: string

### dirname(path)

Return the directory name of a path. Similar to the Unix dirname command.

#### Parameters

path | String |

Returns: String

### basename(path, ext)

Return the last portion of a path. Similar to the Unix basename command.

Example

    path.basename('/foo/bar/baz/asdf/quux.html')
    // returns
    'quux.html'

    path.basename('/foo/bar/baz/asdf/quux.html', '.html')
    // returns
    'quux'

#### Parameters

path | String |
ext | String |

Returns: String

### extname(path)

Return the extension of the path. Everything after the last '.' in the last portion of the path. If there is no '.' in the last portion of the path or the only '.' is the first character, then it returns an empty string.

    path.extname('index.html')
    // returns
    '.html'

    path.extname('index')
    // returns
    ''

#### Parameters

path | String |

Returns: String

## permissions

Permissions functions are used on both Fields and Types to check a given user is authorized to make a change to a document.

### matchUsername()

Field's new value should match current user's name

Returns: Function

### hasRole(role)

Checks if the user has a specific role

#### Parameters

role | String |

Returns: Function

### fieldUneditable()

The value of this field should never change after the document has been created.

Returns: Function

### usernameMatchesField(path)

User's name should match the old value of the given field. A field can be specified using a string or an array of strings (like a path).

    eg: usernameMatchesField('creator')
        usernameMatchesField(['meta','creator'])

        {
            creator: 'name',
            meta: {creator: 'name2'}
        }

#### Parameters

path | String | Array |

Returns: Function

### loggedIn()

Checks that user's context has a username

Returns: Function

### all(perms)

Runs an array of permissions functions and checks that all of them pass, returning all failures.

#### Parameters

perms | Array |

Returns: Function

### any(perms)

Tests to see if any one permission function passes, returning on the first success. If all permissions fail, then all errors are returned.

#### Parameters

perms | Array |

### inherit(type)

Treat new and old values like new documents of a given type, and attempt to authorize the value against the type's permissions. Useful when handling permissions for an embedded type.

Can be combined with permissions.any or permissions.all to extend the permissions for an embedded type field. For example, the following might allow both the owner of the parent document and the owner of the comment itself to remove it.

        comment: fields.embed({
            type: types.comment,
            permissions: {
                remove: permissions.any([
                    permissions.usernameMatchesField('creator'),
                    permissions.inherit(types.comment)
                ])
            }
        });

#### Parameters

type | Type |

## querystring

Querystring functions ported from node.js to work in CouchDB and the browser. This module is used internally by Kanso, although you can use it in your apps too if you find the functions useful.

### unescape(str)

Decodes a URI Component, provided so that it could be overridden if necessary.

#### Parameters

str | String |

Returns: String

### escape(str)

Encodes a URI Component, provided so that it could be overridden if necessary.

#### Parameters

str | String |

Returns: String

### stringify(obj, [sep, eq, name])

Serialize an object to a query string. Optionally override the default separator and assignment characters.

Example:

    querystring.stringify({foo: 'bar'})
    // returns
    'foo=bar'

    querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
    // returns
    'foo:bar;baz:bob'

#### Parameters

obj | Object |
sep | String |
eq | String |
name | String |

Returns: String

### decode(qs, [sep, eq])

Deserialize a query string to an object. Optionally override the default separator and assignment characters.

Example:

    querystring.parse('a=b&b=c')
    // returns
    // { a: 'b', b: 'c' }

#### Parameters

qs | String |
sep | String |
eq | String |

Returns: Object

## render

Renderer constructors and general utilities for rendering Form objects as HTML.

### errorHTML(errors)

Renders HTML for error messages.

#### Parameters

errors | Array |

Returns: String

### labelText(field, name)

Generates the text for a field's label, depending on whether a custom label is defined or not. If not, the name is captialized and underscores are replaces with spaces to produce the label's text.

#### Parameters

field | Object |
name | String |

Returns: String

### labelHTML(field, name, id)

Generates HTML for label tags.

#### Parameters

field | Object |
name | String |
id | String |

Returns: String

### descriptionHTML(obj)

Generates HTML for field descriptions (if defined).

#### Parameters

obj | Object |

Returns: String

### hintHTML(obj)

Generates HTML for field hints (if defined).

#### Parameters

obj | Object |

Returns: String

### classes(field, errors)

Creates an array of default class names for a field. This includes 'required' for required fields and 'error' for fields failing validation.

All fields are given a 'field' class.

#### Parameters

field | Object |
errors | Array |

Returns: Array

### defaultRenderer()

Determines the default renderer class, to be used globally by instances of forms.Form that fail to specify a renderer class.

Returns: Function

### table

The default table renderer class, passed to the toHTML method of a form. Renders a form using a single table, with

tags to represent nested field groups. The
s are labelled with specific CSS classes, including depth information. See style.css for details on how to style this output.

## sanitize

Input sanitization, escaping, and construction functions covering security-sensitive areas.

### escapeHtml(s)

Encodes required characters as HTML entities so a string can be included in a page. This function must be used to avoid Cross-site Scripting attacks.

#### Parameters

s | String |

Returns: String

### escapeJavascriptString(s)

Encodes selected characters in a string, so that the string can be safely used within a Javascript string constant. This function must be used to avoid cross-site scripting attacks (or, in some cases, arbitrary server-side code execution).

#### Parameters

s | String |

Returns: String

### escapeJavascriptString(s)

Encodes selected characters in a string, so that the string can be safely used within an XML character data section. This function must be used to avoid cross-site scripting attacks.

#### Parameters

s | String |

Returns: String

### generateDomIdentifier(s)

Takes any number of arguments, and combines them together to safely form a string that's suitable for use as a DOM element identifier.

#### Parameters

s | String |

Returns: String

### generateDomName(s)

Takes any number of arguments, and combines them together to safely form a string that's suitable for use in a DOM element's name attribute.

#### Parameters

s | String |

Returns: String

## session

Functions related to the management of user sessions and account information.

### fakeRequest(userCtx, callback)

Creates a fake request to /_session to pass to sessionChange, useful when using functions such as templates.render

#### Parameters

userCtx | Object |
callback | Function |

### sessionChange(userCtx, callback)

Calls sessionChange if exported from the currently loaded app.

#### Parameters

userCtx | Object |
callback | Function |

### logout(callback)

Logs out the current user.

#### Parameters

callback | Function |

### login(username, password, callback)

Attempt to login using the username and password provided.

#### Parameters

username | String |
password | String |
callback | Function |

### info(callback)

Returns the current user's session information.

#### Parameters

callback | Function |

### userDb(callback)

Returns the authentication database for the current user's session.

#### Parameters

callback | Function |

### signup(username, password, callback)

Creates a new user document with given username and password.

#### Parameters

username | String |
password | String |
callback | Function |

## settings

The settings module is automatically generated by Kanso and contains the settings defined in your app's kanso.json configuration file.

## sha1

A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined in FIPS PUB 180-1. This module is used to hash user passwords in a way that's compatible with CouchDB.

This module is Copyright Paul Johnston 2000 - 2002 and distributed under the BSD License. See http://pajhome.org.uk/crypt/md5 for details.

### hex(s)

Hashes a string using SHA1 and returns a hex representation of it.

#### Parameters

s | String |

Returns: String

### base64(s)

Hashes a string using SHA1 and returns a base64 representation of it.

#### Parameters

s | String |

Returns: String

### str(s)

Hashes a string using SHA1 and returns a string representation of it.

#### Parameters

s | String |

Returns: String

### hex_hmac(key, data)

Calculates the HMAC-SHA1 of a key and some data, returning a hex representation of it.

#### Parameters

key | String |
data | String |

Returns: String

### base64_hmac(key, data)

Calculates the HMAC-SHA1 of a key and some data, returning a base64 representation of it.

#### Parameters

key | String |
data | String |

Returns: String

### str_hmac(key, data)

Calculates the HMAC-SHA1 of a key and some data, returning a string representation of it.

#### Parameters

key | String |
data | String |

Returns: String

## templates

Kanso uses Dust templates for rendering pages. To learn more about the syntax, see the Dust site.

Since Dust stores compiled templates on the module itself, the templates module does some interesting things to work around the lack of a module cache in CouchDB. Because of this, compiled templates are automatically added to this module from your templates folder each time your app is pushed to CouchDB. You can see a list of the loaded template names on the 'loaded' property of this module.

### render(name, req, context)

Synchronously render dust template and return result, automatically adding baseURL to the template's context. The request object is required so we can determine the value of baseURL.

#### Parameters

name | String |
req | Object |
context | Object |

Returns: String

## types

Document types can be used to ease the validation of updates and check permissions when creating, editing or deleting documents.

### Type(name, options)

Creates a new Type object

#### Options

- fields Object - Field objects to use as the Types's schema
- permissions Object - a permissions check function or an object containing separate functions to run on add, remove and update operations.
- display_name Function|String|Array - name to be used when displaying the document in the admin tool. A string or array will become the property to display. A function should take the document as a object and return the display name.

#### Parameters

options | Object |

### Type.validate(doc, rawDoc)

Run field validators against document and check for missing required fields or extra fields when the Types's allow_extra_fields property is set to false.

#### Parameters

doc | Object |
rawDoc | Object |

Returns: Array

### Type.authorize(nDoc, oDoc, user)

Run field permissions checks against userCtx and document.

#### Parameters

nDoc | Object | new document
oDoc | Object | old document
userCtx | Object | user context object

Returns: Array

### Type.authorizeTypeLevel(nDoc, oDoc, user)

Runs top type-level permissions checks only.

#### Parameters

nDoc | Object | new document
oDoc | Object | old document
userCtx | Object | user context object

Returns: Array

### Type.create(userCtx, callback)

Create's a new object for this Type. Pre-filling any default values and providing a new _id value. This is a convenient function to use when creating a type to embed within another.

#### Parameters

userCtx | Object |
callback | Function |

### validate_doc_update(types, newDoc, oldDoc, userCtx)

Calls validation and permissions functions relevant to a document update. This should be called from your app's exported validate_doc_update function if you wish to use kanso Types in you project.

Throws on error.

#### Parameters

types | Object |
newDoc | Object |
oldDoc | Object |
userCtx | Object |

## underscore

Used by Kanso internally, the excellent Underscore.js library is also included in the standard set of CommonJS modules pushed with your app.

For more information on the Underscore.js API, see the website: http://documentcloud.github.com/underscore/

## url

URL functions ported from node.js to work in CouchDB and the browser. This module is used internally by Kanso, although you can use it in your apps too if you find the functions useful.

### parse(url, [parseQueryString, slashesDenoteHost])

Take a URL string, and return an object. Pass true as the second argument to also parse the query string using the querystring module.

#### Parameters

url | String |
parseQueryString | Boolean |
slashesDenoteHost | Boolean |

Returns: Object

### format(obj)

Take a parsed URL object, and return a formatted URL string.

#### Parameters

obj | Object |

### resolve(source, relative)

Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

#### Parameters

source | String |
relative | String |

Returns: String

## utils

General utility functions used by Kanso. Some functions were moved here from other modules (such as core), to avoid a circular dependency bug in CouchDB.

This module also stores some useful properties such as 'isBrowser', which is true if the code is running in a browser environment, and 'initial_hit' which is set to true when a page is first requested from CouchDB (and set to false for subsequent requests).

### getBaseURL(req)

Returns the path to prefix to any URLs. When running behind a virtual host, there is nothing to prefix URLs with. When accessing the app directly, URLs need to be prefixed with /db/_design/appname/_rewrite.

The request object argument is only required when run server-side, but its a good idea to include it whenever you call getBaseURL.

#### Parameters

req | Object |

Returns: String

### getPropertyPath(obj, path)

Traverses an object and its sub-objects using an array of property names. Returns the value of the matched path, or undefined if the property does not exist.

If a string if used for the path, it is assumed to be a path with a single key (the given string).

    getPropertyPath({a: {b: 'foo'}}, ['a','b']) -> 'foo'
    getPropertyPath({a: {b: 'foo'}}, 'a') -> {b: 'foo'}

#### Parameters

obj | Object |
path | Array|String |

### setPropertyPath(obj, path, val)

Traverses an object and its sub-objects using an array of property names. Sets the value of the matched property.

If a string if used for the path, it is assumed to be a path with a single key (the given string).

    setPropertyPath({}, ['a','b'], 'foo') -> {a: {b: 'foo'}}
    setPropertyPath({}, 'a', 'foo') -> {a: 'foo'}

#### Parameters

obj | Object |
path | Array|String |

### escapeHTML(s)

Encodes required characters as HTML entities so a string can be included in a page.

#### Parameters

s | String |

Returns: String

### parseCSV(csvString)

Parse CSV strings into an array of rows, each row an array of values. Used by the array field's default CSV widget.

#### Parameters

csvString | String |

Returns: Array

### redirect(req, url)

Creates CouchDB response object for returning from a show, list or update function, which redirects to the given app url (automatically prepending the baseURL)

#### Parameters

req | Object |
url | String |

Returns: Object

### isSubPath(a, b)

Tests if path b is equal to or a sub-path of a.

#### Parameters

a | Array |
b | Array |

Returns: Boolean

### titleize(str)

Return a title-case version of the supplied string.

#### Parameters

str |  | The string to transform.

Returns: String

### bindContext(context, closure)

Returns a function that executes {closure} in the context of {context}. Use this function if you'd like to preserve the current context across callbacks, event handlers, and other cases where the value of {this} is set for you.

#### Parameters

context | Object | The context to use when executing closure.Usually, you will specify the current value of 'this'.
closure | Function | The function to to bind to {context}.

## validators

Validation functions used to validate Field contents.

### min(min)

Tests that the field's value is greater than 'min'.

#### Parameters

min | Number |

Returns: Function

### max(max)

Tests that the field's value is less than 'max'

#### Parameters

max | Number |

Returns: Function

### range(min, max)

Tests that the field's value is greater than 'min' AND less than 'max'

#### Parameters

min | Number |
max | Number |

Returns: Function

### minlength(val)

Tests that the field's value length is greater than 'val'

#### Parameters

val | Number |

Returns: Function

### maxlength(val)

Tests that the field's value length is less than 'val'

#### Parameters

val | Number |

Returns: Function

### rangelength(min, max)

Tests that the field's value length is greater than 'min' AND less than 'max'

#### Parameters

min | Number |
max | Number |

Returns: Function

### regexp(re, message)

Tests field's value against a regular expression

#### Parameters

re | RegExp | can be a string or RegExp object
message | String | (optional) a custom error message to throw

Returns: Function

### email()

Tests that field's value is a valid email address using a regular expression.

Returns: Function

### url()

Tests that field's value is a valid URL using a regular expression.

Returns: Function

### missingIDs()

Detects embedded documents with missing _id properties and returns an array of Error objects for each occurence. Returns an empty array if all documents have a populated _id property.

Used by the EmbeddedList field type.

#### Parameters

doc | Object |
value | Array |

Returns: Array

## widgets

Widgets define the way a Field object is displayed when rendered as part of a Form. Changing a Field's widget will be reflected in the admin app.

### Widget(type, [options])

Widget constructor, creates a new Widget object.

#### Parameters

type | String |
options | Object |

Returns: Widget Object

### Widget.toHTML(name, value, raw, field, options)

Converts a widget to HTML using the provided name and parsed and raw values

#### Parameters

name | String |
value |  |
raw |  |
field |  |
options |  |

Returns: String

### Widget.clientInit(path, value, raw, field, options)

Initializes a widget on the client-side only, using the browser's script interpreter. This function is guaranteed to be called after toHTML, and any DOM elements created by toHTML are guaranteed to be accessible

#### Parameters

path | Array |
value |  |
raw |  |
field |  |
options |  |

Returns: Boolean

### Widget.updateName(path)

Called by Kanso when it becomes necessary to rename this widget instance. The widget should respond by updating the id and name attributes.

#### Parameters

elt | String | An element that contains one ormore instances of the widget referenced by `this'.,{String} path The widget's new path; combine this usingthe _name or _id function to generate a usable string.,{Object} options A new set of toHTML/clientInit options.This may or may not influence the widget's name.

### Widget.updateValue(elt, path, value, options)

Called by Kanso when it becomes necessary to rename this widget instance. The widget should respond by updating the value attribute.

#### Parameters

elt | String | An element that contains one ormore instances of the widget referenced by `this'.
path | String | The path to the widget.
value | Object | The new value for the widget, unencoded.
options | Object | An up-to-date set of toHTML/clientInit options.

### Widget.getValue(elt, path, options)

Called by Kanso when it becomes necessary to interrogate this widget to determine its value. The widget should respond by returning an unencoded value (typically as an object).

#### Parameters

elt | String | An element that contains one ormore instances of the widget referenced by `this'.
path | String | The path to the widget.
options | Object | An up-to-date set of toHTML/clientInit options.

### Widget.validate(elt, path, options)

Called by Kanso when it becomes necessary to validate the contents of this widget -- i.e. to ensure it's in a consistent state before using its value or proceeding. Most widgets will not implement this method; its primary use is complex widgets that host validation-enabled forms and/or types. Returns true if the contents is consistent and valid; false otherwise.

#### Parameters

elt | String | An element that contains one ormore instances of the widget referenced by `this'.
path | String | The path to the widget.
options | Object | An up-to-date set of toHTML/clientInit options.

### text([options])

Creates a new text input widget.

#### Parameters

options |  |

Returns: Widget Object

### password([options])

Creates a new password input widget.

#### Parameters

options |  |

Returns: Widget Object

### hidden([options])

Creates a new hidden input widget.

#### Parameters

options |  |

Returns: Widget Object

### textarea([options])

Creates a new textarea widget.

#### Parameters

options |  |

Returns: Widget Object

### checkbox([options])

Creates a new checkbox widget.

#### Parameters

options |  |

Returns: Widget Object

### select([options])

Creates a new select widget.

#### Parameters

options |  |

Returns: Widget Object

### computed([options])

Creates a new computed widget. Computed widgets display a string, but are uneditable, working as a hidden field behind the scenes.

#### Parameters

options |  |

Returns: Widget Object

### creator([options])

Creates a new computed input widget which sets the value of the field to the current user on new documents, responding to sessionChange events

#### Parameters

options |  |

Returns: Widget Object

### embedded([options])

Creates a new field for storing/displaying an embedded object. This is automatically added to embed and embedList field types that don't specify a widget.

#### Parameters

options |  |

Returns: Widget Object

### defaultEmbedded([options])

Creates a new field for storing/displaying an embedded object. This is automatically added to embed and embedList field types that don't specify a widget.

#### Parameters

options |  |

Returns: Widget Object

### embedForm([options])

Creates a new instance of an embedded form for the specified type. This is the basis for the presentation of complex data types in Kanso, and is used within an embedList to add and/or edit items.

#### Parameters

options |  |

Returns: Widget Object