Streamline route/request path handling and split params + body in requests (#2361)

Fixes #2360
Fixes #1138
Fixes #1788 a little less hackishly
Probably fixes a few other issues I'm not aware of.

This more or less goes with @lhorie's comment here, just with a minor name
change from `query` to `params`:

https://github.com/MithrilJS/mithril.js/issues/1138#issuecomment-231363395

Specifically, here's what this patch entails:

- I changed `data` and `useBody` to `params` and `body` in `m.request`.
  Migration is trivial: just use `params` or `body` depending on which you
  intend to send. Most servers do actually care where the data goes, so you can
  generally pretty easily translate this accordingly. If you *really* need the
  old behavior, pass the old value in `params` and if `method === "GET"` or
  `method === "TRACE"`, also in `body`.
- I opened up all methods to have request bodies.
- I fixed `m.parseQueryString` to prefer later values over earlier values and
  to ensure that objects and arrays are persisted across both hash and query
  param parsing. That method also accepts an existing key/value map to append
  to, to simplify deduplication.
- I normalized path interpolation to be identical between routes and requests.
- I no longer include interpolated values in query strings. If you need to
  duplicate values again, rename the interpolation to be a distinct property
  and pass the value you want to duplicate as it.
- I converted `m.route` to use pre-compiled routes instead of its existing
  system of dynamic runtime checking. This shouldn't have a major effect on
  performance short-term, but it'll ease the migration to built-in userland
  components and make it a little easier to reconcile. It'll also come handy
  for large numbers of routes.
- I added support for matching routes like `"/:file.:ext"` or
  `"/:lang-:region"`, giving each defined semantics.
- I added support for matching against routes with static query strings, such
  as `"/edit?type=image": { ... }`.
- I'm throwing a few new informative errors.
- And I've updated the docs accordingly.

I also made a few drive-by edits:

- I fixed a bug in the `Stream.HALT` warning where it warned all but the first
  usage when the intent was to warn only on first use.
- Some of the tests were erroneously using `Stream.HALT` when they should've
  been using `Stream.SKIP`. I've fixed the tests to only test that
  `Stream.HALT === Stream.SKIP` and that it only warns on first use.
- The `m.request` and `m.jsonp` docs signatures were improved to more clearly
  explain how `m.request(url, options?)` and `m.jsonp(url, options?)` translate
  to `m.request(options)` and `m.jsonp(options)` respectively.

-----

There is some justification to these changes:

- In general, it matters surprisingly more than you would expect how things
  translate to HTTP requests. So the comment there suggesting a thing that
  papers over the difference has led to plenty of confusion in both Gitter and
  in GitHub issues.

- A lot of servers expect a GET with a body and no parameters, and leaving
  `m.request` open to working with that makes it much more flexible.

- Sometimes, servers expect a POST with query parameters *instead* of a JSON
  object. I've seen this quite a bit, even with more popular REST APIs like
  Stack Overflow's.

- I've encountered a few servers that expect both parameters and a body, each
  with distinct semantic meaning, so the separation makes it much easier to
  translate into a request.

- Most of the time, path segments are treated individually, and URL-escaping
  the contents is much less error-prone. It also avoids being potentially
  lossy, and when the variable in question isn't trusted, escaping the path
  segment enables you to pass it through the URL and not risk being redirected
  to unexpected locations, avoiding some risks of vulnerabilities and client
  side crashes.

If you really don't care how the template and parameters translate to an
eventual URL, just pass the same object for the `params` and `body` and use
`:param...` for each segment. Either way, the more explicit nature should help
a lot in making the intent clearer, whether you care or not.
This commit is contained in:
Isiah Meadows 2019-05-29 09:28:40 -04:00 committed by GitHub
parent b17b00e9eb
commit 58f1c74394
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
28 changed files with 1068 additions and 168 deletions

View file

@ -36,11 +36,11 @@ module.exports = function($window, redrawService) {
if (payload.onmatch) {
Promise.resolve(payload.onmatch(params, path, route)).then(function(resolved) {
update(payload, resolved)
}, bail)
}, function () { bail(path) })
}
else update(payload, "div")
}
}, bail)
}, bail, defaultRoute)
}
route.set = function(path, data, options) {
if (lastUpdate != null) {

View file

@ -990,7 +990,8 @@ o.spec("route", function() {
$window.location.href = prefix + "/a"
route(root, "/", {
"/a": {view: view},
"/b": {onmatch: onmatch}
"/b": {onmatch: onmatch},
"/": {view: function() {}}
})
o(view.callCount).equals(1)

41
docs/buildPathname.md Normal file
View file

@ -0,0 +1,41 @@
# buildPathname(object)
- [Description](#description)
- [Signature](#signature)
- [How it works](#how-it-works)
---
### Description
Turns a [path template](paths.md) and a parameters object into a string of form `/path/user?a=1&b=2`
```javascript
var querystring = m.buildPathname("/path/:id", {id: "user", a: "1", b: "2"})
// "/path/user?a=1&b=2"
```
---
### Signature
`querystring = m.buildPathname(object)`
Argument | Type | Required | Description
------------ | ------------------------------------------ | -------- | ---
`object` | `Object` | Yes | A key-value map to be converted into a string
**returns** | `String` | | A string representing the input object
[How to read signatures](signatures.md)
---
### How it works
The `m.buildPathname` creates a [path name](paths.md) from a path template and a parameters object. It's useful for building URLs, and it's what [`m.route`](route.md), [`m.request`](request.md), and [`m.jsonp`](jsonp.md) all use internally to interpolate paths. It uses [`m.buildQueryString`](buildQueryString.md) to generate the query parameters to append to the path name.
```javascript
var querystring = m.buildPathname("/path/:id", {id: "user", a: 1, b: 2})
// querystring is "/path/user?a=1&b=2"
```

View file

@ -35,6 +35,10 @@
- cast className using toString ([#2309](https://github.com/MithrilJS/mithril.js/pull/2309))
- render: call attrs' hooks first, with express exception of `onbeforeupdate` to allow attrs to block components from even diffing ([#2297](https://github.com/MithrilJS/mithril.js/pull/2297))
- API: `m.withAttr` removed. ([#2317](https://github.com/MithrilJS/mithril.js/pull/2317))
- request: `data` has now been split to `params` and `body` and `useBody` has been removed in favor of just using `body`. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
- route, request: Interpolated arguments are URL-escaped (and for declared routes, URL-unescaped) automatically. If you want to use a raw route parameter, use a variadic parameter like in `/asset/:path.../view`. This was previously only available in `m.route` route definitions, but it's now usable in both that and where paths are accepted. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
- route, request: Interpolated arguments are *not* appended to the query string. This means `m.request({url: "/api/user/:id/get", params: {id: user.id}})` would result in a request like `GET /api/user/1/get`, not one like `GET /api/user/1/get?id=1`. If you really need it in both places, pass the same value via two separate parameters with the non-query-string parameter renamed, like in `m.request({url: "/api/user/:urlID/get", params: {id: user.id, urlID: user.id}})`. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
- route, request: `m.route.set`, `m.request`, and `m.jsonp` all use the same path template syntax now, and vary only in how they receive their parameters. Furthermore, declared routes in `m.route` shares the same syntax and semantics, but acts in reverse as if via pattern matching. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
#### News
@ -55,6 +59,10 @@
- `m()` itself from `mithril` is exported as the default export.
- `mithril/stream`'s primary export is exported as the default export.
- fragments: allow same attrs/children overloading logic as hyperscript ([#2328](https://github.com/MithrilJS/mithril.js/pull/2328))
- route: Declared routes may check against path names with query strings. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
- route: Declared routes in `m.route` now support `-` and `.` as delimiters for path segments. This means you can have a route like `"/edit/:file.:ext"`. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
- Previously, this was possible to do in `m.route.set`, `m.request`, and `m.jsonp`, but it was wholly untested for and also undocumented.
- API: `m.buildPathname` and `m.parsePathname` added. ([#2361](https://github.com/MithrilJS/mithril.js/pull/2361))
#### Bug fixes

View file

@ -26,12 +26,12 @@ m.jsonp({
### Signature
`promise = m.jsonp([url,] options)`
`promise = m.jsonp(options)`
Argument | Type | Required | Description
---------------------- | --------------------------------- | -------- | ---
`url` | `String` | No | If present, it's equivalent to having the option `{url: url}`. Values passed to the `options` argument override options set via this shorthand.
`options.url` | `String` | Yes | The URL to send the request to. The URL may be either absolute or relative, and it may contain [interpolations](#dynamic-urls).
`options` | `Object` | Yes | The request options to pass.
`options.url` | `String` | Yes | The [path name](paths.md) to send the request to, optionally interpolated with values from `options.data`.
`options.data` | `any` | No | The data to be interpolated into the URL and serialized into the querystring.
`options.type` | `any = Function(any)` | No | A constructor to be applied to each object in the response. Defaults to the [identity function](https://en.wikipedia.org/wiki/Identity_function).
`options.callbackName` | `String` | No | The name of the function that will be called as the callback. Defaults to a randomized string (e.g. `_mithril_6888197422121285_0({a: 1})`
@ -39,6 +39,16 @@ Argument | Type | Required | Descript
`options.background` | `Boolean` | No | If `false`, redraws mounted components upon completion of the request. If `true`, it does not. Defaults to `false`.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through `type` method
`promise = m.jsonp(url, options)`
Argument | Type | Required | Description
----------- | --------- | -------- | ---
`url` | `String` | Yes | The [path name](paths.md) to send the request to. `options.url` overrides this when present.
`options` | `Object` | No | The request options to pass.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `type` method
This second form is mostly equivalent to `m.jsonp(Object.assign({url: url}, options))`, just it does not depend on the ES6 global `Object.assign` internally.
[How to read signatures](signatures.md)
---
@ -87,4 +97,3 @@ m.jsonp({
console.log(response.data.login) // logs "lhorie"
})
```

View file

@ -12,6 +12,7 @@
- [Testing](testing.md)
- [Examples](examples.md)
- [3rd Party Integration](integrating-libs.md)
- [Path Handling](paths.md)
- Key concepts
- [Vnodes](vnodes.md)
- [Components](components.md)

42
docs/parsePathname.md Normal file
View file

@ -0,0 +1,42 @@
# parsePathname(string)
- [Description](#description)
- [Signature](#signature)
- [How it works](#how-it-works)
---
### Description
Turns a string of the form `/path/user?a=1&b=2` to an object
```javascript
var object = m.parsePathname("/path/user?a=1&b=2")
// {path: "/path/user", params: {a: "1", b: "2"}}
```
---
### Signature
`object = m.parsePathname(string)`
Argument | Type | Required | Description
------------ | -------- | -------- | ---
`string` | `String` | Yes | A URL
**returns** | `Object` | | A `{path, params}` pair where `path` is the [normalized path](paths.md#path-normalization) and `params` is the [parsed parameters](paths.md#parameter-normalization).
[How to read signatures](signatures.md)
---
### How it works
The `m.parsePathname` method creates an object from a path with a possible query string and hash string. It is useful for parsing a URL into more sensible paths, and it's what [`m.route`](route.md) uses internally to normalize paths to later match them. It uses [`m.parseQueryString`](parseQueryString.md) to parse the query parameters into an object.
```javascript
var data = m.parsePathname("/path/user?a=hello&b=world#random=hash&some=value")
// data.path is "/path/user"
// data.params is {a: "hello", b: "world", random: "hash", some: "value"}
```

View file

@ -19,12 +19,13 @@ var object = m.parseQueryString("a=1&b=2")
### Signature
`object = m.parseQueryString(string)`
`object = m.parseQueryString(string, object)`
Argument | Type | Required | Description
------------ | ------------------------------------------ | -------- | ---
`string` | `String` | Yes | A querystring
**returns** | `Object` | | A key-value map
`object` | `Object` | No | An existing key-value map to merge values into, potentially from a previous `m.parseQueryString` call
**returns** | `Object` | | A key-value map, `object` if provided
[How to read signatures](signatures.md)
@ -68,4 +69,4 @@ Querystrings that contain bracket notation are correctly parsed into deep data s
m.parseQueryString("a[0]=hello&a[1]=world")
// data is {a: ["hello", "world"]}
```
```

132
docs/paths.md Normal file
View file

@ -0,0 +1,132 @@
# Path Handling
- [Path types](#path-types)
- [Path parameters](#path-parameters)
- [Parameter normalization](#parameter-normalization)
- [Path normalization](#path-normalization)
-----
[`m.route`](route.md), [`m.request`](request.md), and [`m.jsonp`](jsonp.md) each have a concept called a path. This is used to generate the URL you route to or fetch from.
### Path types
There are two general types of paths: raw paths and parameterized paths.
- Raw paths are simply strings used directly as URLs. Nothing is substituted or even split. It's just normalized with all the parameters appended to the end.
- Parameterized paths let you insert values into paths, escaped by default for convenience and safety against URL injection.
For [`m.request`](request.md) and [`m.jsonp`](jsonp.md), these can be pretty much any URL, but for [routes](route.md), these can only be absolute URL path names without schemes or domains.
### Path parameters
Path parameters are themselves pretty simple. They come in two forms:
- `:foo` - This injects a simple `params.foo` into the URL, escaping its value first.
- `:foo...` - This injects a raw `params.foo` path into the URL without escaping anything.
You're probably wondering what that `params` object is supposed to be. It's pretty simple: it's the `params` in either [`m.route.set(path, params)`](route.md#mrouteset), [`m.request({url, params})`](request.md#signature), or [`m.jsonp({url, params})`](jsonp.md#signature).
When receiving routes via [`m.route(root, defaultRoute, routes)`](route.md#signature), you can use these parameters to *extract* values from routes. They work basically the same way as generating the paths, just in the opposite direction.
```javascript
// Edit a single item
m.route(document.body, "/edit/1", {
"/edit/:id": {
view: function() {
return [
m(Menu),
m("h1", "Editing user " + m.route.param("id"))
]
}
},
})
// Edit an item identified by path
m.route(document.body, "/edit/pictures/image.jpg", {
"/edit/:file...": {
view: function() {
return [
m(Menu),
m("h1", "Editing file " + m.route.param("file"))
]
}
},
})
```
In the first example, assuming you're navigating to the default route in each, `m.route.param("id")` would be read as `"1"` and `m.route.param("file")` would be read as `pictures/image.jpg`.
Path parameters may be delimited by either a `/`, `-`, or `.`. This lets you have dynamic path segments, and they're considerably more flexible than just a path name. For example, you could match against routes like `"/edit/:name.:ext"` for editing based on file extension or `"/:lang-:region/view"` for a localized route.
Path parameters are greedy: given a declared route `"/edit/:name.:ext"`, if you navigate to `/edit/file.test.png`, the parameters extracted will be `{name: "file.test", ext: "png"}`, not `{name: "file", ext: "test.png"}`. Similarly, given `"/route/:path.../view/:child..."`, if you go to `/route/foo/view/bar/view/baz`, the parameters extracted will be `{path: "foo/view/bar", child: "baz"}`.
### Parameter normalization
Path parameters that are interpolated into path names are omitted from the query string, for convenience and to keep the path name reasonably readable. For example, this sends a server request of `GET /api/user/1/connections?sort=name-asc`, omitting the duplicate `id=1` in the URL string.
```javascript
m.request({
url: "https://example.com/api/user/:userID/connections",
params: {
userID: 1,
sort: "name-asc"
}
})
```
You can also specify parameters explicitly in the query string itself, such as in this, which is equivalent to the above:
```javascript
m.request({
url: "https://example.com/api/user/:userID/connections?sort=name-asc",
params: {
userID: 1
}
})
```
And of course, you can mix and match. This fires a request to `GET /api/user/1/connections?sort=name-asc&first=10`.
```javascript
m.request({
url: "https://example.com/api/user/:userID/connections?sort=name-asc",
params: {
userID: 1,
first: 10
}
})
```
This even extends to route matching: you can match against a route *with* explicit query strings. It retains the matched parameter for convenience, so you can still access them via vnode parameters or via [`m.route.param`](route.md#mrouteparam). Note that although this *is* possible, it's not generally recommended, since you should prefer paths for pages. It could sometimes useful if you need to generate a somewhat different view just for a particular file type, but it still logically is a query-like parameter, not a whole separate page.
```javascript
// Note: this is generally *not* recommended - you should prefer paths for route
// declarations, not query strings.
m.route(document.body, "/edit/1", {
"/edit?type=image": {
view: function() {
return [
m(Menu),
m("h1", "Editing photo")
]
}
},
"/edit": {
view: function() {
return [
m(Menu),
m("h1", "Editing " + m.route.param("type"))
]
}
}
})
```
Note that query parameters are implicit - you don't need to name them to accept them. You can match based on an existing value, like in `"/edit?type=image"`, but you don't need to use `"/edit?type=:type"` to accept the value. In fact, Mithril would treat that as you trying to literally match against `m.route.param("type") === ":type"`. Or in summary, use `m.route.param("key")` to extract parameters - it simplifies things.
### Path normalization
Parsed paths are always returned with all the duplicate parameters and extra slashes dropped, and they always start with a slash. These little differences often get in the way, and it makes routing and path handling a lot more complicated than it should be. Mithril internally normalizes paths for routing, but it does not expose the current, normalized route directly. (You could compute it via [`m.parsePathname(m.route.get()).path`](parsePathname.md).)
When parameters are deduplicated during matching, parameters in the query string are preferred over parameters in the path name, and parameters towards the end of the URL are preferred over parameters closer to the start of the URL.

View file

@ -38,13 +38,13 @@ m.request({
### Signature
`promise = m.request([url,] options)`
`promise = m.request(options)`
Argument | Type | Required | Description
------------------------- | --------------------------------- | -------- | ---
`url` | `String` | No | If present, it's equivalent to having the options `{method: "GET", url: url}`. Values passed to the `options` argument override options set via this shorthand.
`options` | `Object` | Yes | The request options to pass.
`options.method` | `String` | No | The HTTP method to use. This value should be one of the following: `GET`, `POST`, `PUT`, `PATCH`, `DELETE`, `HEAD` or `OPTIONS`. Defaults to `GET`.
`options.url` | `String` | Yes | The URL to send the request to. The URL may be either absolute or relative, and it may contain [interpolations](#dynamic-urls).
`options.url` | `String` | Yes | The [path name](paths.md) to send the request to, optionally interpolated with values from `options.data`.
`options.data` | `any` | No | The data to be interpolated into the URL and serialized into the querystring (for GET requests) or body (for other types of requests).
`options.async` | `Boolean` | No | Whether the request should be asynchronous. Defaults to `true`.
`options.user` | `String` | No | A username for HTTP authorization. Defaults to `undefined`.
@ -62,6 +62,16 @@ Argument | Type | Required | Descr
`options.background` | `Boolean` | No | If `false`, redraws mounted components upon completion of the request. If `true`, it does not. Defaults to `false`.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods
`promise = m.request(url, options)`
Argument | Type | Required | Description
----------- | --------- | -------- | ---
`url` | `String` | Yes | The [path name](paths.md) to send the request to. `options.url` overrides this when present.
`options` | `Object` | No | The request options to pass.
**returns** | `Promise` | | A promise that resolves to the response data, after it has been piped through the `extract`, `deserialize` and `type` methods
This second form is mostly equivalent to `m.request(Object.assign({url: url}, options))`, just it does not depend on the ES6 global `Object.assign` internally.
[How to read signatures](signatures.md)
---

View file

@ -71,7 +71,7 @@ Redirects to a matching route, or to the default route if no matching routes can
Argument | Type | Required | Description
----------------- | --------- | -------- | ---
`path` | `String` | Yes | The path to route to, without a prefix. The path may include slots for routing parameters
`path` | `String` | Yes | The [path name](paths.md) to route to, without a prefix. The path may include parameters, interpolated with values from `data`.
`data` | `Object` | No | Routing parameters. If `path` has routing parameter slots, the properties of this object are interpolated into the path string
`options.replace` | `Boolean` | No | Whether to create a new history entry or to replace the current one. Defaults to false
`options.state` | `Object` | No | The `state` object to pass to the underlying `history.pushState` / `history.replaceState` call. This state object becomes available in the `history.state` property, and is merged into the [routing parameters](#routing-parameters) object. Note that this option only works when using the pushState API, but is ignored if the router falls back to hashchange mode (i.e. if the pushState API is not available)
@ -209,7 +209,7 @@ Routing is a system that allows creating Single-Page-Applications (SPA), i.e. ap
It enables seamless navigability while preserving the ability to bookmark each page individually, and the ability to navigate the application via the browser's history mechanism.
Routing without page refreshes is made partially possible by the [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState()_method) API. Using this API, it's possible to programmatically change the URL displayed by the browser after a page has loaded, but it's the application developer's responsibility to ensure that navigating to any given URL from a cold state (e.g. a new tab) will render the appropriate markup.
Routing without page refreshes is made partially possible by the [`history.pushState`](https://developer.mozilla.org/en-US/docs/Web/API/History_API#The_pushState%28%29_method) API. Using this API, it's possible to programmatically change the URL displayed by the browser after a page has loaded, but it's the application developer's responsibility to ensure that navigating to any given URL from a cold state (e.g. a new tab) will render the appropriate markup.
#### Routing strategies
@ -293,7 +293,7 @@ When navigating to routes, there's no need to explicitly specify the router pref
### Routing parameters
Sometimes we want to have a variable id or similar data appear in a route, but we don't want to explicitly specify a separate route for every possible id. In order to achieve that, Mithril supports parameterized routes:
Sometimes we want to have a variable id or similar data appear in a route, but we don't want to explicitly specify a separate route for every possible id. In order to achieve that, Mithril supports [parameterized routes](paths.md#path-parameters):
```javascript
var Edit = {

View file

@ -19,6 +19,8 @@ m.request = requestService.request
m.jsonp = requestService.jsonp
m.parseQueryString = require("./querystring/parse")
m.buildQueryString = require("./querystring/build")
m.parsePathname = require("./pathname/parse")
m.buildPathname = require("./pathname/build")
m.version = "bleeding-edge"
m.vnode = require("./render/vnode")
m.PromisePolyfill = require("./promise/polyfill")

5
pathname/assign.js Normal file
View file

@ -0,0 +1,5 @@
"use strict"
module.exports = Object.assign || function(target, source) {
Object.keys(source).forEach(function(key) { target[key] = source[key] })
}

43
pathname/build.js Normal file
View file

@ -0,0 +1,43 @@
"use strict"
var buildQueryString = require("../querystring/build")
var assign = require("./assign")
// Returns `path` from `template` + `params`
module.exports = function(template, params) {
if ((/:([^\/\.-]+)(\.{3})?:/).test(template)) {
throw new SyntaxError("Template parameter names *must* be separated")
}
if (params == null) return template
var queryIndex = template.indexOf("?")
var hashIndex = template.indexOf("#")
var queryEnd = hashIndex < 0 ? template.length : hashIndex
var pathEnd = queryIndex < 0 ? queryEnd : queryIndex
var path = template.slice(0, pathEnd)
var query = {}
assign(query, params)
var resolved = path.replace(/:([^\/\.-]+)(\.{3})?/g, function(m, key, variadic) {
delete query[key]
// If no such parameter exists, don't interpolate it.
if (params[key] == null) return m
// Escape normal parameters, but not variadic ones.
return variadic ? params[key] : encodeURIComponent(String(params[key]))
})
// In case the template substitution adds new query/hash parameters.
var newQueryIndex = resolved.indexOf("?")
var newHashIndex = resolved.indexOf("#")
var newQueryEnd = newHashIndex < 0 ? resolved.length : newHashIndex
var newPathEnd = newQueryIndex < 0 ? newQueryEnd : newQueryIndex
var result = resolved.slice(0, newPathEnd)
if (queryIndex >= 0) result += "?" + template.slice(queryIndex, queryEnd)
if (newQueryIndex >= 0) result += (queryIndex < 0 ? "?" : "&") + resolved.slice(newQueryIndex, newQueryEnd)
var querystring = buildQueryString(query)
if (querystring) result += (queryIndex < 0 && newQueryIndex < 0 ? "?" : "&") + querystring
if (hashIndex >= 0) result += template.slice(hashIndex)
if (newHashIndex >= 0) result += (hashIndex < 0 ? "" : "&") + resolved.slice(newHashIndex)
return result
}

View file

@ -0,0 +1,43 @@
"use strict"
var parsePathname = require("./parse")
// Compiles a template into a function that takes a resolved path (without query
// strings) and returns an object containing the template parameters with their
// parsed values. This expects the input of the compiled template to be the
// output of `parsePathname`. Note that it does *not* remove query parameters
// specified in the template.
module.exports = function(template) {
var templateData = parsePathname(template)
var templateKeys = Object.keys(templateData.params)
var keys = []
var regexp = new RegExp("^" + templateData.path.replace(
// I escape literal text so people can use things like `:file.:ext` or
// `:lang-:locale` in routes. This is all merged into one pass so I
// don't also accidentally escape `-` and make it harder to detect it to
// ban it from template parameters.
/:([^\/.-]+)(\.{3}|\.(?!\.)|-)?|[\\^$*+.()|\[\]{}]/g,
function(m, key, extra) {
if (key == null) return "\\" + m
keys.push({k: key, r: extra === "..."})
if (extra === "...") return "(.*)"
if (extra === ".") return "([^/]+)\\."
return "([^/]+)" + (extra || "")
}
) + "$")
return function(data) {
// First, check the params. Usually, there isn't any, and it's just
// checking a static set.
for (var i = 0; i < templateKeys.length; i++) {
if (templateData.params[templateKeys[i]] !== data.params[templateKeys[i]]) return false
}
// If no interpolations exist, let's skip all the ceremony
if (!keys.length) return regexp.test(data.path)
var values = regexp.exec(data.path)
if (values == null) return false
for (var i = 0; i < keys.length; i++) {
data.params[keys[i].k] = keys[i].r ? values[i + 1] : decodeURIComponent(values[i + 1])
}
return true
}
}

24
pathname/parse.js Normal file
View file

@ -0,0 +1,24 @@
"use strict"
var parseQueryString = require("../querystring/parse")
// Returns `{path, params}` from `url`
module.exports = function(url) {
var queryIndex = url.indexOf("?")
var hashIndex = url.indexOf("#")
var queryEnd = hashIndex < 0 ? url.length : hashIndex
var pathEnd = queryIndex < 0 ? queryEnd : queryIndex
var path = url.slice(0, pathEnd).replace(/\/{2,}/g, "/")
var params = {}
if (!path) path = "/"
else {
if (path[0] !== "/") path = "/" + path
if (path.length > 1 && path[path.length - 1] === "/") path = path.slice(0, -1)
}
// Note: these are reversed because `parseQueryString` appends parameters
// only if they don't exist. Please don't flip them.
if (queryIndex >= 0) parseQueryString(url.slice(queryIndex + 1, queryEnd), params)
if (hashIndex >= 0) parseQueryString(url.slice(hashIndex + 1), params)
return {path: path, params: params}
}

19
pathname/tests/index.html Normal file
View file

@ -0,0 +1,19 @@
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<script src="../../module/module.js"></script>
<script src="../../ospec/ospec.js"></script>
<script src="../../pathname/build.js"></script>
<script src="../../pathname/parse.js"></script>
<script src="../../pathname/parseTemplate.js"></script>
<script src="test-buildPathname.js"></script>
<script src="test-parsePathname.js"></script>
<script src="test-parseTemplate.js"></script>
<script>require("../../ospec/ospec").run()</script>
</body>
</html>

View file

@ -0,0 +1,109 @@
"use strict"
var o = require("../../ospec/ospec")
var buildPathname = require("../../pathname/build")
o.spec("buildPathname", function() {
function test(prefix) {
o("returns path if no params", function () {
var string = buildPathname(prefix + "/route/foo", undefined)
o(string).equals(prefix + "/route/foo")
})
o("skips interpolation if no params", function () {
var string = buildPathname(prefix + "/route/:id", undefined)
o(string).equals(prefix + "/route/:id")
})
o("appends query strings", function () {
var string = buildPathname(prefix + "/route/foo", {a: "b", c: 1})
o(string).equals(prefix + "/route/foo?a=b&c=1")
})
o("inserts template parameters at end", function () {
var string = buildPathname(prefix + "/route/:id", {id: "1"})
o(string).equals(prefix + "/route/1")
})
o("inserts template parameters at beginning", function () {
var string = buildPathname(prefix + "/:id/foo", {id: "1"})
o(string).equals(prefix + "/1/foo")
})
o("inserts template parameters at middle", function () {
var string = buildPathname(prefix + "/route/:id/foo", {id: "1"})
o(string).equals(prefix + "/route/1/foo")
})
o("inserts variadic paths", function () {
var string = buildPathname(prefix + "/route/:foo...", {foo: "id/1"})
o(string).equals(prefix + "/route/id/1")
})
o("inserts variadic paths with initial slashes", function () {
var string = buildPathname(prefix + "/route/:foo...", {foo: "/id/1"})
o(string).equals(prefix + "/route//id/1")
})
o("skips template parameters at end if param missing", function () {
var string = buildPathname(prefix + "/route/:id", {param: 1})
o(string).equals(prefix + "/route/:id?param=1")
})
o("skips template parameters at beginning if param missing", function () {
var string = buildPathname(prefix + "/:id/foo", {param: 1})
o(string).equals(prefix + "/:id/foo?param=1")
})
o("skips template parameters at middle if param missing", function () {
var string = buildPathname(prefix + "/route/:id/foo", {param: 1})
o(string).equals(prefix + "/route/:id/foo?param=1")
})
o("skips variadic template parameters if param missing", function () {
var string = buildPathname(prefix + "/route/:foo...", {param: "/id/1"})
o(string).equals(prefix + "/route/:foo...?param=%2Fid%2F1")
})
o("handles escaped values", function() {
var data = buildPathname(prefix + "/route/:foo", {"foo": ";:@&=+$,/?%#"})
o(data).equals(prefix + "/route/%3B%3A%40%26%3D%2B%24%2C%2F%3F%25%23")
})
o("handles unicode", function() {
var data = buildPathname(prefix + "/route/:ö", {"ö": "ö"})
o(data).equals(prefix + "/route/%C3%B6")
})
o("handles zero", function() {
var string = buildPathname(prefix + "/route/:a", {a: 0})
o(string).equals(prefix + "/route/0")
})
o("handles false", function() {
var string = buildPathname(prefix + "/route/:a", {a: false})
o(string).equals(prefix + "/route/false")
})
o("handles dashes", function() {
var string = buildPathname(prefix + "/:lang-:region/route", {
lang: "en",
region: "US"
})
o(string).equals(prefix + "/en-US/route")
})
o("handles dots", function() {
var string = buildPathname(prefix + "/:file.:ext/view", {
file: "image",
ext: "png"
})
o(string).equals(prefix + "/image.png/view")
})
}
o.spec("absolute", function() { test("") })
o.spec("relative", function() { test("..") })
o.spec("absolute + domain", function() { test("https://example.com") })
o.spec("absolute + `file:`", function() { test("file://") })
})

View file

@ -0,0 +1,233 @@
"use strict"
var o = require("../../ospec/ospec")
var parsePathname = require("../../pathname/parse")
var compileTemplate = require("../../pathname/compileTemplate")
o.spec("compileTemplate", function() {
o("checks empty string", function() {
var data = parsePathname("/")
o(compileTemplate("/")(data)).equals(true)
o(data.params).deepEquals({})
})
o("checks identical match", function() {
var data = parsePathname("/foo")
o(compileTemplate("/foo")(data)).equals(true)
o(data.params).deepEquals({})
})
o("checks identical mismatch", function() {
var data = parsePathname("/bar")
o(compileTemplate("/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks single parameter", function() {
var data = parsePathname("/1")
o(compileTemplate("/:id")(data)).equals(true)
o(data.params).deepEquals({id: "1"})
})
o("checks single variadic parameter", function() {
var data = parsePathname("/some/path")
o(compileTemplate("/:id...")(data)).equals(true)
o(data.params).deepEquals({id: "some/path"})
})
o("checks single parameter with extra match", function() {
var data = parsePathname("/1/foo")
o(compileTemplate("/:id/foo")(data)).equals(true)
o(data.params).deepEquals({id: "1"})
})
o("checks single parameter with extra mismatch", function() {
var data = parsePathname("/1/bar")
o(compileTemplate("/:id/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks single variadic parameter with extra match", function() {
var data = parsePathname("/some/path/foo")
o(compileTemplate("/:id.../foo")(data)).equals(true)
o(data.params).deepEquals({id: "some/path"})
})
o("checks single variadic parameter with extra mismatch", function() {
var data = parsePathname("/some/path/bar")
o(compileTemplate("/:id.../foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters", function() {
var data = parsePathname("/1/2")
o(compileTemplate("/:id/:name")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks incomplete multiple parameters", function() {
var data = parsePathname("/1")
o(compileTemplate("/:id/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters with extra match", function() {
var data = parsePathname("/1/2/foo")
o(compileTemplate("/:id/:name/foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks multiple parameters with extra mismatch", function() {
var data = parsePathname("/1/2/bar")
o(compileTemplate("/:id/:name/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters, last variadic, with extra match", function() {
var data = parsePathname("/1/some/path/foo")
o(compileTemplate("/:id/:name.../foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "some/path"})
})
o("checks multiple parameters, last variadic, with extra mismatch", function() {
var data = parsePathname("/1/some/path/bar")
o(compileTemplate("/:id/:name.../foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters", function() {
var data = parsePathname("/1/sep/2")
o(compileTemplate("/:id/sep/:name")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks incomplete multiple separated parameters", function() {
var data = parsePathname("/1")
o(compileTemplate("/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
data = parsePathname("/1/sep")
o(compileTemplate("/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters missing sep", function() {
var data = parsePathname("/1/2")
o(compileTemplate("/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters with extra match", function() {
var data = parsePathname("/1/sep/2/foo")
o(compileTemplate("/:id/sep/:name/foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks multiple separated parameters with extra mismatch", function() {
var data = parsePathname("/1/sep/2/bar")
o(compileTemplate("/:id/sep/:name/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters, last variadic, with extra match", function() {
var data = parsePathname("/1/sep/some/path/foo")
o(compileTemplate("/:id/sep/:name.../foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "some/path"})
})
o("checks multiple separated parameters, last variadic, with extra mismatch", function() {
var data = parsePathname("/1/sep/some/path/bar")
o(compileTemplate("/:id/sep/:name.../foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters + prefix", function() {
var data = parsePathname("/route/1/2")
o(compileTemplate("/route/:id/:name")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks incomplete multiple parameters + prefix", function() {
var data = parsePathname("/route/1")
o(compileTemplate("/route/:id/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters + prefix with extra match", function() {
var data = parsePathname("/route/1/2/foo")
o(compileTemplate("/route/:id/:name/foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks multiple parameters + prefix with extra mismatch", function() {
var data = parsePathname("/route/1/2/bar")
o(compileTemplate("/route/:id/:name/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple parameters + prefix, last variadic, with extra match", function() {
var data = parsePathname("/route/1/some/path/foo")
o(compileTemplate("/route/:id/:name.../foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "some/path"})
})
o("checks multiple parameters + prefix, last variadic, with extra mismatch", function() {
var data = parsePathname("/route/1/some/path/bar")
o(compileTemplate("/route/:id/:name.../foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters + prefix", function() {
var data = parsePathname("/route/1/sep/2")
o(compileTemplate("/route/:id/sep/:name")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks incomplete multiple separated parameters + prefix", function() {
var data = parsePathname("/route/1")
o(compileTemplate("/route/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
var data = parsePathname("/route/1/sep")
o(compileTemplate("/route/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters + prefix missing sep", function() {
var data = parsePathname("/route/1/2")
o(compileTemplate("/route/:id/sep/:name")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters + prefix with extra match", function() {
var data = parsePathname("/route/1/sep/2/foo")
o(compileTemplate("/route/:id/sep/:name/foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "2"})
})
o("checks multiple separated parameters + prefix with extra mismatch", function() {
var data = parsePathname("/route/1/sep/2/bar")
o(compileTemplate("/route/:id/sep/:name/foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks multiple separated parameters + prefix, last variadic, with extra match", function() {
var data = parsePathname("/route/1/sep/some/path/foo")
o(compileTemplate("/route/:id/sep/:name.../foo")(data)).equals(true)
o(data.params).deepEquals({id: "1", name: "some/path"})
})
o("checks multiple separated parameters + prefix, last variadic, with extra mismatch", function() {
var data = parsePathname("/route/1/sep/some/path/bar")
o(compileTemplate("/route/:id/sep/:name.../foo")(data)).equals(false)
o(data.params).deepEquals({})
})
o("checks query params match", function() {
var data = parsePathname("/route/1?foo=bar")
o(compileTemplate("/route/:id?foo=bar")(data)).equals(true)
o(data.params).deepEquals({id: "1", foo: "bar"})
})
o("checks query params mismatch", function() {
var data = parsePathname("/route/1?foo=bar")
o(compileTemplate("/route/:id?foo=1")(data)).equals(false)
o(data.params).deepEquals({foo: "bar"})
o(compileTemplate("/route/:id?bar=foo")(data)).equals(false)
o(data.params).deepEquals({foo: "bar"})
})
o("checks hash params match", function() {
var data = parsePathname("/route/1#foo=bar")
o(compileTemplate("/route/:id#foo=bar")(data)).equals(true)
o(data.params).deepEquals({id: "1", foo: "bar"})
})
o("checks hash params mismatch", function() {
var data = parsePathname("/route/1#foo=bar")
o(compileTemplate("/route/:id#foo=1")(data)).equals(false)
o(data.params).deepEquals({foo: "bar"})
o(compileTemplate("/route/:id#bar=foo")(data)).equals(false)
o(data.params).deepEquals({foo: "bar"})
})
o("checks dot before dot", function() {
var data = parsePathname("/file.test.png/edit")
o(compileTemplate("/:file.:ext/edit")(data)).equals(true)
o(data.params).deepEquals({file: "file.test", ext: "png"})
})
o("checks dash before dot", function() {
var data = parsePathname("/file-test.png/edit")
o(compileTemplate("/:file.:ext/edit")(data)).equals(true)
o(data.params).deepEquals({file: "file-test", ext: "png"})
})
o("checks dot before dash", function() {
var data = parsePathname("/file.test-png/edit")
o(compileTemplate("/:file-:ext/edit")(data)).equals(true)
o(data.params).deepEquals({file: "file.test", ext: "png"})
})
o("checks dash before dash", function() {
var data = parsePathname("/file-test-png/edit")
o(compileTemplate("/:file-:ext/edit")(data)).equals(true)
o(data.params).deepEquals({file: "file-test", ext: "png"})
})
})

View file

@ -0,0 +1,126 @@
"use strict"
var o = require("../../ospec/ospec")
var parsePathname = require("../../pathname/parse")
o.spec("parsePathname", function() {
o("parses empty string", function() {
var data = parsePathname("")
o(data).deepEquals({
path: "/",
params: {}
})
})
o("parses query at start", function() {
var data = parsePathname("?a=b&c=d")
o(data).deepEquals({
path: "/",
params: {a: "b", c: "d"}
})
})
o("parses hash at start", function() {
var data = parsePathname("#a=b&c=d")
o(data).deepEquals({
path: "/",
params: {a: "b", c: "d"}
})
})
o("parses query + hash at start", function() {
var data = parsePathname("?a=1&b=2#c=3&d=4")
o(data).deepEquals({
path: "/",
params: {a: "1", b: "2", c: "3", d: "4"}
})
})
o("parses root", function() {
var data = parsePathname("/")
o(data).deepEquals({
path: "/",
params: {}
})
})
o("parses root + query at start", function() {
var data = parsePathname("/?a=b&c=d")
o(data).deepEquals({
path: "/",
params: {a: "b", c: "d"}
})
})
o("parses root + hash at start", function() {
var data = parsePathname("/#a=b&c=d")
o(data).deepEquals({
path: "/",
params: {a: "b", c: "d"}
})
})
o("parses root + query + hash at start", function() {
var data = parsePathname("/?a=1&b=2#c=3&d=4")
o(data).deepEquals({
path: "/",
params: {a: "1", b: "2", c: "3", d: "4"}
})
})
o("parses route", function() {
var data = parsePathname("/route/foo")
o(data).deepEquals({
path: "/route/foo",
params: {}
})
})
o("parses route + empty query", function() {
var data = parsePathname("/route/foo?")
o(data).deepEquals({
path: "/route/foo",
params: {}
})
})
o("parses route + empty hash", function() {
var data = parsePathname("/route/foo?")
o(data).deepEquals({
path: "/route/foo",
params: {}
})
})
o("parses route + empty query + empty hash", function() {
var data = parsePathname("/route/foo?#")
o(data).deepEquals({
path: "/route/foo",
params: {}
})
})
o("parses route + query", function() {
var data = parsePathname("/route/foo?a=1&b=2")
o(data).deepEquals({
path: "/route/foo",
params: {a: "1", b: "2"}
})
})
o("parses route + hash", function() {
var data = parsePathname("/route/foo?c=3&d=4")
o(data).deepEquals({
path: "/route/foo",
params: {c: "3", d: "4"}
})
})
o("parses route + query + hash", function() {
var data = parsePathname("/route/foo?a=1&b=2#c=3&d=4")
o(data).deepEquals({
path: "/route/foo",
params: {a: "1", b: "2", c: "3", d: "4"}
})
})
o("deduplicates same-named params in query + hash", function() {
var data = parsePathname("/route/foo?a=1&b=2#a=3&c=4")
o(data).deepEquals({
path: "/route/foo",
params: {a: "3", b: "2", c: "4"}
})
})
o("parses route + query + hash with lots of junk slashes", function() {
var data = parsePathname("//route/////foo//?a=1&b=2#c=3&d=4")
o(data).deepEquals({
path: "/route/foo",
params: {a: "1", b: "2", c: "3", d: "4"}
})
})
})

View file

@ -1,10 +1,13 @@
"use strict"
module.exports = function(string) {
// The extra `data` parameter is for if you want to append to an existing
// parameters object.
module.exports = function(string, data) {
if (data == null) data = {}
if (string === "" || string == null) return {}
if (string.charAt(0) === "?") string = string.slice(1)
var entries = string.split("&"), data = {}, counters = {}
var entries = string.split("&"), counters = {}
for (var i = 0; i < entries.length; i++) {
var entry = entries[i].split("=")
var key = decodeURIComponent(entry[0])
@ -22,12 +25,13 @@ module.exports = function(string) {
var isValue = j === levels.length - 1
if (level === "") {
var key = levels.slice(0, j).join()
if (counters[key] == null) counters[key] = 0
if (counters[key] == null) {
counters[key] = Array.isArray(cursor) ? cursor.length : 0
}
level = counters[key]++
}
if (cursor[level] == null) {
cursor[level] = isValue ? value : isNumber ? [] : {}
}
if (isValue) cursor[level] = value
else if (cursor[level] == null) cursor[level] = isNumber ? [] : {}
cursor = cursor[level]
}
}

View file

@ -93,4 +93,20 @@ o.spec("parseQueryString", function() {
var data = parseQueryString("a")
o(data).deepEquals({a: ""})
})
o("prefers later values", function() {
var data = parseQueryString("a=1&b=2&a=3")
o(data).deepEquals({a: "3", b: "2"})
})
o("continues to append to arrays between calls", function() {
var data = {}
parseQueryString("a[]=1&a[]=2", data)
parseQueryString("a[]=3&a[]=4", data)
o(data).deepEquals({a: ["1", "2", "3", "4"]})
})
o("continues to append to objects between calls", function() {
var data = {}
parseQueryString("a[b]=1&a[c]=2", data)
parseQueryString("a[d]=3&a[e]=4", data)
o(data).deepEquals({a: {b: "1", c: "2", d: "3", e: "4"}})
})
})

View file

@ -1,6 +1,6 @@
"use strict"
var buildQueryString = require("../querystring/build")
var buildPathname = require("../pathname/build")
module.exports = function($window, Promise) {
var callbackCount = 0
@ -11,7 +11,7 @@ module.exports = function($window, Promise) {
if (typeof url !== "string") { args = url; url = url.url }
else if (args == null) args = {}
var promise = new Promise(function(resolve, reject) {
factory(url, args, function (data) {
factory(buildPathname(url, args.params), args, function (data) {
if (typeof args.type === "function") {
if (Array.isArray(data)) {
for (var i = 0; i < data.length; i++) {
@ -54,30 +54,11 @@ module.exports = function($window, Promise) {
return false
}
function interpolate(url, data, assemble) {
if (data == null) return url
url = url.replace(/:([^\/]+)/gi, function (m, key) {
return data[key] != null ? data[key] : m
})
if (assemble && data != null) {
var querystring = buildQueryString(data)
if (querystring) url += (url.indexOf("?") < 0 ? "?" : "&") + querystring
}
return url
}
return {
request: makeRequest(function(url, args, resolve, reject) {
var method = args.method != null ? args.method.toUpperCase() : "GET"
var useBody = method !== "GET" && method !== "TRACE" &&
(typeof args.useBody !== "boolean" || args.useBody)
var data = args.data
var assumeJSON = (args.serialize == null || args.serialize === JSON.serialize) && !(data instanceof $window.FormData)
if (useBody) {
if (typeof args.serialize === "function") data = args.serialize(data)
else if (!(data instanceof $window.FormData)) data = JSON.stringify(data)
}
var body = args.body
var assumeJSON = (args.serialize == null || args.serialize === JSON.serialize) && !(body instanceof $window.FormData)
var xhr = new $window.XMLHttpRequest(),
aborted = false,
@ -88,9 +69,9 @@ module.exports = function($window, Promise) {
_abort.call(xhr)
}
xhr.open(method, interpolate(url, args.data, !useBody), typeof args.async !== "boolean" || args.async, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined)
xhr.open(method, url, args.async !== false, typeof args.user === "string" ? args.user : undefined, typeof args.password === "string" ? args.password : undefined)
if (assumeJSON && useBody && !hasHeader(args, /^content-type$/i)) {
if (assumeJSON && !hasHeader(args, /^content-type$/i)) {
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8")
}
if (typeof args.deserialize !== "function" && !hasHeader(args, /^accept$/i)) {
@ -139,23 +120,24 @@ module.exports = function($window, Promise) {
}
}
if (useBody && data != null) xhr.send(data)
else xhr.send()
if (body == null) xhr.send()
else if (typeof args.serialize === "function") xhr.send(args.serialize(body))
else if (body instanceof $window.FormData) xhr.send(body)
else xhr.send(JSON.stringify(body))
}),
jsonp: makeRequest(function(url, args, resolve, reject) {
var callbackName = args.callbackName || "_mithril_" + Math.round(Math.random() * 1e16) + "_" + callbackCount++
var script = $window.document.createElement("script")
$window[callbackName] = function(data) {
delete $window[callbackName]
script.parentNode.removeChild(script)
resolve(data)
delete $window[callbackName]
}
script.onerror = function() {
delete $window[callbackName]
script.parentNode.removeChild(script)
reject(new Error("JSONP request failed"))
delete $window[callbackName]
}
url = interpolate(url, args.data, true)
script.src = url + (url.indexOf("?") < 0 ? "?" : "&") +
encodeURIComponent(args.callbackKey || "callback") + "=" +
encodeURIComponent(callbackName)

View file

@ -47,7 +47,7 @@ o.spec("jsonp", function() {
return {status: 200, responseText: queryData["callback"] + "(" + JSON.stringify(queryData) + ")"}
}
})
jsonp({url: "/item", data: {a: "b", c: "d"}}).then(function(data) {
jsonp({url: "/item", params: {a: "b", c: "d"}}).then(function(data) {
delete data["callback"]
o(data).deepEquals({a: "b", c: "d"})
}).then(done)

View file

@ -79,7 +79,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({a: request.query})}
}
})
xhr({method: "GET", url: "/item", data: {x: "y"}}).then(function(data) {
xhr({method: "GET", url: "/item", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "?x=y"})
}).then(done)
})
@ -89,7 +89,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({a: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item", data: {x: "y"}}).then(function(data) {
xhr({method: "POST", url: "/item", body: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: {x: "y"}})
}).then(done)
})
@ -99,7 +99,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({a: request.query})}
}
})
xhr({method: "GET", url: "/item", data: {x: ":y"}}).then(function(data) {
xhr({method: "GET", url: "/item", params: {x: ":y"}}).then(function(data) {
o(data).deepEquals({a: "?x=%3Ay"})
}).then(done)
})
@ -109,28 +109,88 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({a: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item", data: {x: ":y"}}).then(function(data) {
xhr({method: "POST", url: "/item", body: {x: ":y"}}).then(function(data) {
o(data).deepEquals({a: {x: ":y"}})
}).then(done)
})
o("works w/ parameterized url via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query})}
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "GET", url: "/item/:x", data: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?x=y"})
xhr({method: "GET", url: "/item/:x", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: null})
}).then(done)
})
o("works w/ parameterized url via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: JSON.parse(request.body)})}
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "POST", url: "/item/:x", data: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {x: "y"}})
xhr({method: "POST", url: "/item/:x", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: null})
}).then(done)
})
o("works w/ parameterized url + body via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + body via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + query via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y", q: "term"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: null})
}).then(done)
})
o("works w/ parameterized url + query via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y", q: "term"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: null})
}).then(done)
})
o("works w/ parameterized url + query + body via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y", q: "term"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + query + body via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y", q: "term"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: {a: "b"}})
}).then(done)
})
o("works w/ array", function(done) {
@ -139,7 +199,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({a: request.url, b: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/items", data: [{x: "y"}]}).then(function(data) {
xhr({method: "POST", url: "/items", body: [{x: "y"}]}).then(function(data) {
o(data).deepEquals({a: "/items", b: [{x: "y"}]})
}).then(done)
})
@ -201,7 +261,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({body: request.query})}
}
})
xhr({method: "GET", url: "/item", serialize: serialize, data: {id: 1}}).then(function(data) {
xhr({method: "GET", url: "/item", serialize: serialize, params: {id: 1}}).then(function(data) {
o(data.body).equals("?id=1")
}).then(done)
})
@ -215,7 +275,7 @@ o.spec("xhr", function() {
return {status: 200, responseText: JSON.stringify({body: request.body})}
}
})
xhr({method: "POST", url: "/item", serialize: serialize, data: {id: 1}}).then(function(data) {
xhr({method: "POST", url: "/item", serialize: serialize, body: {id: 1}}).then(function(data) {
o(data.body).equals("id=1")
}).then(done)
})

View file

@ -1,7 +1,9 @@
"use strict"
var buildQueryString = require("../querystring/build")
var parseQueryString = require("../querystring/parse")
var buildPathname = require("../pathname/build")
var parsePathname = require("../pathname/parse")
var compileTemplate = require("../pathname/compileTemplate")
var assign = require("../pathname/assign")
module.exports = function($window) {
var supportsPushState = typeof $window.history.pushState === "function"
@ -14,58 +16,15 @@ module.exports = function($window) {
}
var asyncId
function debounceAsync(callback) {
return function() {
if (asyncId != null) return
asyncId = callAsync(function() {
asyncId = null
callback()
})
}
}
function parsePath(path, queryData, hashData) {
var queryIndex = path.indexOf("?")
var hashIndex = path.indexOf("#")
var pathEnd = queryIndex > -1 ? queryIndex : hashIndex > -1 ? hashIndex : path.length
if (queryIndex > -1) {
var queryEnd = hashIndex > -1 ? hashIndex : path.length
var queryParams = parseQueryString(path.slice(queryIndex + 1, queryEnd))
for (var key in queryParams) queryData[key] = queryParams[key]
}
if (hashIndex > -1) {
var hashParams = parseQueryString(path.slice(hashIndex + 1))
for (var key in hashParams) hashData[key] = hashParams[key]
}
return path.slice(0, pathEnd)
}
var router = {prefix: "#!"}
router.getPath = function() {
var type = router.prefix.charAt(0)
switch (type) {
case "#": return normalize("hash").slice(router.prefix.length)
case "?": return normalize("search").slice(router.prefix.length) + normalize("hash")
default: return normalize("pathname").slice(router.prefix.length) + normalize("search") + normalize("hash")
}
if (router.prefix.charAt(0) === "#") return normalize("hash").slice(router.prefix.length)
if (router.prefix.charAt(0) === "?") return normalize("search").slice(router.prefix.length) + normalize("hash")
return normalize("pathname").slice(router.prefix.length) + normalize("search") + normalize("hash")
}
router.setPath = function(path, data, options) {
var queryData = {}, hashData = {}
path = parsePath(path, queryData, hashData)
if (data != null) {
for (var key in data) queryData[key] = data[key]
path = path.replace(/:([^\/]+)/g, function(match, token) {
delete queryData[token]
return data[token]
})
}
var query = buildQueryString(queryData)
if (query) path += "?" + query
var hash = buildQueryString(hashData)
if (hash) path += "#" + hash
path = buildPathname(path, data)
if (supportsPushState) {
var state = options ? options.state : null
var title = options ? options.title : null
@ -75,36 +34,53 @@ module.exports = function($window) {
}
else $window.location.href = router.prefix + path
}
router.defineRoutes = function(routes, resolve, reject) {
router.defineRoutes = function(routes, resolve, reject, defaultRoute) {
var compiled = Object.keys(routes).map(function(route) {
if (route.charAt(0) !== "/") throw new SyntaxError("Routes must start with a `/`")
if ((/:([^\/\.-]+)(\.{3})?:/).test(route)) {
throw new SyntaxError("Route parameter names must be separated with either `/`, `.`, or `-`")
}
return {
route: route,
component: routes[route],
check: compileTemplate(route),
}
})
if (defaultRoute != null) {
var defaultData = parsePathname(defaultRoute)
if (!compiled.some(function (i) { return i.check(defaultData) })) {
throw new ReferenceError("Default route doesn't match any known routes")
}
}
function resolveRoute() {
var path = router.getPath()
var params = {}
var pathname = parsePath(path, params, params)
var data = parsePathname(path)
var state = $window.history.state
if (state != null) {
for (var k in state) params[k] = state[k]
}
for (var route in routes) {
var matcher = new RegExp("^" + route.replace(/:[^\/]+?\.{3}/g, "(.*?)").replace(/:[^\/]+/g, "([^\\/]+)") + "\/?$")
assign(data.params, $window.history.state)
if (matcher.test(pathname)) {
pathname.replace(matcher, function() {
var keys = route.match(/:[^\/]+/g) || []
var values = [].slice.call(arguments, 1, -2)
for (var i = 0; i < keys.length; i++) {
params[keys[i].replace(/:|\./g, "")] = decodeURIComponent(values[i])
}
resolve(routes[route], params, path, route)
})
for (var i = 0; i < compiled.length; i++) {
if (compiled[i].check(data)) {
resolve(compiled[i].component, data.params, path, compiled[i].route)
return
}
}
reject(path, params)
reject(path, data.params)
}
if (supportsPushState) $window.onpopstate = debounceAsync(resolveRoute)
if (supportsPushState) {
$window.onpopstate = function() {
if (asyncId) return
asyncId = callAsync(function() {
asyncId = null
resolveRoute()
})
}
}
else if (router.prefix.charAt(0) === "#") $window.onhashchange = resolveRoute
resolveRoute()
}

View file

@ -22,14 +22,14 @@ o.spec("Router.defineRoutes", function() {
o("calls onRouteChange on init", function(done) {
$window.location.href = prefix + "/a"
router.defineRoutes({"/a": {data: 1}}, onRouteChange, onFail)
callAsync(function() {
o(onRouteChange.callCount).equals(1)
done()
})
})
o("resolves to route", function(done) {
$window.location.href = prefix + "/test"
router.defineRoutes({"/test": {data: 1}}, onRouteChange, onFail)
@ -38,7 +38,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {}, "/test", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
@ -51,7 +51,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 2}, {"ö": "ö"}, "/ö?ö=ö#ö=ö", "/ö"])
o(onFail.callCount).equals(0)
done()
})
})
@ -64,7 +64,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 2}, {"ö": "ö"}, "/ö?ö=ö#ö=ö", "/ö"])
o(onFail.callCount).equals(0)
done()
})
})
@ -81,7 +81,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {}, "/test", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
@ -94,7 +94,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "x"}, "/test/x", "/test/:a"])
o(onFail.callCount).equals(0)
done()
})
})
@ -107,7 +107,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "x", b: "y"}, "/test/x/y", "/test/:a/:b"])
o(onFail.callCount).equals(0)
done()
})
})
@ -120,7 +120,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "x/y"}, "/test/x/y", "/test/:a..."])
o(onFail.callCount).equals(0)
done()
})
})
@ -133,7 +133,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "b", c: "d"}, "/test?a=b&c=d", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
@ -146,7 +146,7 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "b", c: "d"}, "/test#a=b&c=d", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
@ -159,7 +159,20 @@ o.spec("Router.defineRoutes", function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "b", c: "d"}, "/test?a=b#c=d", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
o("handles route with search and hash + duplicate params", function(done) {
$window.location.href = prefix + "/test?a=b#a=d"
router.defineRoutes({"/test": {data: 1}}, onRouteChange, onFail)
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {a: "d"}, "/test?a=b#a=d", "/test"])
o(onFail.callCount).equals(0)
done()
})
})
@ -171,7 +184,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onFail.callCount).equals(1)
o(onFail.args).deepEquals(["/test", {}])
done()
})
})
@ -183,7 +196,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onFail.callCount).equals(1)
o(onFail.args).deepEquals(["/test?a=b#c=d", {a: "b", c: "d"}])
done()
})
})
@ -195,7 +208,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {}, "/z/y/x", "/z/y/x"])
done()
})
})
@ -207,7 +220,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 2}, {a: "z/y/x"}, "/z/y/x", "/:a..."])
done()
})
})
@ -223,7 +236,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {}, "/z/y/x", "/z/y/x"])
done()
})
})
@ -239,7 +252,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 2}, {a: "z/y/x"}, "/z/y/x", "/:a..."])
done()
})
})
@ -254,7 +267,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 1}, {}, "/z/y/x", "/z/y/x"])
done()
})
})
@ -269,7 +282,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
o(onRouteChange.args).deepEquals([{data: 2}, {a: "z/y/x"}, "/z/y/x", "/:a..."])
done()
})
})
@ -280,7 +293,7 @@ o.spec("Router.defineRoutes", function() {
callAsync(function() {
o(onRouteChange.callCount).equals(1)
done()
})
})

