Built motion from commit 503e72f.|0.0.143
[motion.git] / public / bower_components / angular-resource / angular-resource.js
1 /**
2  * @license AngularJS v1.4.10
3  * (c) 2010-2015 Google, Inc. http://angularjs.org
4  * License: MIT
5  */
6 (function(window, angular, undefined) {'use strict';
7
8 var $resourceMinErr = angular.$$minErr('$resource');
9
10 // Helper functions and regex to lookup a dotted path on an object
11 // stopping at undefined/null.  The path must be composed of ASCII
12 // identifiers (just like $parse)
13 var MEMBER_NAME_REGEX = /^(\.[a-zA-Z_$@][0-9a-zA-Z_$@]*)+$/;
14
15 function isValidDottedPath(path) {
16   return (path != null && path !== '' && path !== 'hasOwnProperty' &&
17       MEMBER_NAME_REGEX.test('.' + path));
18 }
19
20 function lookupDottedPath(obj, path) {
21   if (!isValidDottedPath(path)) {
22     throw $resourceMinErr('badmember', 'Dotted member path "@{0}" is invalid.', path);
23   }
24   var keys = path.split('.');
25   for (var i = 0, ii = keys.length; i < ii && angular.isDefined(obj); i++) {
26     var key = keys[i];
27     obj = (obj !== null) ? obj[key] : undefined;
28   }
29   return obj;
30 }
31
32 /**
33  * Create a shallow copy of an object and clear other fields from the destination
34  */
35 function shallowClearAndCopy(src, dst) {
36   dst = dst || {};
37
38   angular.forEach(dst, function(value, key) {
39     delete dst[key];
40   });
41
42   for (var key in src) {
43     if (src.hasOwnProperty(key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
44       dst[key] = src[key];
45     }
46   }
47
48   return dst;
49 }
50
51 /**
52  * @ngdoc module
53  * @name ngResource
54  * @description
55  *
56  * # ngResource
57  *
58  * The `ngResource` module provides interaction support with RESTful services
59  * via the $resource service.
60  *
61  *
62  * <div doc-module-components="ngResource"></div>
63  *
64  * See {@link ngResource.$resource `$resource`} for usage.
65  */
66
67 /**
68  * @ngdoc service
69  * @name $resource
70  * @requires $http
71  *
72  * @description
73  * A factory which creates a resource object that lets you interact with
74  * [RESTful](http://en.wikipedia.org/wiki/Representational_State_Transfer) server-side data sources.
75  *
76  * The returned resource object has action methods which provide high-level behaviors without
77  * the need to interact with the low level {@link ng.$http $http} service.
78  *
79  * Requires the {@link ngResource `ngResource`} module to be installed.
80  *
81  * By default, trailing slashes will be stripped from the calculated URLs,
82  * which can pose problems with server backends that do not expect that
83  * behavior.  This can be disabled by configuring the `$resourceProvider` like
84  * this:
85  *
86  * ```js
87      app.config(['$resourceProvider', function($resourceProvider) {
88        // Don't strip trailing slashes from calculated URLs
89        $resourceProvider.defaults.stripTrailingSlashes = false;
90      }]);
91  * ```
92  *
93  * @param {string} url A parameterized URL template with parameters prefixed by `:` as in
94  *   `/user/:username`. If you are using a URL with a port number (e.g.
95  *   `http://example.com:8080/api`), it will be respected.
96  *
97  *   If you are using a url with a suffix, just add the suffix, like this:
98  *   `$resource('http://example.com/resource.json')` or `$resource('http://example.com/:id.json')`
99  *   or even `$resource('http://example.com/resource/:resource_id.:format')`
100  *   If the parameter before the suffix is empty, :resource_id in this case, then the `/.` will be
101  *   collapsed down to a single `.`.  If you need this sequence to appear and not collapse then you
102  *   can escape it with `/\.`.
103  *
104  * @param {Object=} paramDefaults Default values for `url` parameters. These can be overridden in
105  *   `actions` methods. If a parameter value is a function, it will be executed every time
106  *   when a param value needs to be obtained for a request (unless the param was overridden).
107  *
108  *   Each key value in the parameter object is first bound to url template if present and then any
109  *   excess keys are appended to the url search query after the `?`.
110  *
111  *   Given a template `/path/:verb` and parameter `{verb:'greet', salutation:'Hello'}` results in
112  *   URL `/path/greet?salutation=Hello`.
113  *
114  *   If the parameter value is prefixed with `@` then the value for that parameter will be extracted
115  *   from the corresponding property on the `data` object (provided when calling an action method).  For
116  *   example, if the `defaultParam` object is `{someParam: '@someProp'}` then the value of `someParam`
117  *   will be `data.someProp`.
118  *
119  * @param {Object.<Object>=} actions Hash with declaration of custom actions that should extend
120  *   the default set of resource actions. The declaration should be created in the format of {@link
121  *   ng.$http#usage $http.config}:
122  *
123  *       {action1: {method:?, params:?, isArray:?, headers:?, ...},
124  *        action2: {method:?, params:?, isArray:?, headers:?, ...},
125  *        ...}
126  *
127  *   Where:
128  *
129  *   - **`action`** – {string} – The name of action. This name becomes the name of the method on
130  *     your resource object.
131  *   - **`method`** – {string} – Case insensitive HTTP method (e.g. `GET`, `POST`, `PUT`,
132  *     `DELETE`, `JSONP`, etc).
133  *   - **`params`** – {Object=} – Optional set of pre-bound parameters for this action. If any of
134  *     the parameter value is a function, it will be executed every time when a param value needs to
135  *     be obtained for a request (unless the param was overridden).
136  *   - **`url`** – {string} – action specific `url` override. The url templating is supported just
137  *     like for the resource-level urls.
138  *   - **`isArray`** – {boolean=} – If true then the returned object for this action is an array,
139  *     see `returns` section.
140  *   - **`transformRequest`** –
141  *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
142  *     transform function or an array of such functions. The transform function takes the http
143  *     request body and headers and returns its transformed (typically serialized) version.
144  *     By default, transformRequest will contain one function that checks if the request data is
145  *     an object and serializes to using `angular.toJson`. To prevent this behavior, set
146  *     `transformRequest` to an empty array: `transformRequest: []`
147  *   - **`transformResponse`** –
148  *     `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
149  *     transform function or an array of such functions. The transform function takes the http
150  *     response body and headers and returns its transformed (typically deserialized) version.
151  *     By default, transformResponse will contain one function that checks if the response looks like
152  *     a JSON string and deserializes it using `angular.fromJson`. To prevent this behavior, set
153  *     `transformResponse` to an empty array: `transformResponse: []`
154  *   - **`cache`** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
155  *     GET request, otherwise if a cache instance built with
156  *     {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
157  *     caching.
158  *   - **`timeout`** – `{number}` – timeout in milliseconds.<br />
159  *     **Note:** In contrast to {@link ng.$http#usage $http.config}, {@link ng.$q promises} are
160  *     **not** supported in $resource, because the same value would be used for multiple requests.
161  *     If you need support for cancellable $resource actions, you should upgrade to version 1.5 or
162  *     higher.
163  *   - **`withCredentials`** - `{boolean}` - whether to set the `withCredentials` flag on the
164  *     XHR object. See
165  *     [requests with credentials](https://developer.mozilla.org/en/http_access_control#section_5)
166  *     for more information.
167  *   - **`responseType`** - `{string}` - see
168  *     [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
169  *   - **`interceptor`** - `{Object=}` - The interceptor object has two optional methods -
170  *     `response` and `responseError`. Both `response` and `responseError` interceptors get called
171  *     with `http response` object. See {@link ng.$http $http interceptors}.
172  *
173  * @param {Object} options Hash with custom settings that should extend the
174  *   default `$resourceProvider` behavior.  The only supported option is
175  *
176  *   Where:
177  *
178  *   - **`stripTrailingSlashes`** – {boolean} – If true then the trailing
179  *   slashes from any calculated URL will be stripped. (Defaults to true.)
180  *
181  * @returns {Object} A resource "class" object with methods for the default set of resource actions
182  *   optionally extended with custom `actions`. The default set contains these actions:
183  *   ```js
184  *   { 'get':    {method:'GET'},
185  *     'save':   {method:'POST'},
186  *     'query':  {method:'GET', isArray:true},
187  *     'remove': {method:'DELETE'},
188  *     'delete': {method:'DELETE'} };
189  *   ```
190  *
191  *   Calling these methods invoke an {@link ng.$http} with the specified http method,
192  *   destination and parameters. When the data is returned from the server then the object is an
193  *   instance of the resource class. The actions `save`, `remove` and `delete` are available on it
194  *   as  methods with the `$` prefix. This allows you to easily perform CRUD operations (create,
195  *   read, update, delete) on server-side data like this:
196  *   ```js
197  *   var User = $resource('/user/:userId', {userId:'@id'});
198  *   var user = User.get({userId:123}, function() {
199  *     user.abc = true;
200  *     user.$save();
201  *   });
202  *   ```
203  *
204  *   It is important to realize that invoking a $resource object method immediately returns an
205  *   empty reference (object or array depending on `isArray`). Once the data is returned from the
206  *   server the existing reference is populated with the actual data. This is a useful trick since
207  *   usually the resource is assigned to a model which is then rendered by the view. Having an empty
208  *   object results in no rendering, once the data arrives from the server then the object is
209  *   populated with the data and the view automatically re-renders itself showing the new data. This
210  *   means that in most cases one never has to write a callback function for the action methods.
211  *
212  *   The action methods on the class object or instance object can be invoked with the following
213  *   parameters:
214  *
215  *   - HTTP GET "class" actions: `Resource.action([parameters], [success], [error])`
216  *   - non-GET "class" actions: `Resource.action([parameters], postData, [success], [error])`
217  *   - non-GET instance actions:  `instance.$action([parameters], [success], [error])`
218  *
219  *
220  *   Success callback is called with (value, responseHeaders) arguments, where the value is
221  *   the populated resource instance or collection object. The error callback is called
222  *   with (httpResponse) argument.
223  *
224  *   Class actions return empty instance (with additional properties below).
225  *   Instance actions return promise of the action.
226  *
227  *   The Resource instances and collection have these additional properties:
228  *
229  *   - `$promise`: the {@link ng.$q promise} of the original server interaction that created this
230  *     instance or collection.
231  *
232  *     On success, the promise is resolved with the same resource instance or collection object,
233  *     updated with data from server. This makes it easy to use in
234  *     {@link ngRoute.$routeProvider resolve section of $routeProvider.when()} to defer view
235  *     rendering until the resource(s) are loaded.
236  *
237  *     On failure, the promise is rejected with the {@link ng.$http http response} object, without
238  *     the `resource` property.
239  *
240  *     If an interceptor object was provided, the promise will instead be resolved with the value
241  *     returned by the interceptor.
242  *
243  *   - `$resolved`: `true` after first server interaction is completed (either with success or
244  *      rejection), `false` before that. Knowing if the Resource has been resolved is useful in
245  *      data-binding.
246  *
247  * @example
248  *
249  * # Credit card resource
250  *
251  * ```js
252      // Define CreditCard class
253      var CreditCard = $resource('/user/:userId/card/:cardId',
254       {userId:123, cardId:'@id'}, {
255        charge: {method:'POST', params:{charge:true}}
256       });
257
258      // We can retrieve a collection from the server
259      var cards = CreditCard.query(function() {
260        // GET: /user/123/card
261        // server returns: [ {id:456, number:'1234', name:'Smith'} ];
262
263        var card = cards[0];
264        // each item is an instance of CreditCard
265        expect(card instanceof CreditCard).toEqual(true);
266        card.name = "J. Smith";
267        // non GET methods are mapped onto the instances
268        card.$save();
269        // POST: /user/123/card/456 {id:456, number:'1234', name:'J. Smith'}
270        // server returns: {id:456, number:'1234', name: 'J. Smith'};
271
272        // our custom method is mapped as well.
273        card.$charge({amount:9.99});
274        // POST: /user/123/card/456?amount=9.99&charge=true {id:456, number:'1234', name:'J. Smith'}
275      });
276
277      // we can create an instance as well
278      var newCard = new CreditCard({number:'0123'});
279      newCard.name = "Mike Smith";
280      newCard.$save();
281      // POST: /user/123/card {number:'0123', name:'Mike Smith'}
282      // server returns: {id:789, number:'0123', name: 'Mike Smith'};
283      expect(newCard.id).toEqual(789);
284  * ```
285  *
286  * The object returned from this function execution is a resource "class" which has "static" method
287  * for each action in the definition.
288  *
289  * Calling these methods invoke `$http` on the `url` template with the given `method`, `params` and
290  * `headers`.
291  * When the data is returned from the server then the object is an instance of the resource type and
292  * all of the non-GET methods are available with `$` prefix. This allows you to easily support CRUD
293  * operations (create, read, update, delete) on server-side data.
294
295    ```js
296      var User = $resource('/user/:userId', {userId:'@id'});
297      User.get({userId:123}, function(user) {
298        user.abc = true;
299        user.$save();
300      });
301    ```
302  *
303  * It's worth noting that the success callback for `get`, `query` and other methods gets passed
304  * in the response that came from the server as well as $http header getter function, so one
305  * could rewrite the above example and get access to http headers as:
306  *
307    ```js
308      var User = $resource('/user/:userId', {userId:'@id'});
309      User.get({userId:123}, function(u, getResponseHeaders){
310        u.abc = true;
311        u.$save(function(u, putResponseHeaders) {
312          //u => saved user object
313          //putResponseHeaders => $http header getter
314        });
315      });
316    ```
317  *
318  * You can also access the raw `$http` promise via the `$promise` property on the object returned
319  *
320    ```
321      var User = $resource('/user/:userId', {userId:'@id'});
322      User.get({userId:123})
323          .$promise.then(function(user) {
324            $scope.user = user;
325          });
326    ```
327
328  * # Creating a custom 'PUT' request
329  * In this example we create a custom method on our resource to make a PUT request
330  * ```js
331  *    var app = angular.module('app', ['ngResource', 'ngRoute']);
332  *
333  *    // Some APIs expect a PUT request in the format URL/object/ID
334  *    // Here we are creating an 'update' method
335  *    app.factory('Notes', ['$resource', function($resource) {
336  *    return $resource('/notes/:id', null,
337  *        {
338  *            'update': { method:'PUT' }
339  *        });
340  *    }]);
341  *
342  *    // In our controller we get the ID from the URL using ngRoute and $routeParams
343  *    // We pass in $routeParams and our Notes factory along with $scope
344  *    app.controller('NotesCtrl', ['$scope', '$routeParams', 'Notes',
345                                       function($scope, $routeParams, Notes) {
346  *    // First get a note object from the factory
347  *    var note = Notes.get({ id:$routeParams.id });
348  *    $id = note.id;
349  *
350  *    // Now call update passing in the ID first then the object you are updating
351  *    Notes.update({ id:$id }, note);
352  *
353  *    // This will PUT /notes/ID with the note object in the request payload
354  *    }]);
355  * ```
356  */
357 angular.module('ngResource', ['ng']).
358   provider('$resource', function() {
359     var PROTOCOL_AND_DOMAIN_REGEX = /^https?:\/\/[^\/]*/;
360     var provider = this;
361
362     this.defaults = {
363       // Strip slashes by default
364       stripTrailingSlashes: true,
365
366       // Default actions configuration
367       actions: {
368         'get': {method: 'GET'},
369         'save': {method: 'POST'},
370         'query': {method: 'GET', isArray: true},
371         'remove': {method: 'DELETE'},
372         'delete': {method: 'DELETE'}
373       }
374     };
375
376     this.$get = ['$http', '$log', '$q', function($http, $log, $q) {
377
378       var noop = angular.noop,
379         forEach = angular.forEach,
380         extend = angular.extend,
381         copy = angular.copy,
382         isFunction = angular.isFunction;
383
384       /**
385        * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
386        * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set
387        * (pchar) allowed in path segments:
388        *    segment       = *pchar
389        *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
390        *    pct-encoded   = "%" HEXDIG HEXDIG
391        *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
392        *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
393        *                     / "*" / "+" / "," / ";" / "="
394        */
395       function encodeUriSegment(val) {
396         return encodeUriQuery(val, true).
397           replace(/%26/gi, '&').
398           replace(/%3D/gi, '=').
399           replace(/%2B/gi, '+');
400       }
401
402
403       /**
404        * This method is intended for encoding *key* or *value* parts of query component. We need a
405        * custom method because encodeURIComponent is too aggressive and encodes stuff that doesn't
406        * have to be encoded per http://tools.ietf.org/html/rfc3986:
407        *    query       = *( pchar / "/" / "?" )
408        *    pchar         = unreserved / pct-encoded / sub-delims / ":" / "@"
409        *    unreserved    = ALPHA / DIGIT / "-" / "." / "_" / "~"
410        *    pct-encoded   = "%" HEXDIG HEXDIG
411        *    sub-delims    = "!" / "$" / "&" / "'" / "(" / ")"
412        *                     / "*" / "+" / "," / ";" / "="
413        */
414       function encodeUriQuery(val, pctEncodeSpaces) {
415         return encodeURIComponent(val).
416           replace(/%40/gi, '@').
417           replace(/%3A/gi, ':').
418           replace(/%24/g, '$').
419           replace(/%2C/gi, ',').
420           replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
421       }
422
423       function Route(template, defaults) {
424         this.template = template;
425         this.defaults = extend({}, provider.defaults, defaults);
426         this.urlParams = {};
427       }
428
429       Route.prototype = {
430         setUrlParams: function(config, params, actionUrl) {
431           var self = this,
432             url = actionUrl || self.template,
433             val,
434             encodedVal,
435             protocolAndDomain = '';
436
437           var urlParams = self.urlParams = {};
438           forEach(url.split(/\W/), function(param) {
439             if (param === 'hasOwnProperty') {
440               throw $resourceMinErr('badname', "hasOwnProperty is not a valid parameter name.");
441             }
442             if (!(new RegExp("^\\d+$").test(param)) && param &&
443               (new RegExp("(^|[^\\\\]):" + param + "(\\W|$)").test(url))) {
444               urlParams[param] = true;
445             }
446           });
447           url = url.replace(/\\:/g, ':');
448           url = url.replace(PROTOCOL_AND_DOMAIN_REGEX, function(match) {
449             protocolAndDomain = match;
450             return '';
451           });
452
453           params = params || {};
454           forEach(self.urlParams, function(_, urlParam) {
455             val = params.hasOwnProperty(urlParam) ? params[urlParam] : self.defaults[urlParam];
456             if (angular.isDefined(val) && val !== null) {
457               encodedVal = encodeUriSegment(val);
458               url = url.replace(new RegExp(":" + urlParam + "(\\W|$)", "g"), function(match, p1) {
459                 return encodedVal + p1;
460               });
461             } else {
462               url = url.replace(new RegExp("(\/?):" + urlParam + "(\\W|$)", "g"), function(match,
463                   leadingSlashes, tail) {
464                 if (tail.charAt(0) == '/') {
465                   return tail;
466                 } else {
467                   return leadingSlashes + tail;
468                 }
469               });
470             }
471           });
472
473           // strip trailing slashes and set the url (unless this behavior is specifically disabled)
474           if (self.defaults.stripTrailingSlashes) {
475             url = url.replace(/\/+$/, '') || '/';
476           }
477
478           // then replace collapse `/.` if found in the last URL path segment before the query
479           // E.g. `http://url.com/id./format?q=x` becomes `http://url.com/id.format?q=x`
480           url = url.replace(/\/\.(?=\w+($|\?))/, '.');
481           // replace escaped `/\.` with `/.`
482           config.url = protocolAndDomain + url.replace(/\/\\\./, '/.');
483
484
485           // set params - delegate param encoding to $http
486           forEach(params, function(value, key) {
487             if (!self.urlParams[key]) {
488               config.params = config.params || {};
489               config.params[key] = value;
490             }
491           });
492         }
493       };
494
495
496       function resourceFactory(url, paramDefaults, actions, options) {
497         var route = new Route(url, options);
498
499         actions = extend({}, provider.defaults.actions, actions);
500
501         function extractParams(data, actionParams) {
502           var ids = {};
503           actionParams = extend({}, paramDefaults, actionParams);
504           forEach(actionParams, function(value, key) {
505             if (isFunction(value)) { value = value(); }
506             ids[key] = value && value.charAt && value.charAt(0) == '@' ?
507               lookupDottedPath(data, value.substr(1)) : value;
508           });
509           return ids;
510         }
511
512         function defaultResponseInterceptor(response) {
513           return response.resource;
514         }
515
516         function Resource(value) {
517           shallowClearAndCopy(value || {}, this);
518         }
519
520         Resource.prototype.toJSON = function() {
521           var data = extend({}, this);
522           delete data.$promise;
523           delete data.$resolved;
524           return data;
525         };
526
527         forEach(actions, function(action, name) {
528           var hasBody = /^(POST|PUT|PATCH)$/i.test(action.method);
529
530           Resource[name] = function(a1, a2, a3, a4) {
531             var params = {}, data, success, error;
532
533             /* jshint -W086 */ /* (purposefully fall through case statements) */
534             switch (arguments.length) {
535               case 4:
536                 error = a4;
537                 success = a3;
538               //fallthrough
539               case 3:
540               case 2:
541                 if (isFunction(a2)) {
542                   if (isFunction(a1)) {
543                     success = a1;
544                     error = a2;
545                     break;
546                   }
547
548                   success = a2;
549                   error = a3;
550                   //fallthrough
551                 } else {
552                   params = a1;
553                   data = a2;
554                   success = a3;
555                   break;
556                 }
557               case 1:
558                 if (isFunction(a1)) success = a1;
559                 else if (hasBody) data = a1;
560                 else params = a1;
561                 break;
562               case 0: break;
563               default:
564                 throw $resourceMinErr('badargs',
565                   "Expected up to 4 arguments [params, data, success, error], got {0} arguments",
566                   arguments.length);
567             }
568             /* jshint +W086 */ /* (purposefully fall through case statements) */
569
570             var isInstanceCall = this instanceof Resource;
571             var value = isInstanceCall ? data : (action.isArray ? [] : new Resource(data));
572             var httpConfig = {};
573             var responseInterceptor = action.interceptor && action.interceptor.response ||
574               defaultResponseInterceptor;
575             var responseErrorInterceptor = action.interceptor && action.interceptor.responseError ||
576               undefined;
577
578             forEach(action, function(value, key) {
579               switch (key) {
580                 default:
581                   httpConfig[key] = copy(value);
582                   break;
583                 case 'params':
584                 case 'isArray':
585                 case 'interceptor':
586                   break;
587                 case 'timeout':
588                   if (value && !angular.isNumber(value)) {
589                     $log.debug('ngResource:\n' +
590                         '  Only numeric values are allowed as `timeout`.\n' +
591                         '  Promises are not supported in $resource, because the same value would ' +
592                         'be used for multiple requests.\n' +
593                         '  If you need support for cancellable $resource actions, you should ' +
594                         'upgrade to version 1.5 or higher.');
595                   }
596                   break;
597               }
598             });
599
600             if (hasBody) httpConfig.data = data;
601             route.setUrlParams(httpConfig,
602               extend({}, extractParams(data, action.params || {}), params),
603               action.url);
604
605             var promise = $http(httpConfig).then(function(response) {
606               var data = response.data,
607                 promise = value.$promise;
608
609               if (data) {
610                 // Need to convert action.isArray to boolean in case it is undefined
611                 // jshint -W018
612                 if (angular.isArray(data) !== (!!action.isArray)) {
613                   throw $resourceMinErr('badcfg',
614                       'Error in resource configuration for action `{0}`. Expected response to ' +
615                       'contain an {1} but got an {2} (Request: {3} {4})', name, action.isArray ? 'array' : 'object',
616                     angular.isArray(data) ? 'array' : 'object', httpConfig.method, httpConfig.url);
617                 }
618                 // jshint +W018
619                 if (action.isArray) {
620                   value.length = 0;
621                   forEach(data, function(item) {
622                     if (typeof item === "object") {
623                       value.push(new Resource(item));
624                     } else {
625                       // Valid JSON values may be string literals, and these should not be converted
626                       // into objects. These items will not have access to the Resource prototype
627                       // methods, but unfortunately there
628                       value.push(item);
629                     }
630                   });
631                 } else {
632                   shallowClearAndCopy(data, value);
633                   value.$promise = promise;
634                 }
635               }
636
637               value.$resolved = true;
638
639               response.resource = value;
640
641               return response;
642             }, function(response) {
643               value.$resolved = true;
644
645               (error || noop)(response);
646
647               return $q.reject(response);
648             });
649
650             promise = promise.then(
651               function(response) {
652                 var value = responseInterceptor(response);
653                 (success || noop)(value, response.headers);
654                 return value;
655               },
656               responseErrorInterceptor);
657
658             if (!isInstanceCall) {
659               // we are creating instance / collection
660               // - set the initial promise
661               // - return the instance / collection
662               value.$promise = promise;
663               value.$resolved = false;
664
665               return value;
666             }
667
668             // instance call
669             return promise;
670           };
671
672
673           Resource.prototype['$' + name] = function(params, success, error) {
674             if (isFunction(params)) {
675               error = success; success = params; params = {};
676             }
677             var result = Resource[name].call(this, params, this, success, error);
678             return result.$promise || result;
679           };
680         });
681
682         Resource.bind = function(additionalParamDefaults) {
683           return resourceFactory(url, extend({}, paramDefaults, additionalParamDefaults), actions);
684         };
685
686         return Resource;
687       }
688
689       return resourceFactory;
690     }];
691   });
692
693
694 })(window, window.angular);