<template name="api">
{{#better_markdown}}

The Meteor API

Your Javascript code can run in two environments: the client
(browser), and the server (a Node.js container on a server).  For
each function in this API reference, we'll indicate if the function is
available just on the client, just on the server, or *Anywhere*.

Meteor Core

{{> api_box isClient}}
{{> api_box isServer}}
{{> api_box startup}}

On a server, the function will run as soon as the server process is
finished starting. On a client, the function will run as soon as the DOM
is ready and any `<body>` templates from your `.html` files have been
put on the screen.

    // On server startup, if the database is empty, create some initial data.
    if (Meteor.isServer) {
      Meteor.startup(function () {
        if (Rooms.find().count() === 0) {
          Rooms.insert({name: "Initial room"});
        }
      });
    }

{{> api_box absoluteUrl}}

Publish and subscribe

These functions control how Meteor servers publish sets of records and
how clients can subscribe to those sets.

{{> api_box publish}}

To publish records to clients, call `Meteor.publish` on the server with
two parameters: the name of the record set, and a *publish function*
that Meteor will call each time a client subscribes to the name.

Publish functions can return a
[`Collection.Cursor`](#meteor_collection_cursor), in which case Meteor
will publish that cursor's documents.

    // server: publish the rooms collection, minus secret info.
    Meteor.publish("rooms", function () {
      return Rooms.find({}, {fields: {secretInfo: false}});
    });

Otherwise, the publish function can set and unset
individual record attributes on a client, use these methods provided by
`this` in your publish function.

In particular, if you use observe() to watch changes to the database, be
sure to call `this.flush` from inside your observe callbacks.  Methods
that update the database are considered finished when the observe
callbacks return.

Example:

    // server: publish the current size of a collection
    Meteor.publish("counts-by-room", function (roomId) {
      var self = this;
      var uuid = Meteor.uuid();
      var count = 0;

      var handle = Messages.find({roomId: roomId}).observe({
        added: function (doc, idx) {
          count++;
          self.set("counts", uuid, {roomId: roomId, count: count});
          self.flush();
        },
        removed: function (doc, idx) {
          count--;
          self.set("counts", uuid, {roomId: roomId, count: count});
          self.flush();
        }
        // don't care about moved or changed
      });

      // remove data and turn off observe when client unsubs
      self.onStop(function () {
        handle.stop();
        self.unset("counts", uuid, ["roomId", "count"]);
        self.flush();
      });
    });

    // client: declare collection to hold count object
    Counts = new Meteor.Collection("counts");

    // client: autosubscribe to the count for the current room
    Meteor.autosubscribe(function () {
      Meteor.subscribe("counts-by-room", Session.get("roomId"));
    });

    // client: use the new collection
    console.log("Current room has " + Counts.findOne().count + " messages.");

{{#warning}}
Meteor will emit a warning message if you call `Meteor.publish` in a
project that includes the `autopublish` package.  Your publish function
will still work.
{{/warning}}

{{> api_box subscription_set}}
{{> api_box subscription_unset}}
{{> api_box subscription_complete}}
{{> api_box subscription_flush}}

{{> api_box subscription_onStop}}

If you call [`observe`](#observe) in your publish handler, this
is the place to stop the observes.

{{> api_box subscription_stop}}

{{> api_box subscribe}}

When you subscribe to a record set, it tells the server to send records
to the client.  The client stores these records in local Minimongo
collections, with the same name as the `collection` argument to `set`.
Meteor will queue incoming attributes until you declare the
`Meteor.Collection` on the client with the matching collection name.

    // okay to subscribe (and possibly receive data) before declaring
    // the client collection that will hold it.  assume "allplayers"
    // publishes data from server's "players" collection.
    Meteor.subscribe("allplayers");
    ...
    // client queues incoming players records until ...
    ...
    Players = new Meteor.Collection("players");

If more than one subscription sends conflicting values for an attribute
(same collection name, document ID, and attribute name), then the value
on the client will be that from the *first* subscription the client
activated.  (Even if it is not the first to send the duplicated
attribute.)

If all of the attributes in a document are removed, Meteor
will remove the (now empty) document.  If you want to publish empty
documents, just use a placeholder attribute.

    // Clicks.insert({exists: true});

{{> api_box autosubscribe}}

`func` will be run immediately, and while it runs,
records will be kept of the subscriptions it makes
(via [`Meteor.subscribe`](#meteor_subscribe)) and the data it uses
(including calls to [`Session.get`](#session_get)
and [`collection.find`](#find)).

Whenever the used data changes, the subscriptions will be cancelled and
`func` will be re-run to make replacement subscriptions.
`Meteor.autosubscribe` will automatically stop the old subscription.
It's not necessary to call `stop` on subscriptions made from inside
`Meteor.autosubscribe`.

Example:

    // Subscribe to the chat messages in the current room. Automatically
    // update the subscription whenever the current room changes.
    Meteor.autosubscribe(function () {
      Meteor.subscribe("chat", {room: Session.get("current-room");});
    });

Methods

Methods are remote functions that Meteor clients can invoke.

{{> api_box methods}}

Example:

    Meteor.methods({
      foo: function (arg1, arg2) {
        // .. do stuff ..
        if (you want to throw an error)
          throw new Meteor.Error(404, "Can't find my pants");
        return "some return value";
      },

      bar: function () {
        // .. do other stuff ..
        return "baz";
      }
    });

Calling `methods` on the server defines functions that can be called
remotely by clients.  They should return a value or throw an exception.
Inside your method invocation, `this` is bound to a method invocation
object, which provides the following:

* `isSimulation`: a boolean value, true if this invocation is a stub.
* `unblock`: when called, allows the next method from this client to
begin running.

Calling `methods` on the client defines *stub* functions associated with
server methods of the same name.  You don't have to define a stub for
your method if you don't want to.  In that case, method calls are just
like remote procedure calls in other systems, and you'll have to wait
for the results from the server.

If you do define a stub, when a client invokes a server method it will
also run its stub in parallel.  On the client, the return value of a
stub is ignored.  Stubs are run for their side-effects: they are
intended to *simulate* the result of what the server's method will do,
but without waiting for the round trip delay.  If a stub throws an
exception it will be logged to the console.

{{> api_box method_invocation_isSimulation}}

{{> api_box method_invocation_unblock}}

On the server, methods from a given client run one at a time. The N+1th
invocation from a client won't start until the Nth invocation
returns. However, you can change this by calling `this.unblock`. This
will allow the N+1th invocation to start running in a new fiber.

{{> api_box error}}

If you want to return an error from a method, throw an exception.
Methods can throw any kind of exception.  But `Meteor.Error` is the only
kind of error that a server will send to the client.  If a method
function throws a different exception, then it will be mapped to
`Meteor.Error(500, "Internal server error")` on the wire.

{{> api_box meteor_call}}

This is how to invoke a method.  It will run the method on the server.
If a stub is available, it will also run the stub on the client.

If you include a callback function as the last argument (which can't be
an argument to the method, since functions aren't serializeable), the
method will run asynchronously: it will return nothing in particular and
will not throw an exception.  When the method is complete (which may or
may not happen before `Meteor.call` returns), the callback will be
called with two arguments: `error` and `result`. If an error was thrown,
then `error` will be the exception object.  Otherwise, `error` will be
undefined and the return value (possibly undefined) will be in `result`.

    // async call
    Meteor.call('foo', 1, 2, function (error, result) { ... } );

If you do not pass a callback on the server, the method invocation will
block until the method is complete.  It will eventually return the
return value of the method, or it will throw an exception if the method
threw an exception. (Possibly mapped to 500 Server Error if the
exception happened remotely and it was not a `Meteor.Error` exception.)

    // sync call
    var result = Meteor.call('foo', 1, 2);

On the client, if you do not pass a callback and you are not inside a
stub, `call` will return `undefined`, and you will have no way to get
the return value of the method. That is because the client doesn't have
fibers, so there is not actually any way it can block on the remote
execution of a method.

Finally, if you are inside a stub on the client and call another
method, the other method is not executed (no RPC is generated, nothing
"real" happens.)  If that other method has a stub, that stub stands in
for the method and is executed. The method call's return value is the
return value of the stub function.  The client has no problem executing
a stub synchronously, and that is why it's okay for the client to use
the synchronous `Meteor.call` form from inside a method body, as
described earlier.

You use this functionality all the time, because the database mutators
(`insert`, `update`, `remove`) are essentially methods. When you call
them on the client (whether from inside a method or at top level), you're
invoking their stub versions that update the local cache, instead of
their "real" versions that update the database (using credentials known
only to the server.)

{{> api_box meteor_apply}}

`Meteor.apply` is just like `Meteor.call`, but it allows the
arguments to be passed as an array.

Server connections

These functions manage and inspect the network connection between the
Meteor client and server.

{{> api_box status}}

This method returns the status of the connection between the client and
the server. The return value is an object with the following fields:

connected
  Boolean

True if currently connected to the server. If false, changes and
  method invocations will be queued up until the connection is
  reestablished.

status
  String

Describes the current reconnection status. The possible
  values are connected (the connection is up and
  running), connecting (disconnected and trying to open a
  new connection), and waiting (failed to connect and
  waiting to try to reconnect).

retryCount
  Number

The number of times the client has tried to reconnect since the
  connection was lost. 0 when connected.

retryTime
  Number or undefined

The estimated time of the next reconnection attempt. To turn this
  into an interval until the next reconnection, use
  retryTime - (new Date()).getTime(). This key will
  be set only when status is waiting.

Instead of using callbacks to notify you on changes, this is
a reactive data source. You can use it in a
template or invalidation
context to get realtime updates.

{{> api_box reconnect}}

{{> api_box connect}}

To call methods on another Meteor application or subscribe to its data
sets, call `Meteor.connect` with the URL of the application.
`Meteor.connect` returns an object which provides:

* `subscribe` -
  Subscribe to a record set. See
  Meteor.subscribe.
* `call` -
  Invoke a method. See Meteor.call.
* `apply` -
  Invoke a method with an argument array. See
  Meteor.apply.
* `methods` -
  Define client-only stubs for methods defined on the remote server. See
  Meteor.methods.
* `status` -
  Get the current connection status. See
  Meteor.status.
* `reconnect` -
  See Meteor.reconnect.
* `onReconnect` - Set this to a function to be called as the first step of
  reconnecting. This function can call methods which will be executed before
  any other outstanding methods. For example, this can be used to re-establish
  the appropriate authentication context on the new connection.

By default, clients open a connection to the server from which they're loaded.
When you call `Meteor.subscribe`, `Meteor.status`, `Meteor.call`, and
`Meteor.apply`, you are using a connection back to that default
server.

{{#warning}}
In this release, `Meteor.connect` can only be called on the client.
Servers can not yet connect to other servers.
{{/warning}}

Collections

Meteor stores data in *collections*.  To get started, declare a
collection with `new Meteor.Collection`.

{{> api_box meteor_collection}}

Calling this function is analogous to declaring a model in an
traditional ORM (Object-Relation Mapper)-centric framework. It sets up a
*collection* (a storage space for records, or "documents") that can be
used to store a particular type of information, like users, posts,
scores, todo items, or whatever matters to your application.  Each
document is a JSON object.  It includes an `_id` property whose value is
unique in the collection, which Meteor will set when you first create
the document.

    // common code on client and server declares livedata-managed mongo
    // collection.
    Chatrooms = new Meteor.Collection("chatrooms");
    Messages = new Meteor.Collection("messages");

The function returns an object with methods to [`insert`](#insert)
documents in the collection, [`update`](#update) their properties, and
[`remove`](#remove) them, and to [`find`](#find) the documents in the
collection that match arbitrary criteria. The way these methods work is
compatible with the popular Mongo database API.  The same database API
works on both the client and the server (see below).

    // return array of my messages
    var myMessages = Messages.find({userId: Session.get('myUserId')}).fetch();

    // create a new message
    Messages.insert({text: "Hello, world!"});

    // mark my first message as "important"
    Messages.update(myMessages[0].id, {$set: {important: true}});

If you pass a `name` when you create the collection, then you are
declaring a persistent collection — one that is stored on the
server and seen by all users. Client code and server code can both
access the same collection using the same API.

Specifically, when you pass a `name`, here's what happens:

* On the server, a collection with that name is created on a backend
Mongo server. When you call methods on that collection on the server,
they translate directly into normal Mongo operations.

* On the client, a Minimongo instance is
created. Minimongo is essentially an in-memory, non-persistent
implementation of Mongo in pure JavaScript. It serves as a local cache
that stores just the subset of the database that this client is working
with. Queries on the client ([`find`](#find)) are served directly out of
this cache, without talking to the server.

* When you write to the database on the client ([`insert`](#insert),
[`update`](#update), [`remove`](#remove)), the command is executed
immediately on the client, and, simultaneously, it's shipped up to the
server and executed there too.  The `livedata` package is
responsible for this.

If you pass `null` as the `name`, then you're creating a local
collection. It's not synchronized anywhere; it's just a local scratchpad
that supports Mongo-style [`find`](#find), [`insert`](#insert),
[`update`](#update), and [`remove`](#remove) operations.  (On both the
client and the server, this scratchpad is implemented using Minimongo.)

By default, Meteor automatically publishes every document in your
collection to each connected client.  To turn this behavior off, remove
the package:

    $ meteor remove autopublish

{{#warning}}
Currently the client is given full write access to the collection. They
can execute arbitrary Mongo update commands. Once we build
authentication, you will be able to limit the client's direct access to
insert, update, and remove.  We are also considering validators and
other ORM-like functionality.
{{/warning}}

    // Create a collection called Posts and put a document in it. The
    // document will be immediately visible in the local copy of the
    // collection. It will be written to the server-side database
    // a fraction of a second later, and a fraction of a second
    // after that, it will be synchronized down to any other clients
    // that are subscribed to a query that includes it (see
    // Meteor.subscribe and autopublish)
    Posts = new Meteor.Collection("posts");
    Posts.insert({title: "Hello world", body: "First post"});

    // Changes are visible immediately -- no waiting for a round trip to
    // the server.
    assert(Posts.find().count() === 1);

    // Create a temporary, local collection. It works just any other
    // collection, but it doesn't send changes to the server, and it
    // can't receive any data from subscriptions.
    Scratchpad = new Meteor.Collection;
    for (var i = 0; i < 10; i++)
      Scratchpad.insert({number: i * 2});
    assert(Scratchpad.find({number: {$lt: 9}}).count() === 5);

{{#warning}}
In this release, Minimongo has some limitations:

* `$elemMatch` is not supported in selectors.
* `$pull` in modifiers can only accept certain kinds
of selectors.
* In selectors, dot notation and ordinal indexing may not work correctly.
* `$` to denote the matched array position is not
supported in modifier.
* Sort does not support subkeys (you can sort on `a`,
but not `a.b`.)
* `findAndModify`, upsert, aggregate functions, and
map/reduce aren't supported.
* The supported types are String, Number, Boolean, Array,
and Object.

All of these will be addressed in a future release. For full
Minimongo release notes, see packages/minimongo/NOTES
in the repository.
{{/warning}}

{{#warning}}
Minimongo currently doesn't have indexes. This will come soon. It's
usually not an issue, since there usually isn't that much data in
the client — it is not that common for developers to implement
indexes in their client-side models anyway.
{{/warning}}

{{> api_box find}}

`find` returns a cursor.  It does not immediately access the database or
return documents.  Cursors provide `fetch` to return all matching
documents, `map` and `forEach` to iterate over all matching
documents, and `observe` to register callbacks when the set of
matching documents changes.

{{#warning}}
Collection cursors are not query snapshots.  If the database changes
between calling `Collection.find` and fetching the
results of the cursor, or while fetching results from the cursor,
those changes may or may not appear in the result set.
{{/warning}}

Cursors are a reactive data source.  The first time you retrieve a
cursor's documents with `fetch`, `map`, or `forEach` inside a
reactive context (eg, [`Meteor.render`](#meteor_render),
[`Meteor.autosubscribe`](#meteor_autosubscribe), Meteor will register a
dependency on the underlying data.  Any change to the collection that
changes the documents in a cursor will trigger a recomputation.  To
disable this behavior, pass `{reactive: false}` as an option to
`find`.

{{> api_box findone}}

Equivalent to `find(selector, options).fetch()[0]`.

{{> api_box insert}}

Add a document to the collection. A document is just an object, and
its fields can contain any combination of JSON-compatible datatypes
(arrays, objects, numbers, strings, null, true, and false).

`insert` will generate a unique ID for the object you pass, insert it
in the database, and return the ID.

On the server, if you don't provide a callback, then `insert` blocks
until the database acknowledges the write, or throws an exception if
something went wrong.  If you do provide a callback, `insert` still
returns the ID immediately.  Once the insert completes (or fails), the
callback is called with error and result arguments.  In an error case,
`result` is undefined.  If the insert is successful, `error` is
undefined and `result` is the new document ID.

On the client, `insert` never blocks.  If you do not provide a callback
and the insert fails on the server, then Meteor will log a warning to
the console.  If you provide a callback, Meteor will call that function
with `error` and `result` arguments.  In an error case, `result` is
undefined.  If the insert is successful, `error` is undefined and
`result` is the new document ID.

Example:

    var groceriesId = Lists.insert({name: "Groceries"});
    Items.insert({list: groceriesId, name: "Watercress"});
    Items.insert({list: groceriesId, name: "Persimmons"});

{{> api_box update}}

Modify documents that match `selector` as
given by `modifier` (see modifier
documentation).  By default, modify only one matching document.
If `multi` is true, modify all matching documents.

Instead of a selector, you can pass a string, which will be
interpreted as an `_id`.

On the server, if you don't provide a callback, then `update` blocks
until the database acknowledges the write, or throws an exception if
something went wrong.  If you do provide a callback, `update` returns
immediately.  Once the update completes, the callback is called with a
single error argument in the case of failure, or no arguments if the
update was successful.

On the client, `update` never blocks.  If you do not provide a callback
and the update fails on the server, then Meteor will log a warning to
the console.  If you provide a callback, Meteor will call that function
with an error argument if there was an error, or no arguments if the
update was successful.

Example:

    // Give the "Superlative" badge to each user with a score greater than
    // 10. If they are logged in and their badge list is visible on the
    // screen, it will update automatically as they watch.
    Users.update({score: {$gt: 10}},
                 {$addToSet: {badges: "Superlative"}},
                 {multi: true});

{{#warning}}
The Mongo `upsert` feature is not implemented.
{{/warning}}

{{> api_box remove}}

Find all of the documents that match `selector` and delete them from the
collection. Or instead of a selector, you may pass a string, to delete
the document with that `_id`.  As a safety measure, do nothing if the
selector is undefined.  If the selector is `{}`, remove all the
documents from the collection.)

On the server, if you don't provide a callback, then `remove` blocks
until the database acknowledges the write, or throws an exception if
something went wrong.  If you do provide a callback, `remove` returns
immediately.  Once the remove completes, the callback is called with a
single error argument in the case of failure, or no arguments if the
update was successful.

On the client, `remove` never blocks.  If you do not provide a callback
and the remove fails on the server, then Meteor will log a warning to
the console.  If you provide a callback, Meteor will call that function
with an error argument if there was an error, or no arguments if the
update was successful.

Example:

    // Delete all users with a karma of less than -2.
    Users.remove({karma: {$lt: -2}});

    // Delete all the log entries
    Logs.remove({});

Cursors

To create a cursor, use [`find`](#find).  To access the documents in a
cursor, use [`forEach`](#foreach), [`map`](#map), or [`fetch`](#fetch).

{{> api_box cursor_foreach}}

When called in a reactive context, `forEach` registers dependencies on
the matching documents.

Examples:

    // Print the titles of the five top-scoring posts
    var topPosts = Posts.find({}, {sort: {score: -1}, limit: 5});
    var count = 0;
    topPosts.forEach(function (post) {
      console.log("Title of post " + count + ": " + post.title);
      count += 1;
    });

{{> api_box cursor_map}}

When called in a reactive context, `map` registers dependencies on
the matching documents.

On the server, if `callback` yields, other calls to `callback` may occur while
the first call is waiting. If strict sequential execution is necessary, use
`forEach` instead.

{{> api_box cursor_fetch}}

When called in a reactive context, `fetch` registers dependencies on
the matching documents.

{{> api_box cursor_count}}

    // Display a count of posts matching certain criteria. Automatically
    // keep it updated as the database changes.
    var frag = Meteor.render(function () {
      var highScoring = Posts.find({score: {$gt: 10}});
      return "
There are " + highScoring.count() + " posts with " +
        "scores greater than 10
";
    });
    document.body.appendChild(frag);

Unlike the other functions, `count` registers a dependency only on the
number of matching documents.  (Updates that just change or reorder the
documents in the result set will not trigger a recomputation.)

{{> api_box cursor_rewind}}

The `forEach`, `map`, or `fetch` methods can only be called once on a
cursor.  To access the data in a cursor more than once, use `rewind` to
reset the cursor.

{{> api_box cursor_observe}}

Establishes a *live query* that notifies callbacks on any change to the
query result.

`callbacks` may have the following functions as properties:

{{#dtdd "added(document, beforeIndex)"}}
A new document entered the result set. It was inserted
immediately before the document currently at the
position `beforeIndex`. Or if it was inserted at the end
of the list, `beforeIndex` will be equal to the (prior)
length of the list.
{{/dtdd}}

{{#dtdd "changed(newDocument, atIndex, oldDocument)"}}
The contents of the document at position `atIndex`
changed to `newDocument`, was previously `oldDocument`.
{{/dtdd}}

{{#dtdd "moved(document, oldIndex, newIndex)"}}
A document changed its position in the result set,
from `oldIndex` to `newIndex`. For your
convenience, its current contents is `document`. (This will
only fire immediately after `changed`.
{{/dtdd}}

{{#dtdd "removed(oldDocument, atIndex)"}}
The document at position `atIndex`, which was previously
`oldDocument`, is no longer in the result set.
{{/dtdd}}

`added` will immediately be called as necessary to
deliver the initial results of the query, if any.

`observe` returns a live query handle, which is an object with a
`stop` method.  Call this function with no arguments to stop calling
the callback functions and tear down the query. **The query will run
forever until you call this.**

Example:

    // Keep track of how many administrators are online.
    var count = 0;
    var query = Users.find({admin: true, onlineNow: true});
    var handle = query.observe({
      added: function (user) {
        count++;
        console.log(user.name + " brings the total to " + count + " admins.");
      },
      removed: function () {
        count--;
        console.log("Lost one. We're now down to " + count + " admins.");
      }
    });

    // After five seconds, stop keeping the count.
    setTimeout(function () {handle.stop();}, 5000);

{{#api_box_inline selectors}}

In its simplest form, a selector is just a set of keys that must
match in a document:

    // Matches all documents where deleted is false
    {deleted: false}

    // Matches all documents where the name and cognomen are as given
    {name: "Rhialto", cognomen: "the Marvelous"}

    // Matches every document
    {}

But they can also contain more complicated tests:

    // Matches documents where age is greater than 18
    {age: {$gt: 18}}

    // Also matches documents where tags is an array containing "popular"
    {tags: "popular"}

    // Matches documents where fruit is one of three possibilities
    {fruit: {$in: ["peach", "plum", "pear"]}}

See the complete documentation.

{{/api_box_inline}}

{{#api_box_inline modifiers}}

A modifier is an object that describes how to update a document in
place by changing some of its fields. Some examples:

    // Set the 'admin' property on the document to true
    {$set: {admin: true}}

    // Add 2 to the 'votes' property, and add "Traz" to the end of the
    // 'supporters' array
    {$inc: {votes: 2}, $push: {supporters: "Traz"}}

But if a modifier doesn't contain any $-operators, then it is
instead interpreted as a literal document, and completely replaces
whatever was previously in the database.

    // Find the document with id "123", and completely replace it.
    Users.update({_id: "123"}, {name: "Alice", friends: ["Bob"]});

See the full list of modifiers.

{{/api_box_inline}}

{{#api_box_inline sortspecifiers}}

Sorts may be specified using your choice of several syntaxes:

    // All of these do the same thing (sort in ascending order by
    // key "a", breaking ties in descending order of key "b")

    [["a", "asc"], ["b", "desc"]]
    ["a", ["b", "desc"]]
    {a: 1, b: -1}

The last form will only work if your JavaScript implementation
preserves the order of keys in objects. Most do, most of the time, but
it's up to you to be sure.

{{/api_box_inline}}

{{#api_box_inline fieldspecifiers}}

On the server, queries can specify a particular set of fields to include
or exclude from the result object.  Minimongo ignores the field
specifier.

To exclude certain fields from the result objects, the field specifier
is a dictionary whose keys are field names and whose values are `0`.

    // Users.find({}, {fields: {password: 0, hash: 0}})

To return an object that only includes the specified field, use `1` as
the value.  The `_id` field is still included in the result.

    // Users.find({}, {fields: {firstname: 1, lastname: 1}})

It is not possible to mix inclusion and exclusion styles.

{{/api_box_inline}}

Session

`Session` provides a global object on the client that you can use to
store an arbitrary set of key-value pairs. Use it to store things like
the currently selected item in a list.

What's special about `Session` is that it's reactive. If
you call [`Session.get`](#session_get)`("currentList")`
from inside a template, the template will automatically be rerendered
whenever [`Session.set`](#session_set)`("currentList", x)` is called.

{{> api_box set}}

Example:

    Meteor.autosubcribe(function () {
      Meteor.subscribe("chat-history", {room: Session.get("currentRoomId")});
    });

    // Causes the function passed to Meteor.autosubscribe to be re-run, so
    // that the chat-history subscription is moved to the room "home".
    Session.set("currentRoomId", "home");

See [`Meteor.deps`](#meteor_deps) for another example.

{{> api_box get}}

Example:

    Session.set("enemy", "Eastasia");
    var frag = Meteor.render(function () {
      return "
We've always been at war with " +
        Session.get("enemy") + "
";
    });

    // Page will say "We've always been at war with Eastasia"
    document.body.append(frag);

    // Page will change to say "We've always been at war with Eurasia"
    Session.set("enemy", "Eurasia");

{{> api_box equals}}

These two expressions do the same thing:

    (1) Session.get("key") === value
    (2) Session.equals("key", value)

... but the second one is always better. It triggers fewer invalidations
(template redraws), making your program more efficient.

Example:

    <template name="postsView">
    {{dstache}}! Show a dynamically updating list of items. Let the user click on an
        item to select it. The selected item is given a CSS class so it
        can be rendered differently. }}

    {{dstache}}#each posts}}
      {{dstache}}> postItem }}
    {{dstache}}/each}}
    </{{! }}template>

    <template name="postItem">

{{dstache}}title}}

    </{{! }}template>

    ///// in JS file
    Template.postsView.posts = function() {
      return Posts.find();
    };

    Template.postItem.postClass = function() {
      return Session.equals("selectedPost", this._id) ?
        "selected" : "";
    };

    Template.postItem.events({
      'click': function() {
        Session.set("selectedPost", this._id);
      }
    });

    // Using Session.equals here means that when the user clicks
    // on an item and changes the selection, only the newly selected
    // and the newly unselected items are re-rendered.
    //
    // If Session.get had been used instead of Session.equals, then
    // when the selection changed, all the items would be re-rendered.

Templates

A template that you declare as `<{{! }}template name="foo"> ... </{{!
}}template>` can be accessed as the function `Template.foo`, which
returns a string of HTML when called.

The same template may occur many times on the page, and these
occurrences are called template instances.  Template instances have a
life cycle of being created, put into the document, and later taken
out of the document and destroyed.  Meteor manages these stages for
you, including determining when a template instance has been removed
or replaced and should be cleaned up.  You can associate data with a
template instance, and you can access its DOM nodes when it is in the
document.

Additionally, Meteor will maintain a template instance and its state
even if its surrounding HTML is re-rendered into new DOM nodes.  As
long as the structure of template invocations is the same, Meteor will
not consider any instances to have been created or destroyed.  You can
request that the same DOM nodes be retained as well using `preserve`
and `constant`.

There are a number of callbacks and directives that you can specify on
a named template and that apply to all instances of the template.
They are described below.

{{> api_box template_call}}

When called inside a template helper, the body of `Meteor.render`, or
other settings where reactive HTML is being generated, the resulting
HTML is annotated so that it renders as reactive DOM elements.
Otherwise, the HTML is unadorned and static.

{{> api_box template_rendered}}

This callback is called once when an instance of Template.*myTemplate* is rendered into DOM nodes and put into the document for the first time, and again each time any part of the template is re-rendered.

In the body of the callback, `this` is a [template
instance](#template_inst) object that is unique to this occurrence of
the template and persists across re-renderings.  Use the `created` and
`destroyed` callbacks to perform initialization or clean-up on the
object.

{{> api_box template_created}}

This callback is called when an invocation of *myTemplate* represents
a new occurrence of the template and not a re-rendering of an existing
template instance.  Inside the callback, `this` is the new [template
instance](#template_inst) object.  Properties you set on this object
will be visible from the `rendered` and `destroyed` callbacks and from
event handlers.

This callback fires once and is the first callback to fire.  Every
`created` has a corresponding `destroyed`; that is, if you get a
`created` callback with a certain template instance object in `this`,
you will eventually get a `destroyed` callback for the same object.

{{> api_box template_destroyed}}

This callback is called when an occurrence of a template is taken off
the page for any reason and not replaced with a re-rendering.  Inside
the callback, `this` is the [template instance](#template_inst) object
being destroyed.

This callback is most useful for cleaning up or undoing any external
effects of `created`.  It fires once and is the last callback to fire.

{{> api_box template_events}}

Declare event handers for instances of this template. Multiple calls add
new event handlers in addition to the existing ones.

See [Event Maps](#eventmaps) for a detailed description of the event
map format and how event handling works in Meteor.

{{#note}}
This syntax replaces the previous syntax: `Template.myTemplate.events = {...}`, but for now, the
old syntax still works.
{{/note}}

{{> api_box template_helpers}}

Each template has a local dictionary of helpers that are made available to it,
and this call specifies helpers to add to the template's dictionary.

Example:

    Template.myTemplate.helpers({
      foo: function () {
        return Session.get("foo");
      }
    });

In Handlebars, this helper would then be invoked as `{{dstache}}foo}}`.

The following syntax is equivalent, but won't work for reserved property
names:

    Template.myTemplate.foo = function () {
      return Session.get("foo");
    };

{{> api_box template_preserve}}

You can "preserve" a DOM element during re-rendering, leaving the
existing element in place in the document while replacing the
surrounding HTML.  This means that re-rendering a template need not
disturb text fields, iframes, and other sensitive elements it
contains.  The elements to preserve must be present both as nodes in
the old DOM and as tags in the new HTML.  Meteor will patch the DOM
around the preserved elements.

{{#note}}
By default, new Meteor apps automatically include the
`preserve-inputs` package.  This preserves all elements of type
`input`, `textarea`, `button`, `select`, and `option` that have unique
`id` attributes or that have `name` attributes that are unique within
an enclosing element with an `id` attribute.  To turn off this default
behavior, simply remove the `preserve-inputs` package.
{{/note}}

Preservation is useful in a variety of cases where replacing a DOM
element with an identical or modified element would not have the same
effect as retaining the original element.  These include:

* Input text fields and other form controls
* Elements with CSS animations
* Iframes
* Nodes with references kept in JavaScript code

If you want to preserve a whole region of the DOM, an element and its
children, or nodes not rendered by Meteor, use a [constant
region](#constant) instead.

To preserve nodes, pass a list of selectors each of which should match
at most one element in the template.  When the template is re-rendered,
the selector is run on the old DOM and the new DOM, and Meteor will
reuse the old element in place while working in any HTML changes around
it.

A second form of `preserve` takes a labeling function for each selector
and allows the selectors to match multiple nodes. The node-labeling
function takes a node and returns a label string that is unique for each
node, or `false` to exclude the node from preservation.

For example, to preserve all `<input>` elements with ids in template 'foo', use:

    Template.foo.preserve({
      'input[id]': function (node) { return node.id; }
    });

Selectors are interpreted as rooted at the top level of the template.
Each occurrence of the template operates independently, so the selectors
do not have to be unique on the entire page, only within one occurrence
of the template.  Selectors will match nodes even if they are in
sub-templates.

Preserving a node does *not* preserve its attributes or contents. They
will be updated to reflect the new HTML. Text in input fields is not
preserved unless the input field has focus, in which case the cursor and
selection are left intact. Iframes retain their navigation state and
animations continue to run as long as their parameters haven't changed.

There are some cases where nodes can not be preserved because of
constraints inherent in the DOM API. For example, an element's tag name
can't be changed, and it can't be moved relative to its parent or other
preserved nodes.  For this reason, nodes that are re-ordered or
re-parented by an update will not be preserved.

{{#note}}
Previous versions of Meteor had an implicit page-wide `preserve`
directive that labeled nodes by their "id" and "name" attributes.
This has been removed in favor of the explicit, opt-in mechanism.
{{/note}}

Template instances

A template instance object represents an occurrence of a template in
the document.  It can be used to access the DOM and it can be
assigned properties that persist across page re-renderings.

Template instance objects are found as the value of `this` in the
`created`, `rendered`, and `destroyed` template callbacks and as an
argument to event handlers.

In addition to the properties and functions described below, you can
assign additional properties of your choice to the object.  Property names
starting with `_` are guaranteed to be available for your use.  Use
the `created` and `destroyed` callbacks to perform initialization or
clean-up on the object.

You can only access `findAll`, `find`, `firstNode`, and `lastNode`
from the `rendered` callback and event handlers, not from `created`
and `destroyed`, because they require the template instance to be
in the DOM.

{{> api_box template_findAll}}

Returns an array of DOM elements matching `selector`.

The template instance serves as the document root for the selector. Only
elements inside the template and its sub-templates can match parts of
the selector.

{{> api_box template_find}}

Returns one DOM element matching `selector`, or `null` if there are no
such elements.

The template instance serves as the document root for the selector. Only
elements inside the template and its sub-templates can match parts of
the selector.

{{> api_box template_firstNode}}

The two nodes `firstNode` and `lastNode` indicate the extent of the
rendered template in the DOM.  The rendered template includes these
nodes, their intervening siblings, and their descendents.  These two
nodes are siblings (they have the same parent), and `lastNode` comes
after `firstNode`, or else they are the same node.

{{> api_box template_lastNode}}

{{> api_box template_data}}

This property provides access to the data context at the top level of
the template.  It is updated each time the template is re-rendered.
Access is read-only and non-reactive.

{{> api_box render}}

`Meteor.render` creates a `DocumentFragment` (a sequence of DOM nodes)
that automatically updates in realtime. Most Meteor apps don't need to
call this directly, they use templates and Meteor handles the rendering.

Pass in `htmlFunc`, a function that returns an HTML
string. `Meteor.render` calls the function and turns the output into
DOM nodes. Meanwhile, it tracks the data that was used when `htmlFunc`
ran, and automatically wires up callbacks so that whenever any of the
data changes, `htmlFunc` is re-run and the DOM nodes are updated in
place.

You may insert the returned `DocumentFragment` directly into the DOM
wherever you would like it to appear. The inserted nodes will continue
to update until they are taken off the screen. Then they will be
automatically cleaned up. For more details about clean-up, see
[`Meteor.flush`](#meteor_flush).

`Meteor.render` tracks the data dependencies of `htmlFunc` by running
it in a reactive context, so it can respond to changes in any reactive
data sources used by that function. For more information, or to learn
how to make your own reactive data sources, see
[Reactivity](#reactivity).

Example:

    // Show the number of users online.
    var frag = Meteor.render(function () {
      return "
There are " + Users.find({online: true}).count() +
        " users online.
";
    });
    document.body.appendChild(frag);

    // Find all users that have been idle for a while, and mark them as
    // offline. The count on the screen will automatically update.
    Users.update({idleTime: {$gt: 30}}, {online: false});

{{> api_box renderList}}

Creates a `DocumentFragment` that automatically updates as the results
of a database query change. Most Meteor apps use `{{dstache}}#each}}` in
a template instead of calling this directly.

`renderList` is more efficient than using `Meteor.render` to render HTML
for a list of documents.  For example, if a new document is created in
the database that matches the query, a new item will be rendered and
inserted at the appropriate place in the DOM without re-rendering the
other elements.  Similarly, if a document changes position in a sorted
query, the DOM nodes will simply be moved and not re-rendered.

`docFunc` is called as needed to generate HTML for each document.  If
you provide `elseFunc`, then whenever the query returns no results, it
will be called to render alternate content. You might use this to show
a message like "No records match your query."

Each call to `docFunc` or `elseFunc` is run in its own reactive
context so that if it has other external data dependencies, it will be
individually re-run when the data changes.

Example:

    // List the titles of all of the posts that have the tag
    // "frontpage". Keep the list updated as new posts are made, as tags
    // change, etc.  Display the selected post differently.
    var frag = Meteor.renderList(
      Posts.find({tags: "frontpage"}),
      function(post) {
        var style = Session.equals("selectedId", post._id) ? "selected" : "";
        // A real app would need to quote/sanitize post.name
        return '
' + post.name + '
';
      });
    document.body.appendChild(frag);

    // Select a post.  This will cause only the selected item and the
    // previously selected item to update.
    var somePost = Posts.findOne({tags: "frontpage"});
    Session.set("selectedId", somePost._id);

{{#api_box_inline eventmaps}}

Several functions take event maps. An event map is an object where
the properties specify a set of events to handle, and the values are
the handlers for those events. The property can be in one of several
forms:

{{#dtdd "eventtype"}}
Matches a particular type of event, such as 'click'.
{{/dtdd}}

{{#dtdd "eventtype selector"}}
Matches a particular type of event, but only when it appears on
an element that matches a certain CSS selector.
{{/dtdd}}

{{#dtdd "event1, event2"}}
To handle more than one type of event with the same function, use a comma-separated list.
{{/dtdd}}

The handler function receives two arguments: `event`, an object with
information about the event, and `template`, a [template
instance](#template_inst) for the template where the handler is
defined.  The handler also receives some additional context data in
`this`, depending on the context of the current element handling the
event.  In a Handlebars template, an element's context is the
Handlebars data context where that element occurs, which is set by
block helpers such as `#with` and `#each`.

Example:

    {
      // Fires when any element is clicked
      'click': function (event) { ... },

      // Fires when any element with the 'accept' class is clicked
      'click .accept': function (event) { ... },

      // Fires when 'accept' is clicked, or a key is pressed
      'keydown, click .accept': function (event) { ... }
    }

Most events bubble up the document tree from their originating
element.  For example, `'click p'` catches a click anywhere in a
paragraph, even if the click originated on a link, span, or some other
element inside the paragraph.  The originating element of the event
is available as the `target` property, while the element that matched
the selector and is currently handling it is called `currentTarget`.

    {
      'click p': function (event) {
        var paragraph = event.currentTarget; // always a P
        var clickedElement = event.target; // could be the P or a child element
      }
    }

If a selector matches multiple elements that an event bubbles to, it
will be called multiple times, for example in the case of `'click
div'` or `'click *'`.  If no selector is given, the handler
will only be called once, on the original target element.

The following properties and methods are available on the event object
passed to handlers:

{{#dtdd name="type" type="String"}}
The event's type, such as "click", "blur" or "keypress".
{{/dtdd}}

{{#dtdd name="target" type="DOM Element"}}
The element that originated the event.
{{/dtdd}}

{{#dtdd name="currentTarget" type="DOM Element"}}
The element currently handling the event.  This is the element that
matched the selector in the event map.  For events that bubble, it may
be `target` or an ancestor of `target`, and its value changes as the
event bubbles.
{{/dtdd}}

{{#dtdd name="which" type="Number"}}
For mouse events, the number of the mouse button (1=left, 2=middle, 3=right).
For key events, a character or key code.
{{/dtdd}}

{{#dtdd "stopPropagation()"}}
Prevent the event from propagating (bubbling) up to other elements.
Other event handlers matching the same element are still fired, in
this and other event maps.
{{/dtdd}}

{{#dtdd "stopImmediatePropagation()"}}
Prevent all additional event handlers from being run on this event,
including other handlers in this event map, handlers reached by
bubbling, and handlers in other event maps.
{{/dtdd}}

{{#dtdd "preventDefault()"}}
Prevents the action the browser would normally take in response to this
event, such as following a link or submitting a form.  Further handlers
are still called, but cannot reverse the effect.
{{/dtdd}}

{{#dtdd "isPropagationStopped()"}}
Returns whether `stopPropagation()` has been called for this event.
{{/dtdd}}

{{#dtdd "isImmediatePropagationStopped()"}}
Returns whether `stopImmediatePropagation()` has been called for this event.
{{/dtdd}}

{{#dtdd "isDefaultPrevented()"}}
Returns whether `preventDefault()` has been called for this event.
{{/dtdd}}

Returning `false` from a handler is the same as calling
both `stopImmediatePropagation` and `preventDefault` on the event.

Event types and their uses include:

{{#dtdd "click"}}
Mouse click on any element, including a link, button, form control, or div.
Use `preventDefault()` to prevent a clicked link from being followed.
Some ways of activating an element from the keyboard also fire `click`.
{{/dtdd}}

{{#dtdd "dblclick"}}
Double-click.
{{/dtdd}}

{{#dtdd "focus, blur"}}
A text input field or other form control gains or loses focus.  You
can make any element focusable by giving it a `tabindex` property.
Browsers differ on whether links, checkboxes, and radio buttons are
natively focusable.  These events do not bubble.
{{/dtdd}}

{{#dtdd "change"}}
A checkbox or radio button changes state.  For text fields, use
`blur` or key events to respond to changes.
{{/dtdd}}

{{#dtdd "mouseenter, mouseleave"}} The pointer enters or
leaves the bounds of an element.  These events do not bubble.
{{/dtdd}}

{{#dtdd "mousedown, mouseup"}}
The mouse button is newly down or up.
{{/dtdd}}

{{#dtdd "keydown, keypress, keyup"}}
The user presses a keyboard key.  `keypress` is most useful for
catching typing in text fields, while `keydown` and `keyup` can be
used for arrow keys or modifier keys.
{{/dtdd}}

Other DOM events are available as well, but for the events above,
Meteor has taken some care to ensure that they work uniformly in all
browsers.

{{/api_box_inline}}

{{#api_box_inline constant}}

You can mark a region of a template as "constant" and not subject to
re-rendering using the
`{{dstache}}#constant}}...{{dstache}}/constant}}` block helper.
Content inside the `#constant` block helper is preserved exactly as-is
even if the enclosing template is re-rendered.  Changes to other parts
of the template are patched in around it in the same manner as
`preserve`.  Unlike individual node preservation, a constant region
retains not only the identities of its nodes but also their attributes
and contents.  The contents of the block will only be evaluated once
per occurrence of the enclosing template.

Constant regions allow non-Meteor content to be embedded in a Meteor
template.  Many third-party widgets create and manage their own DOM
nodes programmatically. Typically, you put an empty element in your
template, which the widget or library will then populate with
children. Normally, when Meteor re-renders the enclosing template it
would remove the new children, since the template says it should be
empty. If the container is wrapped in a `#constant` block, however, it
is left alone; whatever content is currently in the DOM remains.

{{#note}}
Constant regions are intended for embedding non-Meteor content.
Event handlers and reactive dependencies don't currently work
correctly inside constant regions.
{{/note}}

{{/api_box_inline}}

{{#api_box_inline isolate}}

Each template runs in its own reactive context.  When the template
accesses a reactive data source, such as by calling `Session.get` or
making a database query, this establishes a data dependency that will
cause the whole template to be re-rendered when the data changes.
This means that the amount of re-rendering for a particular change
is affected by how you've divided your HTML into templates.

Typically, the exact extent of re-rendering is not crucial, but if you
want more control, such as for performance reasons, you can use the
`{{dstache}}#isolate}}...{{dstache}}/isolate}}` helper.  Data
dependencies established inside an `#isolate` block are localized to
the block and will not in themselves cause the parent template to be
re-rendered.  This block helper essentially conveys the reactivity
benefits you would get by pulling the content out into a new
sub-template.

{{/api_box_inline}}

Timers

Meteor uses global environment variables
to keep track of things like the current request's user.  To make sure
these variables have the right values, you need to use
`Meteor.setTimeout` instead of `setTimeout` and `Meteor.setInterval`
instead of `setInterval`.

These functions work just like their native JavaScript equivalents.
You'll get an error if you call the native function.

{{> api_box setTimeout}}
{{> api_box setInterval}}
{{> api_box clearTimeout}}
{{> api_box clearInterval}}

Meteor.deps

Meteor has a simple dependency tracking system, so that it it can
automatically rerender templates and such when [`Session`](#session)
variables are modified, or database queries change.

Unlike most other systems, you don't have to manually declare these
dependencies — it "just works". The mechanism is simple and
efficient. When you call a function that supports reactive updates
(say, a database query), it automatically saves the current
"invalidation context" object if any (say, the current template being
rendered.) Later, when the data changes, it can "invalidates" this
context (tell the template to rerender itself.) The whole
implementation is about 50 lines of code.

Developers, particularly package authors, can use *invalidation
contexts* to implement additional reactive data sources or to write
functions that automatically register dependencies on reactive data
sources.

{{> api_box Context }}

Create an invalidation context by calling this constructor, then run
some code inside the context with [`run`](#run). Finally, register a
callback with [`onInvalidate`](#oninvalidate) that will get called
when the code you run wants to signal that it should be rerun.

Code can see if it's running inside an invalidation context by reading
the [`Meteor.deps.Context.current`](#current) global variable, which
will be the currently active context, or `null` if it's not being run
from inside a context.  If it wants to participate in the reactivity
system, it should save this context away, and later call the
[`invalidate`](#invalidate) method on the context when it wants to
signal that something has changed. If it does this, it should also use
[`onInvalidate`](#oninvalidate) to set up a cleanup function so that
it can know when to stop listening for changes.

Invalidation contexts have an attribute `id` which is a unique positive
integer. You're free to add any other attributes you like to the
invalidation context for your own convenience, as long as they don't
start with an underscore.

{{> api_box run }}

This function simply sets [`Meteor.deps.Context.current`](#current) to
this invalidation context, runs `func`, and then restores it to its
previous value. It returns the result of calling `func`.

It's fine for `run` to be called recursively. `current` will return the
innermost context.

{{> api_box onInvalidate }}

If this context hasn't been invalidated yet, adds `callback` to the list
of callbacks that will be called when [`invalidate`](#invalidate) is
called. If the context has already been invalidated, call `callback`
immediately.

Typically this function will have two kinds of callers:

* The function that creates the invalidation context will use the
  `onInvalidate` callback as a signal to rerun the code in the context,
  to see what new value it returns. In order to rerun the code, it'll
  create a fresh invalidation context and reregister its `onInvalidate`
  callback on that new context. When that context is invalidated the
  cycle will repeat.

* Functions that are sources of reactive data will save
  [`Meteor.deps.Context.current`](#current) into some kind of list of
  listeners. They'll use the `onInvalidate` callback to remove the
  context from their listener list.

Example:

    // Print the current username to the console.  Will re-run every time
    // the username changes.
    var logCurrentUsername = function () {
      var update = function () {
        var ctx = new Meteor.deps.Context();  // invalidation context
        ctx.onInvalidate(update);             // rerun update() on invalidation
        ctx.run(function () {
          var username = Session.get("username");
          console.log("The current username is now", username);
        });
      };
      update();
    };

    // Example use. Since Session is reactive (meaning that it knows how
    // to use Meteor.deps to record its dependencies), logCurrentUsername
    // will be re-run whenever Session.set is called for "username".
    Session.set("username", "matt");
    logCurrentUsername(); // prints matt
    Session.set("username", "geoff"); // immediately prints geoff
    Session.set("username", "geoff"); // won't print: Session won't trigger
                                      // invalidation if the value is the same.

{{> api_box invalidate }}

If this function has already been called on this context, it does
nothing (a mathematician would say that it is "idempotent.") Otherwise
it calls each [`onInvalidate`](#oninvalidate) function registered on
the context.

The functions aren't called immediately — instead, they will be
called the next time you call [`Meteor.flush`](#meteor_flush). This function
just adds the context to the flush list and is guaranteed to do nothing
else just yet.

If you don't call [`Meteor.flush`](#meteor_flush) explicitly, it will be called
for you automatically when your code is done running (by setting a
`setTimeout` timer with a delay of zero.)

Example:

    // Create a simple class called Weather that tracks the current
    // temperature. The temperature can be read reactively.
    var Weather = function () {
      this.temperature = 60;
      this.listeners = {};
    };

    // Function to get the temperature (and, if called in a reactive
    // context, start listening for changes to the temperature.)
    Weather.prototype.getTemp = function () {
      var context = Meteor.deps.Context.current;

      // If we're inside a context, and it's not yet listening to
      // temperature changes..
      if (context && !this.listeners[context.id]) {
        // .. add it to our list of contexts that care about the temperature ..
        this.listeners[context.id] = context;

        // .. and remember to take it off our list when it goes away.
        var self = this;
        context.onInvalidate(function () {
          delete self.listeners[context.id];
        });
      }

      // return the current temperature, whether or not in a reactive context.
      return this.temperature;
    };

    // Function to set the temperature, and notify anyone that might be
    // listening for temperature updates.
    Weather.prototype.setTemp = function (newTemp) {
      if (this.temperature === newTemp)
        return; // don't want to trigger invalidation if there's no change.

      // Set the temperature
      this.temperature = newTemp;

      // Notify any contexts that care about temperature changes
      for (var contextId in this.listeners)
        // This will trigger the onInvalidate function above, but not
        // immediately -- only when Meteor.flush() is called, or at the end
        // of the event loop. So we know that this.listeners will be
        // emptied, but it won't change while we're trying to loop over it.
        this.listeners[contextId].invalidate();
    };

{{> api_box current }}

This is a global variable that is set by [`run`](#run).

If you have a background in Lisp or programming language theory, you
might think of it as a dynamically scoped ("special") variable. (That
just means that [`run`](#run) sets it, runs some user-supplied code, and
then restores its previous value.)

{{> api_box flush }}

Normally, when you make changes (like writing to the database),
their impact (like updating the DOM) is delayed until the system is
idle. This keeps things predictable — you can know that the DOM
won't go changing out from under your code as it runs. It's also one
of the things that makes Meteor fast.

`Meteor.flush` forces all of the pending reactive updates to complete
(for example, it ensures the DOM has been updated with your recent
database changes.)  Call `flush` to apply those pending changes
immediately. The main use for this is to make sure the DOM has been
brought up to date with your latest changes, so you can manually
manipulate it with jQuery or the like.

When you call `flush`, any auto-updating DOM elements that are not on
the screen may be cleaned up (meaning that Meteor will stop tracking
and updating the elements, so that the browser's garbage collector can
delete them.) So, if you manually call `flush`, you need to make sure
that any auto-updating elements that you have created by calling
[`Meteor.render`](#meteor_render) have already been inserted in the main
DOM tree.

Technically speaking, `flush` calls the [invalidation
callbacks](#oninvalidate) on every [reactive context](#context) that
has been [invalidated](#invalidate), but hasn't yet has its callbacks
called. If the invalidation callbacks invalidate still more contexts,
flush keeps flushing until everything is totally settled. The DOM
elements are cleaned up by logic that is triggered by context invalidations.

Meteor.http

`Meteor.http` provides an HTTP API on the client and server.  To use
these functions, add the HTTP package to your project with `meteor add
http`.

{{> api_box httpcall}}

This function initiates an HTTP request to a remote server. It returns
a result object with the contents of the HTTP response.  The result
object is detailed below.

On the server, this function can be run either synchronously or
asynchronously.  If the callback is omitted, it runs synchronously,
and the results are returned once the request completes. This is
useful when making server-to-server HTTP API calls from within Meteor
methods, as the method can succeed or fail based on the results of the
synchronous HTTP call.  In this case, consider using
[`this.unblock()`](#method_unblock) to allow other methods to run in
the mean time.  On the client, this function must be used
asynchronously by passing a callback.

Both HTTP and HTTPS protocols are supported.  The `url` argument must be
an absolute URL including protocol and host name on the server, but may be
relative to the current host on the client.  The `query` option
replaces the query string of `url`.  Parameters specified in `params`
that are put in the URL are appended to any query string.
For example, with a `url` of `"/path?query"` and
`params` of `{foo:"bar"}`, the final URL will be `"/path?query&foo=bar"`.

The `params` are put in the URL or the request body, depending on the
type of request.  In the case of request with no bodies, like GET and
HEAD, the parameters will always go in the URL.  For a POST or other
type of request, the parameters will be encoded into the body with a
standard `x-www-form-urlencoded` content type, unless the `content`
or `data` option is used to specify a body, in which case the
parameters will be appended to the URL instead.

The callback receives two arguments, `error` and `result`.  The `error`
argument will contain an Error if the request fails in any way,
including a network error, time-out, or an HTTP status code in the 400
or 500 range.  The result object is always
defined. When run in synchronous mode, the `result` is returned from the
function, and the `error` value is a stored as a property in `result`.

Contents of the result object:

statusCode
  Number

Numeric HTTP result status code, or null on error.

content
  String

The body of the HTTP response as a string.

data
  Object or null

If the response headers indicate JSON content, this contains the body of the document parsed as a JSON object.

headers
  Object

A dictionary of HTTP headers from the response.

error
  Error

Error object if the request failed. Matches the `error` callback parameter.

Example server method:

    Meteor.methods({checkTwitter: function (userId) {
      this.unblock();
      var result = Meteor.http.call("GET", "http://api.twitter.com/xxx",
                                    {params: {user: userId}});
      if (result.statusCode === 200)
         return true
      return false;
    }});

Example asynchronous HTTP call:

    Meteor.http.call("POST", "http://api.twitter.com/xxx",
                     {data: {some: "json", stuff: 1}},
                     function (error, result) {
                       if (result.statusCode === 200) {
                         Session.set("twizzled", true);
                       }
                     });

{{> api_box http_get}}
{{> api_box http_post}}
{{> api_box http_put}}
{{> api_box http_del}}

Email

The `email` package allows sending email from a Meteor app. To use it, add the
package to your project with `$ meteor add email`.

The server reads from the `MAIL_URL` environment variable to determine how to
send mail. Currently, Meteor supports sending mail over SMTP; the `MAIL_URL`
environment variable should be of the form
`smtp://USERNAME:PASSWORD@HOST:PORT/`. For apps deployed with `meteor deploy`,
`MAIL_URL` defaults to an account (provided by
Mailgun) which allows
apps to send up to 200 emails per day; you may override this default by
assigning to `process.env.MAIL_URL` before your first call to `Email.send`.

If `MAIL_URL` is not set (eg, when running your application locally),
`Email.send` outputs the message to standard output instead.

{{> api_box email_send }}

You must provide the `from` option and at least one of `to`, `cc`, and `bcc`;
all other options are optional.

{{/better_markdown}}
</template>

<template name="api_box">

  {{{name}}}
{{#if locus}}
  {{locus}}
{{/if}}

{{#each descr}}{{#better_markdown}}{{{this}}}{{/better_markdown}}{{/each}}

{{#if args}}

Arguments

{{> api_box_args args}}
{{/if}}

{{#if options}}

Options

{{> api_box_args options}}
{{/if}}

{{#if body}}
{{#better_markdown}}{{{body}}}{{/better_markdown}}
{{/if}}

</template>

<template name="api_box_args">

{{#each this}}

{{{name}}}

    {{#if type_link}}
      {{type}}
    {{else}}
      {{type}}
    {{/if}}

{{#better_markdown}}{{{descr}}}{{/better_markdown}}

{{/each}}

</template>

<template name="api_section_helper">

{{name}}

</template>


// call this function to allow other method invocations (from the

// same client) to continue running without waiting for this one to

this.unblock = unblock || function () {};

this.unblock = options.unblock || function () {};

/******************************************************************************/
/* LivedataSession                                                            */
/******************************************************************************/

Meteor._LivedataSession = function (server) {
  var self = this;
  self.id = Meteor.uuid();

  self.server = server;

  self.initialized = false;
  self.socket = null;
  self.last_connect_time = 0;
  self.last_detach_time = +(new Date);

  self.in_queue = [];
  self.blocked = false;
  self.worker_running = false;

  self.out_queue = [];

  // id of invocation => {result or error, when}
  self.result_cache = {};

  // Sub objects for active subscriptions
  self.named_subs = {};
  self.universal_subs = [];

  self.next_sub_priority = 0;

  // map from collection name -> id -> key -> subscription id -> true
  self.provides_key = {};

  // if set, ignore flush requests on any subsubcription on this
  // session. when set this back to false, don't forget to call flush
  // manually. this is sometimes needed because subscriptions
  // frequently call flush
  self.dontFlush = false;

  self.userId = null;
};

_.extend(Meteor._LivedataSession.prototype, {
  // Connect a new socket to this session, displacing (and closing)
  // any socket that was previously connected
  connect: function (socket) {
    var self = this;
    if (self.socket) {
      self.socket.close();
      self.detach(self.socket);
    }

    self.socket = socket;
    self.last_connect_time = +(new Date);
    _.each(self.out_queue, function (msg) {
      self.socket.send(JSON.stringify(msg));
    });
    self.out_queue = [];

    // On initial connect, spin up all the universal publishers.
    if (!self.initialized) {
      self.initialized = true;
      Fiber(function () {
        _.each(self.server.universal_publish_handlers, function (handler) {
          self._startSubscription(handler, self.next_sub_priority--);
        });
      }).run();
    }
  },

  // If 'socket' is the socket currently connected to this session,
  // detach it (the session will then have no socket -- it will
  // continue running and queue up its messages.) If 'socket' isn't
  // the currently connected socket, just clean up the pointer that
  // may have led us to believe otherwise.
  detach: function (socket) {
    var self = this;
    if (socket === self.socket) {
      self.socket = null;
      self.last_detach_time = +(new Date);
    }
    if (socket.meteor_session === self)
      socket.meteor_session = null;
  },

  // Should be called periodically to prune the method invocation
  // replay cache.
  cleanup: function () {
    var self = this;
    // Only prune if we're connected, and we've been connected for at
    // least five minutes. That seems like enough time for the client
    // to finish its reconnection. Then, keep five minutes of
    // history. That seems like enough time for the client to receive
    // our responses, or else for us to notice that the connection is
    // gone.
    var now = +(new Date);
    if (!(self.socket && (now - self.last_connect_time) > 5 * 60 * 1000))
      return; // not connected, or not connected long enough

    var kill = [];
    _.each(self.result_cache, function (info, id) {
      if (now - info.when > 5 * 60 * 1000)
        kill.push(id);
    });
    _.each(kill, function (id) {
      delete self.result_cache[id];
    });
  },

  // Destroy this session. Stop all processing and tear everything
  // down. If a socket was attached, close it.
  destroy: function () {
    var self = this;
    if (self.socket) {
      self.socket.close();
      self.detach(self.socket);
    }
    self._stopAllSubscriptions();
    self.in_queue = self.out_queue = [];
  },

  // Send a message (queueing it if no socket is connected right now.)
  // It should be a JSON object (it will be stringified.)
  send: function (msg) {
    var self = this;
    if (self.socket)
      self.socket.send(JSON.stringify(msg));
    else
      self.out_queue.push(msg);
  },

  // Send a connection error.
  sendError: function (reason, offending_message) {
    var self = this;
    var msg = {msg: 'error', reason: reason};
    if (offending_message)
      msg.offending_message = offending_message;
    self.send(msg);
  },

  // Process 'msg' as an incoming message. (But as a guard against
  // race conditions during reconnection, ignore the message if
  // 'socket' is not the currently connected socket.)
  //
  // We run the messages from the client one at a time, in the order
  // given by the client. The message handler is passed an idempotent
  // function 'unblock' which it may call to allow other messages to
  // begin running in parallel in another fiber (for example, a method
  // that wants to yield.) Otherwise, it is automatically unblocked
  // when it returns.
  //
  // Actually, we don't have to 'totally order' the messages in this
  // way, but it's the easiest thing that's correct. (unsub needs to
  // be ordered against sub, methods need to be ordered against each
  // other.)
  processMessage: function (msg_in, socket) {
    var self = this;
    if (socket !== self.socket)
      return;

    self.in_queue.push(msg_in);
    if (self.worker_running)
      return;
    self.worker_running = true;

    var processNext = function () {
      var msg = self.in_queue.shift();
      if (!msg) {
        self.worker_running = false;
        return;
      }

      Fiber(function () {
        var blocked = true;

        var unblock = function () {
          if (!blocked)
            return; // idempotent
          blocked = false;
          processNext();
        };

        if (msg.msg in self.protocol_handlers)
          self.protocol_handlers[msg.msg].call(self, msg, unblock);
        else
          self.sendError('Bad request', msg);
        unblock(); // in case the handler didn't already do it
      }).run();
    };

    processNext();
  },

  protocol_handlers: {
    sub: function (msg) {
      var self = this;

      // reject malformed messages
      if (typeof (msg.id) !== "string" ||
          typeof (msg.name) !== "string" ||
          (('params' in msg) && !(msg.params instanceof Array))) {
        self.sendError("Malformed subscription", msg);
        return;
      }

      if (!self.server.publish_handlers[msg.name]) {
        self.send({
          msg: 'nosub', id: msg.id,
          error: {error: 404, reason: "Subscription not found"}});
        return;
      }

      if (msg.id in self.named_subs)
        // subs are idempotent, or rather, they are ignored if a sub
        // with that id already exists. this is important during
        // reconnect.
        return;

      var handler = self.server.publish_handlers[msg.name];
      self._startSubscription(handler, self.next_sub_priority--,
                              msg.id, msg.params);
    },

    unsub: function (msg) {
      var self = this;

      self._stopSubscription(msg.id);
      self.send({msg: 'nosub', id: msg.id});
    },

    method: function (msg, unblock) {
      var self = this;

      // reject malformed messages
      // XXX should also reject messages with unknown attributes?
      if (typeof (msg.id) !== "string" ||
          typeof (msg.method) !== "string" ||
          (('params' in msg) && !(msg.params instanceof Array))) {
        self.sendError("Malformed method invocation", msg);
        return;
      }

      // set up to mark the method as satisfied once all observers
      // (and subscriptions) have reacted to any writes that were
      // done.
      var fence = new Meteor._WriteFence;
      fence.onAllCommitted(function () {
        // Retire the fence so that future writes are allowed.
        // This means that callbacks like timers are free to use
        // the fence, and if they fire before it's armed (for
        // example, because the method waits for them) their
        // writes will be included in the fence.
        fence.retire();
        self.send({
          msg: 'data', methods: [msg.id]});
      });

      // check for a replayed method (this is important during
      // reconnect)
      if (msg.id in self.result_cache) {
        // found -- just resend whatever we sent last time
        var payload = _.clone(self.result_cache[msg.id]);
        delete payload.when;
        self.send(
          _.extend({msg: 'result', id: msg.id}, payload));
        fence.arm();
        return;
      }

      // find the handler
      var handler = self.server.method_handlers[msg.method];
      if (!handler) {
        self.send({
          msg: 'result', id: msg.id,
          error: {error: 404, reason: "Method not found"}});
        fence.arm();
        return;
      }

      var setUserId = function(userId) {
        self._setUserId(userId);
      };

      var invocation = new Meteor._MethodInvocation(
        false /* isSimulation */, self.userId, setUserId, unblock);
      try {
        var ret =
          Meteor._CurrentWriteFence.withValue(fence, function () {
            return Meteor._CurrentInvocation.withValue(invocation, function () {
              return handler.apply(invocation, msg.params || []);
            });
          });
      } catch (e) {
        var exception = e;
      }

      fence.arm(); // we're done adding writes to the fence
      unblock(); // unblock, if the method hasn't done it already

      // "blind" exceptions other than those that were deliberately
      // thrown to signal errors to the client
      if (exception && !(exception instanceof Meteor.Error)) {
        // tests can set the 'expected' flag on an exception so it
        // won't go to the server log
        if (!exception.expected)
          Meteor._debug("Exception while invoking method '" +
                        msg.method + "'", exception.stack);
        exception = new Meteor.Error(500, "Internal server error");
      }

      // send response and add to cache
      var payload =
        exception ? {error: exception} : (ret !== undefined ?
                                          {result: ret} : {});
      self.result_cache[msg.id] = _.extend({when: +(new Date)}, payload);
      self.send(_.extend({msg: 'result', id: msg.id}, payload));
    }
  },

  // Sets the current user id in all appropriate contexts and reruns
  // all subscriptions
  _setUserId: function(userId) {
    var self = this;
    self.userId = userId;
    this._rerunAllSubscriptions();
  },

  _startSubscription: function (handler, priority, sub_id, params) {
    var self = this;

    var sub = new Meteor._LivedataSubscription(self, sub_id, priority);
    if (sub_id)
      self.named_subs[sub_id] = sub;
    else
      self.universal_subs.push(sub);

    // Store a function to re-run the handler in case we want to rerun
    // subscriptions, for example when the current user id changes
    sub._runHandler = function() {
      try {
        var res = handler.apply(sub, params || []);
      } catch (e) {
        Meteor._debug("Internal exception while starting subscription", sub_id,
                      e.stack);
        return;
      }

      // if Meteor._RemoteCollectionDriver is available (defined in
      // mongo-livedata), automatically wire up handlers that return a
      // Cursor.  otherwise, the handler is completely responsible for
      // delivering its own data messages and registering stop
      // functions.
      //
      // XXX generalize
      if (Meteor._RemoteCollectionDriver && (res instanceof Meteor._Mongo.Cursor))
        sub._publishCursor(res);
    };

    sub._runHandler();
  },

  // tear down specified subscription
  _stopSubscription: function (sub_id) {
    var self = this;

    if (sub_id && self.named_subs[sub_id]) {
      self.named_subs[sub_id].stop();
      delete self.named_subs[sub_id];
    }
  },

  // tear down all subscriptions
  _stopAllSubscriptions: function () {
    var self = this;

    _.each(self.named_subs, function (sub, id) {
      sub.stop();
    });
    self.named_subs = {};

    _.each(self.universal_subs, function (sub) {
      sub.stop();
    });
    self.universal_subs = [];
  },

  // Rerun all subscriptions without sending intermediate state down
  // the wire
  _rerunAllSubscriptions: function () {
    var self = this;

    var rerunSub = function(sub) {
      sub._teardown();
      sub._userId = self.userId;
      sub._runHandler();
    };
    var flushSub = function(sub) {
      sub.flush();
    };

    self.dontFlush = true;
    _.each(self.named_subs, rerunSub);
    _.each(self.universal_subs, rerunSub);

    self.dontFlush = false;
    _.each(self.named_subs, flushSub);
    _.each(self.universal_subs, flushSub);
  },

  // RETURN the current value for a particular key, as given by the
  // current contents of each subscription's snapshot.
  _effectiveValueForKey: function (collection_name, id, key) {
    var self = this;

    // Find all subs that publish a value for this key
    var provided_by = Meteor._get(self.provides_key, collection_name, id, key);
    provided_by = _.values(provided_by || {});

    if (provided_by.length === 0)
      return undefined; // no value for key

    // Which one is highest priority?
    var authority = _.max(provided_by, function (sub) {
      return sub.priority;
    });

    return authority.snapshot[collection_name][id][key];
  }
});

/******************************************************************************/
/* LivedataSubscription                                                       */
/******************************************************************************/

// ctor for a sub handle: the input to each publish function
Meteor._LivedataSubscription = function (session, sub_id, priority) {
  // LivedataSession
  this.session = session;

  // my subscription ID (generated by client, null for universal subs).
  this.sub_id = sub_id;

  // number (possibly negative.) when two subs return conflicting
  // values for the same key, the client will see the value from the
  // sub with the higher priority.
  this.priority = priority;

  // data queued up to be sent by the next flush()
  // map from collection name -> id -> key -> value
  // to indicate unset, value === undefined
  this.pending_data = {};
  this.pending_complete = false;

  // the current data for this subscription (as has been flush()ed to
  // the client.)
  // map from collection name -> id -> key -> value
  this.snapshot = {};
  this.sent_complete = false;

  // has stop() been called?
  this.stopped = false;

  // stop callbacks to g/c this sub.  called w/ zero arguments.
  this.stop_callbacks = [];

  this._userId = session.userId;
};

_.extend(Meteor._LivedataSubscription.prototype, {
  stop: function () {
    var self = this;

    if (self.stopped)
      return;

    self._teardown();
    self.flush();
    self.stopped = true;
  },

  onStop: function (callback) {
    this.stop_callbacks.push(callback);
  },

  set: function (collection_name, id, attributes) {
    var self = this;
    var obj = Meteor._ensure(self.pending_data, collection_name, id);
    _.each(attributes, function (value, key) {
      if (key !== '_id')
        obj[key] = value;
    });
  },

  unset: function (collection_name, id, keys) {
    var self = this;
    var obj = Meteor._ensure(self.pending_data, collection_name, id);
    _.each(keys, function (key) {
      if (key !== '_id')
        obj[key] = undefined; // do not delete - need to mark as 'to be unset'
    });
  },

  complete: function () {
    var self = this;

    // universal subs (sub_id is null) can't signal completion.  it's
    // not an error, since the same handler (eg publishQuery) might be
    // used to implement both named and universal subs.

    if (self.sub_id)
      self.pending_complete = true;
  },

  flush: function () {
    var self = this;

    if (self.session.dontFlush)
      return;

    if (self.stopped)
      return;

    for (var name in self.pending_data)
      for (var id in self.pending_data[name]) {
        // construct outbound DDP data message
        var msg = {msg: 'data', collection: name, id: id};

        // snapshot holds this subscription's values for each key
        var snapshot = Meteor._ensure(self.snapshot, name, id);

        for (var key in self.pending_data[name][id]) {
          // value: set by this run of this publish handler.
          var value = self.pending_data[name][id][key];

          // old_value: set by previous run of this publish handler.
          var old_value = snapshot[key];

          if (value !== old_value) {
            // First, find the effective value that the client currently
            // has, thanks to the highest priority subscription.
            var old_effective_value = self.session._effectiveValueForKey(name, id, key);

            // Update our snapshot based on the written value. Update
            // our session's index too.
            if (value === undefined) {
              delete snapshot[key];
              Meteor._delete(self.session.provides_key, name, id, key, self.sub_id);
            } else {
              snapshot[key] = value;
              var provides = Meteor._ensure(self.session.provides_key,
                                            name, id, key);
              provides[self.sub_id] = self;
            }

            // Now compute new effective value, taking into account our new value.
            var new_effective_value = self.session._effectiveValueForKey(name, id, key);

            // If the effective values differ, this sub is responsible
            // for sending the new data down to the client.
            if (old_effective_value !== new_effective_value) {
              if (new_effective_value === undefined) {
                if (!('unset' in msg))
                  msg.unset = [];
                msg.unset.push(key);
              } else {
                if (!('set' in msg))
                  msg.set = {};
                msg.set[key] = new_effective_value;
              }
            }
          }
        }

        // Send an update for one object.
        if ('set' in msg || 'unset' in msg)
          self.session.send(msg);
      }

    if (self.pending_complete && !self.sent_complete) {
      self.session.send({msg: 'data', subs: [self.sub_id]});
      self.sent_complete = true;
    }

    self.pending_data = {};
    self.pending_complete = false;
  },

  userId: function() {
    return this._userId;
  },

  _teardown: function() {
    var self = this;
    // tell listeners, so they can clean up
    for (var i = 0; i < self.stop_callbacks.length; i++)
      (self.stop_callbacks[i])();

    // remove our data from the client (possibly unshadowing data from
    // lower priority subscriptions)
    self.pending_data = {};
    self.pending_complete = false;
    for (var name in self.snapshot) {
      self.pending_data[name] = {};
      for (var id in self.snapshot[name]) {
        self.pending_data[name][id] = {};
        for (var key in self.snapshot[name][id])
          self.pending_data[name][id][key] = undefined;
      }
    }
  },

  _publishCursor: function (cursor, name) {
    var self = this;
    var collection = name || cursor.collection_name;

    var observe_handle = cursor.observe({
      added: function (obj) {
        self.set(collection, obj._id, obj);
        self.flush();
      },
      changed: function (obj, old_idx, old_obj) {
        var set = {};
        _.each(obj, function (v, k) {
          if (!_.isEqual(v, old_obj[k]))
            set[k] = v;
        });
        self.set(collection, obj._id, set);
        var dead_keys = _.difference(_.keys(old_obj), _.keys(obj));
        self.unset(collection, obj._id, dead_keys);
        self.flush();
      },
      removed: function (old_obj, old_idx) {
        self.unset(collection, old_obj._id, _.keys(old_obj));
        self.flush();
      }
    });

    // observe only returns after the initial added callbacks have
    // run.  mark subscription as completed.
    self.complete();
    self.flush();

    // register stop callback (expects lambda w/ no args).
    self.onStop(_.bind(observe_handle.stop, observe_handle));
  }
});

/******************************************************************************/
/* LivedataServer                                                             */
/******************************************************************************/

Meteor._LivedataServer = function () {
  var self = this;

  self.publish_handlers = {};
  self.universal_publish_handlers = [];

  self.method_handlers = {};

  self.on_autopublish = []; // array of func if AP disabled, null if enabled
  self.warned_about_autopublish = false;

  self.sessions = {}; // map from id to session

  self.stream_server = new Meteor._StreamServer;

  self.stream_server.register(function (socket) {
    socket.meteor_session = null;

    var sendError = function (reason, offending_message) {
      var msg = {msg: 'error', reason: reason};
      if (offending_message)
        msg.offending_message = offending_message;
      socket.send(JSON.stringify(msg));
    };

    socket.on('data', function (raw_msg) {
      try {
        try {
          var msg = JSON.parse(raw_msg);
        } catch (err) {
          sendError('Parse error');
          return;
        }
        if (typeof msg !== 'object' || !msg.msg) {
          sendError('Bad request', msg);
          return;
        }

        if (msg.msg === 'connect') {
          if (socket.meteor_session) {
            sendError("Already connected", msg);
            return;
          }

          // XXX session resumption does not work yet!
          // https://app.asana.com/0/159908330244/577350817064
          // disabled here:
          /*
          if (msg.session)
            var old_session = self.sessions[msg.session];
          if (old_session) {
            // Resuming a session
            socket.meteor_session = old_session;
          }
          else */ {
            // Creating a new session
            socket.meteor_session = new Meteor._LivedataSession(self);
            self.sessions[socket.meteor_session.id] = socket.meteor_session;
          }

          socket.send(JSON.stringify({msg: 'connected',
                                      session: socket.meteor_session.id}));
          // will kick off previous connection, if any
          socket.meteor_session.connect(socket);
          return;
        }

        if (!socket.meteor_session) {
          sendError('Must connect first', msg);
          return;
        }
        socket.meteor_session.processMessage(msg, socket);
      } catch (e) {
        // XXX print stack nicely
        Meteor._debug("Internal exception while processing message", msg,
                      e.stack);
      }
    });

    socket.on('close', function () {
      if (socket.meteor_session)
        socket.meteor_session.detach(socket);
    });
  });

  // Every minute, clean up sessions that have been abandoned for 15
  // minutes. Also run result cache cleanup.
  // XXX at scale, we'll want to have a separate timer for each
  // session, and stagger them
  Meteor.setInterval(function () {
    var now = +(new Date);
    _.each(self.sessions, function (s) {
      s.cleanup();
      if (!s.socket && (now - s.last_detach_time) > 15 * 60 * 1000)
        s.destroy();
    });
  }, 1 * 60 * 1000);
};

_.extend(Meteor._LivedataServer.prototype, {
  /**
   * Register a publish handler function.
   *
   * @param name {String} identifier for query
   * @param handler {Function} publish handler
   * @param options {Object}
   *
   * Server will call handler function on each new subscription,
   * either when receiving DDP sub message for a named subscription, or on
   * DDP connect for a universal subscription.
   *
   * If name is null, this will be a subscription that is
   * automatically established and permanently on for all connected
   * client, instead of a subscription that can be turned on and off
   * with subscribe().
   *
   * options to contain:
   *  - (mostly internal) is_auto: true if generated automatically
   *    from an autopublish hook. this is for cosmetic purposes only
   *    (it lets us determine whether to print a warning suggesting
   *    that you turn off autopublish.)
   */
  publish: function (name, handler, options) {
    var self = this;

    options = options || {};

    if (name && name in self.publish_handlers) {
      Meteor._debug("Ignoring duplicate publish named '" + name + "'");
      return;
    }

    if (!self.on_autopublish && !options.is_auto) {
      // They have autopublish on, yet they're trying to manually
      // picking stuff to publish. They probably should turn off
      // autopublish. (This check isn't perfect -- if you create a
      // publish before you turn on autopublish, it won't catch
      // it. But this will definitely handle the simple case where
      // you've added the autopublish package to your app, and are
      // calling publish from your app code.)
      if (!self.warned_about_autopublish) {
        self.warned_about_autopublish = true;
        Meteor._debug(
"** You've set up some data subscriptions with Meteor.publish(), but\n" +
"** you still have autopublish turned on. Because autopublish is still\n" +
"** on, your Meteor.publish() calls won't have much effect. All data\n" +
"** will still be sent to all clients.\n" +
"**\n" +
"** Turn off autopublish by removing the autopublish package:\n" +
"**\n" +
"**   $ meteor remove autopublish\n" +
"**\n" +
"** .. and make sure you have Meteor.publish() and Meteor.subscribe() calls\n" +
"** for each collection that you want clients to see.\n");
      }
    }

    if (name)
      self.publish_handlers[name] = handler;
    else
      self.universal_publish_handlers.push(handler);
  },

  methods: function (methods) {
    var self = this;
    _.each(methods, function (func, name) {
      if (self.method_handlers[name])
        throw new Error("A method named '" + name + "' is already defined");
      self.method_handlers[name] = func;
    });
  },

  call: function (name /*, arguments */) {
    // if it's a function, the last argument is the result callback,
    // not a parameter to the remote method.
    var args = Array.prototype.slice.call(arguments, 1);
    if (args.length && typeof args[args.length - 1] === "function")
      var callback = args.pop();
    return this.apply(name, args, callback);
  },

  // @param options {Optional Object}
  // @param callback {Optional Function}
  apply: function (name, args, options, callback) {
    var self = this;

    // We were passed 3 arguments. They may be either (name, args, options)
    // or (name, args, callback)
    if (!callback && typeof options === 'function') {
      callback = options;
      options = {};
    }
    options = options || {};

    if (callback)
      // It's not really necessary to do this, since we immediately
      // run the callback in this fiber before returning, but we do it
      // anyway for regularity.
      callback = Meteor.bindEnvironment(callback, function (e) {
        // XXX improve error message (and how we report it)
        Meteor._debug("Exception while delivering result of invoking '" +
                      name + "'", e.stack);
      });

    // Run the handler
    var handler = self.method_handlers[name];
    if (!handler)
      var exception = new Meteor.Error(404, "Method not found");
    else {
      // If this is a method call from within another method, get the
      // user state from the outer method, otherwise don't allow
      // setUserId to be called
      var userId = null;
      var setUserId = function() {
        throw new Error("Can't call setUserId on a server initiated method call");
      };
      var currentInvocation = Meteor._CurrentInvocation.get();
      if (currentInvocation) {
        userId = currentInvocation.userId();
        setUserId = function(userId) {
          currentInvocation.setUserId(userId);
        };
      }

      var invocation = new Meteor._MethodInvocation(
        false /* isSimulation */, userId, setUserId);
      try {
        var ret = Meteor._CurrentInvocation.withValue(invocation, function () {
          return handler.apply(invocation, args);
        });
      } catch (e) {
        var exception = e;
      }
    }

    // Return the result in whichever way the caller asked for it
    if (callback) {
      callback(exception, ret);
      return;
    }
    if (exception)
      throw exception;
    return ret;
  },

  // A much more elegant way to do this would be: let any autopublish
  // provider (eg, mongo-livedata) declare a weak package dependency
  // on the autopublish package, then have that package simply set a
  // flag that eg the Collection constructor checks, and autopublishes
  // if necessary.
  autopublish: function () {
    var self = this;
    _.each(self.on_autopublish || [], function (f) { f(); });
    self.on_autopublish = null;
  },

  onAutopublish: function (f) {
    var self = this;
    if (self.on_autopublish)
      self.on_autopublish.push(f);
    else
      f();
  }
});


  <title>coffeeless</title>

coffeeless

  Welcome to Meteor! Here is a button for you to press.

  {{> button_demo }}

<template name="button_demo">

    <input type="button" value="Button">

    This delightful button has

    {{#if never_pressed}}
      never been pressed! Won't you be the first?
    {{else}}
      been pressed {{press_count}} times.
    {{/if}}

</template>


Package.describe({
  summary: "Better random number and UUIDv4 generators",
  internal: true
});

Package.on_use(function (api, where) {
  where = where || ['client', 'server'];
  api.add_files('uuid.js', where);
});