View file

@ -55,7 +55,7 @@ o.spec("Router.setPath", function() {
router.setPath("/other/x/y/z?c=d#e=f")
o(router.getPath()).equals("/other/x/y/z?c=d#e=f")
done()
})
})
@ -67,7 +67,7 @@ o.spec("Router.setPath", function() {
router.setPath("/%C3%B6?%C3%B6=%C3%B6#%C3%B6=%C3%B6")
o(router.getPath()).equals("/ö?ö=ö#ö=ö")
done()
})
})
@ -79,7 +79,7 @@ o.spec("Router.setPath", function() {
router.setPath("/ö?ö=ö#ö=ö")
o(router.getPath()).equals("/ö?ö=ö#ö=ö")
done()
})
})
@ -96,7 +96,7 @@ o.spec("Router.setPath", function() {
router.setPath("/other/x/y/z?c=d#e=f")
o(router.getPath()).equals("/other/x/y/z?c=d#e=f")
done()
})
})
@ -109,7 +109,7 @@ o.spec("Router.setPath", function() {
$window.onpopstate()
o(router.getPath()).equals("/other/x/y/z?c=d#e=f")
done()
})
})
@ -120,8 +120,8 @@ o.spec("Router.setPath", function() {
callAsync(function() {
router.setPath("/other/:a/:b", {a: "x", b: "y/z", c: "d", e: "f"})
o(router.getPath()).equals("/other/x/y/z?c=d&e=f")
o(router.getPath()).equals("/other/x/y%2Fz?c=d&e=f")
done()
})
})
@ -134,7 +134,7 @@ o.spec("Router.setPath", function() {
$window.history.back()
o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + "/")
done()
})
})
@ -149,7 +149,7 @@ o.spec("Router.setPath", function() {
var slash = prefix[0] === "/" ? "" : "/"
o($window.location.href).equals(env.protocol + "//" + (env.hostname === "/" ? "" : env.hostname) + slash + (prefix ? prefix + "/" : "") + "test")
done()
})
})
@ -161,7 +161,7 @@ o.spec("Router.setPath", function() {
router.setPath("/other", null, {state: {a: 1}})
o($window.history.state).deepEquals({a: 1})
done()
})
})