PageRenderTime 30ms CodeModel.GetById 32ms RepoModel.GetById 0ms app.codeStats 1ms

/wordpress-dev/wp-includes/js/wp-api.js

https://github.com/scottbale/kirkwoodcoc
JavaScript | 1516 lines | 796 code | 265 blank | 455 comment | 172 complexity | 47fa0460e792c6f65c4321c66a02ed42 MD5 | raw file
  1. (function( window, undefined ) {
  2. 'use strict';
  3. /**
  4. * Initialise the WP_API.
  5. */
  6. function WP_API() {
  7. /** @namespace wp.api.models */
  8. this.models = {};
  9. /** @namespace wp.api.collections */
  10. this.collections = {};
  11. /** @namespace wp.api.views */
  12. this.views = {};
  13. }
  14. /** @namespace wp */
  15. window.wp = window.wp || {};
  16. /** @namespace wp.api */
  17. wp.api = wp.api || new WP_API();
  18. wp.api.versionString = wp.api.versionString || 'wp/v2/';
  19. // Alias _includes to _.contains, ensuring it is available if lodash is used.
  20. if ( ! _.isFunction( _.includes ) && _.isFunction( _.contains ) ) {
  21. _.includes = _.contains;
  22. }
  23. })( window );
  24. (function( window, undefined ) {
  25. 'use strict';
  26. var pad, r;
  27. /** @namespace wp */
  28. window.wp = window.wp || {};
  29. /** @namespace wp.api */
  30. wp.api = wp.api || {};
  31. /** @namespace wp.api.utils */
  32. wp.api.utils = wp.api.utils || {};
  33. /**
  34. * Determine model based on API route.
  35. *
  36. * @param {string} route The API route.
  37. *
  38. * @return {Backbone Model} The model found at given route. Undefined if not found.
  39. */
  40. wp.api.getModelByRoute = function( route ) {
  41. return _.find( wp.api.models, function( model ) {
  42. return model.prototype.route && route === model.prototype.route.index;
  43. } );
  44. };
  45. /**
  46. * Determine collection based on API route.
  47. *
  48. * @param {string} route The API route.
  49. *
  50. * @return {Backbone Model} The collection found at given route. Undefined if not found.
  51. */
  52. wp.api.getCollectionByRoute = function( route ) {
  53. return _.find( wp.api.collections, function( collection ) {
  54. return collection.prototype.route && route === collection.prototype.route.index;
  55. } );
  56. };
  57. /**
  58. * ECMAScript 5 shim, adapted from MDN.
  59. * @link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
  60. */
  61. if ( ! Date.prototype.toISOString ) {
  62. pad = function( number ) {
  63. r = String( number );
  64. if ( 1 === r.length ) {
  65. r = '0' + r;
  66. }
  67. return r;
  68. };
  69. Date.prototype.toISOString = function() {
  70. return this.getUTCFullYear() +
  71. '-' + pad( this.getUTCMonth() + 1 ) +
  72. '-' + pad( this.getUTCDate() ) +
  73. 'T' + pad( this.getUTCHours() ) +
  74. ':' + pad( this.getUTCMinutes() ) +
  75. ':' + pad( this.getUTCSeconds() ) +
  76. '.' + String( ( this.getUTCMilliseconds() / 1000 ).toFixed( 3 ) ).slice( 2, 5 ) +
  77. 'Z';
  78. };
  79. }
  80. /**
  81. * Parse date into ISO8601 format.
  82. *
  83. * @param {Date} date.
  84. */
  85. wp.api.utils.parseISO8601 = function( date ) {
  86. var timestamp, struct, i, k,
  87. minutesOffset = 0,
  88. numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ];
  89. // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string
  90. // before falling back to any implementation-specific date parsing, so that’s what we do, even if native
  91. // implementations could be faster.
  92. // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm
  93. if ( ( struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec( date ) ) ) {
  94. // Avoid NaN timestamps caused by “undefined” values being passed to Date.UTC.
  95. for ( i = 0; ( k = numericKeys[i] ); ++i ) {
  96. struct[k] = +struct[k] || 0;
  97. }
  98. // Allow undefined days and months.
  99. struct[2] = ( +struct[2] || 1 ) - 1;
  100. struct[3] = +struct[3] || 1;
  101. if ( 'Z' !== struct[8] && undefined !== struct[9] ) {
  102. minutesOffset = struct[10] * 60 + struct[11];
  103. if ( '+' === struct[9] ) {
  104. minutesOffset = 0 - minutesOffset;
  105. }
  106. }
  107. timestamp = Date.UTC( struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7] );
  108. } else {
  109. timestamp = Date.parse ? Date.parse( date ) : NaN;
  110. }
  111. return timestamp;
  112. };
  113. /**
  114. * Helper function for getting the root URL.
  115. * @return {[type]} [description]
  116. */
  117. wp.api.utils.getRootUrl = function() {
  118. return window.location.origin ?
  119. window.location.origin + '/' :
  120. window.location.protocol + '/' + window.location.host + '/';
  121. };
  122. /**
  123. * Helper for capitalizing strings.
  124. */
  125. wp.api.utils.capitalize = function( str ) {
  126. if ( _.isUndefined( str ) ) {
  127. return str;
  128. }
  129. return str.charAt( 0 ).toUpperCase() + str.slice( 1 );
  130. };
  131. /**
  132. * Helper function that capitalizes the first word and camel cases any words starting
  133. * after dashes, removing the dashes.
  134. */
  135. wp.api.utils.capitalizeAndCamelCaseDashes = function( str ) {
  136. if ( _.isUndefined( str ) ) {
  137. return str;
  138. }
  139. str = wp.api.utils.capitalize( str );
  140. return wp.api.utils.camelCaseDashes( str );
  141. };
  142. /**
  143. * Helper function to camel case the letter after dashes, removing the dashes.
  144. */
  145. wp.api.utils.camelCaseDashes = function( str ) {
  146. return str.replace( /-([a-z])/g, function( g ) {
  147. return g[ 1 ].toUpperCase();
  148. } );
  149. };
  150. /**
  151. * Extract a route part based on negative index.
  152. *
  153. * @param {string} route The endpoint route.
  154. * @param {int} part The number of parts from the end of the route to retrieve. Default 1.
  155. * Example route `/a/b/c`: part 1 is `c`, part 2 is `b`, part 3 is `a`.
  156. * @param {string} [versionString] Version string, defaults to `wp.api.versionString`.
  157. * @param {boolean} [reverse] Whether to reverse the order when extracting the route part. Optional, default false.
  158. */
  159. wp.api.utils.extractRoutePart = function( route, part, versionString, reverse ) {
  160. var routeParts;
  161. part = part || 1;
  162. versionString = versionString || wp.api.versionString;
  163. // Remove versions string from route to avoid returning it.
  164. if ( 0 === route.indexOf( '/' + versionString ) ) {
  165. route = route.substr( versionString.length + 1 );
  166. }
  167. routeParts = route.split( '/' );
  168. if ( reverse ) {
  169. routeParts = routeParts.reverse();
  170. }
  171. if ( _.isUndefined( routeParts[ --part ] ) ) {
  172. return '';
  173. }
  174. return routeParts[ part ];
  175. };
  176. /**
  177. * Extract a parent name from a passed route.
  178. *
  179. * @param {string} route The route to extract a name from.
  180. */
  181. wp.api.utils.extractParentName = function( route ) {
  182. var name,
  183. lastSlash = route.lastIndexOf( '_id>[\\d]+)/' );
  184. if ( lastSlash < 0 ) {
  185. return '';
  186. }
  187. name = route.substr( 0, lastSlash - 1 );
  188. name = name.split( '/' );
  189. name.pop();
  190. name = name.pop();
  191. return name;
  192. };
  193. /**
  194. * Add args and options to a model prototype from a route's endpoints.
  195. *
  196. * @param {array} routeEndpoints Array of route endpoints.
  197. * @param {Object} modelInstance An instance of the model (or collection)
  198. * to add the args to.
  199. */
  200. wp.api.utils.decorateFromRoute = function( routeEndpoints, modelInstance ) {
  201. /**
  202. * Build the args based on route endpoint data.
  203. */
  204. _.each( routeEndpoints, function( routeEndpoint ) {
  205. // Add post and edit endpoints as model args.
  206. if ( _.includes( routeEndpoint.methods, 'POST' ) || _.includes( routeEndpoint.methods, 'PUT' ) ) {
  207. // Add any non empty args, merging them into the args object.
  208. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  209. // Set as default if no args yet.
  210. if ( _.isEmpty( modelInstance.prototype.args ) ) {
  211. modelInstance.prototype.args = routeEndpoint.args;
  212. } else {
  213. // We already have args, merge these new args in.
  214. modelInstance.prototype.args = _.extend( modelInstance.prototype.args, routeEndpoint.args );
  215. }
  216. }
  217. } else {
  218. // Add GET method as model options.
  219. if ( _.includes( routeEndpoint.methods, 'GET' ) ) {
  220. // Add any non empty args, merging them into the defaults object.
  221. if ( ! _.isEmpty( routeEndpoint.args ) ) {
  222. // Set as default if no defaults yet.
  223. if ( _.isEmpty( modelInstance.prototype.options ) ) {
  224. modelInstance.prototype.options = routeEndpoint.args;
  225. } else {
  226. // We already have options, merge these new args in.
  227. modelInstance.prototype.options = _.extend( modelInstance.prototype.options, routeEndpoint.args );
  228. }
  229. }
  230. }
  231. }
  232. } );
  233. };
  234. /**
  235. * Add mixins and helpers to models depending on their defaults.
  236. *
  237. * @param {Backbone Model} model The model to attach helpers and mixins to.
  238. * @param {string} modelClassName The classname of the constructed model.
  239. * @param {Object} loadingObjects An object containing the models and collections we are building.
  240. */
  241. wp.api.utils.addMixinsAndHelpers = function( model, modelClassName, loadingObjects ) {
  242. var hasDate = false,
  243. /**
  244. * Array of parseable dates.
  245. *
  246. * @type {string[]}.
  247. */
  248. parseableDates = [ 'date', 'modified', 'date_gmt', 'modified_gmt' ],
  249. /**
  250. * Mixin for all content that is time stamped.
  251. *
  252. * This mixin converts between mysql timestamps and JavaScript Dates when syncing a model
  253. * to or from the server. For example, a date stored as `2015-12-27T21:22:24` on the server
  254. * gets expanded to `Sun Dec 27 2015 14:22:24 GMT-0700 (MST)` when the model is fetched.
  255. *
  256. * @type {{toJSON: toJSON, parse: parse}}.
  257. */
  258. TimeStampedMixin = {
  259. /**
  260. * Prepare a JavaScript Date for transmitting to the server.
  261. *
  262. * This helper function accepts a field and Date object. It converts the passed Date
  263. * to an ISO string and sets that on the model field.
  264. *
  265. * @param {Date} date A JavaScript date object. WordPress expects dates in UTC.
  266. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  267. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  268. */
  269. setDate: function( date, field ) {
  270. var theField = field || 'date';
  271. // Don't alter non parsable date fields.
  272. if ( _.indexOf( parseableDates, theField ) < 0 ) {
  273. return false;
  274. }
  275. this.set( theField, date.toISOString() );
  276. },
  277. /**
  278. * Get a JavaScript Date from the passed field.
  279. *
  280. * WordPress returns 'date' and 'date_modified' in the timezone of the server as well as
  281. * UTC dates as 'date_gmt' and 'date_modified_gmt'. Draft posts do not include UTC dates.
  282. *
  283. * @param {string} field The date field to set. One of 'date', 'date_gmt', 'date_modified'
  284. * or 'date_modified_gmt'. Optional, defaults to 'date'.
  285. */
  286. getDate: function( field ) {
  287. var theField = field || 'date',
  288. theISODate = this.get( theField );
  289. // Only get date fields and non null values.
  290. if ( _.indexOf( parseableDates, theField ) < 0 || _.isNull( theISODate ) ) {
  291. return false;
  292. }
  293. return new Date( wp.api.utils.parseISO8601( theISODate ) );
  294. }
  295. },
  296. /**
  297. * Build a helper function to retrieve related model.
  298. *
  299. * @param {string} parentModel The parent model.
  300. * @param {int} modelId The model ID if the object to request
  301. * @param {string} modelName The model name to use when constructing the model.
  302. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  303. * @param {string} embedCheckField Which model field to check to see if the model has data.
  304. *
  305. * @return {Deferred.promise} A promise which resolves to the constructed model.
  306. */
  307. buildModelGetter = function( parentModel, modelId, modelName, embedSourcePoint, embedCheckField ) {
  308. var getModel, embeddeds, attributes, deferred;
  309. deferred = jQuery.Deferred();
  310. embeddeds = parentModel.get( '_embedded' ) || {};
  311. // Verify that we have a valid object id.
  312. if ( ! _.isNumber( modelId ) || 0 === modelId ) {
  313. deferred.reject();
  314. return deferred;
  315. }
  316. // If we have embedded object data, use that when constructing the getModel.
  317. if ( embeddeds[ embedSourcePoint ] ) {
  318. attributes = _.findWhere( embeddeds[ embedSourcePoint ], { id: modelId } );
  319. }
  320. // Otherwise use the modelId.
  321. if ( ! attributes ) {
  322. attributes = { id: modelId };
  323. }
  324. // Create the new getModel model.
  325. getModel = new wp.api.models[ modelName ]( attributes );
  326. if ( ! getModel.get( embedCheckField ) ) {
  327. getModel.fetch( {
  328. success: function( getModel ) {
  329. deferred.resolve( getModel );
  330. },
  331. error: function( getModel, response ) {
  332. deferred.reject( response );
  333. }
  334. } );
  335. } else {
  336. // Resolve with the embedded model.
  337. deferred.resolve( getModel );
  338. }
  339. // Return a promise.
  340. return deferred.promise();
  341. },
  342. /**
  343. * Build a helper to retrieve a collection.
  344. *
  345. * @param {string} parentModel The parent model.
  346. * @param {string} collectionName The name to use when constructing the collection.
  347. * @param {string} embedSourcePoint Where to check the embedds object for _embed data.
  348. * @param {string} embedIndex An addiitonal optional index for the _embed data.
  349. *
  350. * @return {Deferred.promise} A promise which resolves to the constructed collection.
  351. */
  352. buildCollectionGetter = function( parentModel, collectionName, embedSourcePoint, embedIndex ) {
  353. /**
  354. * Returns a promise that resolves to the requested collection
  355. *
  356. * Uses the embedded data if available, otherwises fetches the
  357. * data from the server.
  358. *
  359. * @return {Deferred.promise} promise Resolves to a wp.api.collections[ collectionName ]
  360. * collection.
  361. */
  362. var postId, embeddeds, getObjects,
  363. classProperties = '',
  364. properties = '',
  365. deferred = jQuery.Deferred();
  366. postId = parentModel.get( 'id' );
  367. embeddeds = parentModel.get( '_embedded' ) || {};
  368. // Verify that we have a valid post id.
  369. if ( ! _.isNumber( postId ) || 0 === postId ) {
  370. deferred.reject();
  371. return deferred;
  372. }
  373. // If we have embedded getObjects data, use that when constructing the getObjects.
  374. if ( ! _.isUndefined( embedSourcePoint ) && ! _.isUndefined( embeddeds[ embedSourcePoint ] ) ) {
  375. // Some embeds also include an index offset, check for that.
  376. if ( _.isUndefined( embedIndex ) ) {
  377. // Use the embed source point directly.
  378. properties = embeddeds[ embedSourcePoint ];
  379. } else {
  380. // Add the index to the embed source point.
  381. properties = embeddeds[ embedSourcePoint ][ embedIndex ];
  382. }
  383. } else {
  384. // Otherwise use the postId.
  385. classProperties = { parent: postId };
  386. }
  387. // Create the new getObjects collection.
  388. getObjects = new wp.api.collections[ collectionName ]( properties, classProperties );
  389. // If we didn’t have embedded getObjects, fetch the getObjects data.
  390. if ( _.isUndefined( getObjects.models[0] ) ) {
  391. getObjects.fetch( {
  392. success: function( getObjects ) {
  393. // Add a helper 'parent_post' attribute onto the model.
  394. setHelperParentPost( getObjects, postId );
  395. deferred.resolve( getObjects );
  396. },
  397. error: function( getModel, response ) {
  398. deferred.reject( response );
  399. }
  400. } );
  401. } else {
  402. // Add a helper 'parent_post' attribute onto the model.
  403. setHelperParentPost( getObjects, postId );
  404. deferred.resolve( getObjects );
  405. }
  406. // Return a promise.
  407. return deferred.promise();
  408. },
  409. /**
  410. * Set the model post parent.
  411. */
  412. setHelperParentPost = function( collection, postId ) {
  413. // Attach post_parent id to the collection.
  414. _.each( collection.models, function( model ) {
  415. model.set( 'parent_post', postId );
  416. } );
  417. },
  418. /**
  419. * Add a helper function to handle post Meta.
  420. */
  421. MetaMixin = {
  422. /**
  423. * Get meta by key for a post.
  424. *
  425. * @param {string} key The meta key.
  426. *
  427. * @return {object} The post meta value.
  428. */
  429. getMeta: function( key ) {
  430. var metas = this.get( 'meta' );
  431. return metas[ key ];
  432. },
  433. /**
  434. * Get all meta key/values for a post.
  435. *
  436. * @return {object} The post metas, as a key value pair object.
  437. */
  438. getMetas: function() {
  439. return this.get( 'meta' );
  440. },
  441. /**
  442. * Set a group of meta key/values for a post.
  443. *
  444. * @param {object} meta The post meta to set, as key/value pairs.
  445. */
  446. setMetas: function( meta ) {
  447. var metas = this.get( 'meta' );
  448. _.extend( metas, meta );
  449. this.set( 'meta', metas );
  450. },
  451. /**
  452. * Set a single meta value for a post, by key.
  453. *
  454. * @param {string} key The meta key.
  455. * @param {object} value The meta value.
  456. */
  457. setMeta: function( key, value ) {
  458. var metas = this.get( 'meta' );
  459. metas[ key ] = value;
  460. this.set( 'meta', metas );
  461. }
  462. },
  463. /**
  464. * Add a helper function to handle post Revisions.
  465. */
  466. RevisionsMixin = {
  467. getRevisions: function() {
  468. return buildCollectionGetter( this, 'PostRevisions' );
  469. }
  470. },
  471. /**
  472. * Add a helper function to handle post Tags.
  473. */
  474. TagsMixin = {
  475. /**
  476. * Get the tags for a post.
  477. *
  478. * @return {Deferred.promise} promise Resolves to an array of tags.
  479. */
  480. getTags: function() {
  481. var tagIds = this.get( 'tags' ),
  482. tags = new wp.api.collections.Tags();
  483. // Resolve with an empty array if no tags.
  484. if ( _.isEmpty( tagIds ) ) {
  485. return jQuery.Deferred().resolve( [] );
  486. }
  487. return tags.fetch( { data: { include: tagIds } } );
  488. },
  489. /**
  490. * Set the tags for a post.
  491. *
  492. * Accepts an array of tag slugs, or a Tags collection.
  493. *
  494. * @param {array|Backbone.Collection} tags The tags to set on the post.
  495. *
  496. */
  497. setTags: function( tags ) {
  498. var allTags, newTag,
  499. self = this,
  500. newTags = [];
  501. if ( _.isString( tags ) ) {
  502. return false;
  503. }
  504. // If this is an array of slugs, build a collection.
  505. if ( _.isArray( tags ) ) {
  506. // Get all the tags.
  507. allTags = new wp.api.collections.Tags();
  508. allTags.fetch( {
  509. data: { per_page: 100 },
  510. success: function( alltags ) {
  511. // Find the passed tags and set them up.
  512. _.each( tags, function( tag ) {
  513. newTag = new wp.api.models.Tag( alltags.findWhere( { slug: tag } ) );
  514. // Tie the new tag to the post.
  515. newTag.set( 'parent_post', self.get( 'id' ) );
  516. // Add the new tag to the collection.
  517. newTags.push( newTag );
  518. } );
  519. tags = new wp.api.collections.Tags( newTags );
  520. self.setTagsWithCollection( tags );
  521. }
  522. } );
  523. } else {
  524. this.setTagsWithCollection( tags );
  525. }
  526. },
  527. /**
  528. * Set the tags for a post.
  529. *
  530. * Accepts a Tags collection.
  531. *
  532. * @param {array|Backbone.Collection} tags The tags to set on the post.
  533. *
  534. */
  535. setTagsWithCollection: function( tags ) {
  536. // Pluck out the category ids.
  537. this.set( 'tags', tags.pluck( 'id' ) );
  538. return this.save();
  539. }
  540. },
  541. /**
  542. * Add a helper function to handle post Categories.
  543. */
  544. CategoriesMixin = {
  545. /**
  546. * Get a the categories for a post.
  547. *
  548. * @return {Deferred.promise} promise Resolves to an array of categories.
  549. */
  550. getCategories: function() {
  551. var categoryIds = this.get( 'categories' ),
  552. categories = new wp.api.collections.Categories();
  553. // Resolve with an empty array if no categories.
  554. if ( _.isEmpty( categoryIds ) ) {
  555. return jQuery.Deferred().resolve( [] );
  556. }
  557. return categories.fetch( { data: { include: categoryIds } } );
  558. },
  559. /**
  560. * Set the categories for a post.
  561. *
  562. * Accepts an array of category slugs, or a Categories collection.
  563. *
  564. * @param {array|Backbone.Collection} categories The categories to set on the post.
  565. *
  566. */
  567. setCategories: function( categories ) {
  568. var allCategories, newCategory,
  569. self = this,
  570. newCategories = [];
  571. if ( _.isString( categories ) ) {
  572. return false;
  573. }
  574. // If this is an array of slugs, build a collection.
  575. if ( _.isArray( categories ) ) {
  576. // Get all the categories.
  577. allCategories = new wp.api.collections.Categories();
  578. allCategories.fetch( {
  579. data: { per_page: 100 },
  580. success: function( allcats ) {
  581. // Find the passed categories and set them up.
  582. _.each( categories, function( category ) {
  583. newCategory = new wp.api.models.Category( allcats.findWhere( { slug: category } ) );
  584. // Tie the new category to the post.
  585. newCategory.set( 'parent_post', self.get( 'id' ) );
  586. // Add the new category to the collection.
  587. newCategories.push( newCategory );
  588. } );
  589. categories = new wp.api.collections.Categories( newCategories );
  590. self.setCategoriesWithCollection( categories );
  591. }
  592. } );
  593. } else {
  594. this.setCategoriesWithCollection( categories );
  595. }
  596. },
  597. /**
  598. * Set the categories for a post.
  599. *
  600. * Accepts Categories collection.
  601. *
  602. * @param {array|Backbone.Collection} categories The categories to set on the post.
  603. *
  604. */
  605. setCategoriesWithCollection: function( categories ) {
  606. // Pluck out the category ids.
  607. this.set( 'categories', categories.pluck( 'id' ) );
  608. return this.save();
  609. }
  610. },
  611. /**
  612. * Add a helper function to retrieve the author user model.
  613. */
  614. AuthorMixin = {
  615. getAuthorUser: function() {
  616. return buildModelGetter( this, this.get( 'author' ), 'User', 'author', 'name' );
  617. }
  618. },
  619. /**
  620. * Add a helper function to retrieve the featured media.
  621. */
  622. FeaturedMediaMixin = {
  623. getFeaturedMedia: function() {
  624. return buildModelGetter( this, this.get( 'featured_media' ), 'Media', 'wp:featuredmedia', 'source_url' );
  625. }
  626. };
  627. // Exit if we don't have valid model defaults.
  628. if ( _.isUndefined( model.prototype.args ) ) {
  629. return model;
  630. }
  631. // Go thru the parsable date fields, if our model contains any of them it gets the TimeStampedMixin.
  632. _.each( parseableDates, function( theDateKey ) {
  633. if ( ! _.isUndefined( model.prototype.args[ theDateKey ] ) ) {
  634. hasDate = true;
  635. }
  636. } );
  637. // Add the TimeStampedMixin for models that contain a date field.
  638. if ( hasDate ) {
  639. model = model.extend( TimeStampedMixin );
  640. }
  641. // Add the AuthorMixin for models that contain an author.
  642. if ( ! _.isUndefined( model.prototype.args.author ) ) {
  643. model = model.extend( AuthorMixin );
  644. }
  645. // Add the FeaturedMediaMixin for models that contain a featured_media.
  646. if ( ! _.isUndefined( model.prototype.args.featured_media ) ) {
  647. model = model.extend( FeaturedMediaMixin );
  648. }
  649. // Add the CategoriesMixin for models that support categories collections.
  650. if ( ! _.isUndefined( model.prototype.args.categories ) ) {
  651. model = model.extend( CategoriesMixin );
  652. }
  653. // Add the MetaMixin for models that support meta.
  654. if ( ! _.isUndefined( model.prototype.args.meta ) ) {
  655. model = model.extend( MetaMixin );
  656. }
  657. // Add the TagsMixin for models that support tags collections.
  658. if ( ! _.isUndefined( model.prototype.args.tags ) ) {
  659. model = model.extend( TagsMixin );
  660. }
  661. // Add the RevisionsMixin for models that support revisions collections.
  662. if ( ! _.isUndefined( loadingObjects.collections[ modelClassName + 'Revisions' ] ) ) {
  663. model = model.extend( RevisionsMixin );
  664. }
  665. return model;
  666. };
  667. })( window );
  668. /* global wpApiSettings:false */
  669. // Suppress warning about parse function's unused "options" argument:
  670. /* jshint unused:false */
  671. (function() {
  672. 'use strict';
  673. var wpApiSettings = window.wpApiSettings || {},
  674. trashableTypes = [ 'Comment', 'Media', 'Comment', 'Post', 'Page', 'Status', 'Taxonomy', 'Type' ];
  675. /**
  676. * Backbone base model for all models.
  677. */
  678. wp.api.WPApiBaseModel = Backbone.Model.extend(
  679. /** @lends WPApiBaseModel.prototype */
  680. {
  681. // Initialize the model.
  682. initialize: function() {
  683. /**
  684. * Types that don't support trashing require passing ?force=true to delete.
  685. *
  686. */
  687. if ( -1 === _.indexOf( trashableTypes, this.name ) ) {
  688. this.requireForceForDelete = true;
  689. }
  690. },
  691. /**
  692. * Set nonce header before every Backbone sync.
  693. *
  694. * @param {string} method.
  695. * @param {Backbone.Model} model.
  696. * @param {{beforeSend}, *} options.
  697. * @returns {*}.
  698. */
  699. sync: function( method, model, options ) {
  700. var beforeSend;
  701. options = options || {};
  702. // Remove date_gmt if null.
  703. if ( _.isNull( model.get( 'date_gmt' ) ) ) {
  704. model.unset( 'date_gmt' );
  705. }
  706. // Remove slug if empty.
  707. if ( _.isEmpty( model.get( 'slug' ) ) ) {
  708. model.unset( 'slug' );
  709. }
  710. if ( _.isFunction( model.nonce ) && ! _.isUndefined( model.nonce() ) && ! _.isNull( model.nonce() ) ) {
  711. beforeSend = options.beforeSend;
  712. // @todo enable option for jsonp endpoints
  713. // options.dataType = 'jsonp';
  714. // Include the nonce with requests.
  715. options.beforeSend = function( xhr ) {
  716. xhr.setRequestHeader( 'X-WP-Nonce', model.nonce() );
  717. if ( beforeSend ) {
  718. return beforeSend.apply( this, arguments );
  719. }
  720. };
  721. // Update the nonce when a new nonce is returned with the response.
  722. options.complete = function( xhr ) {
  723. var returnedNonce = xhr.getResponseHeader( 'X-WP-Nonce' );
  724. if ( returnedNonce && _.isFunction( model.nonce ) && model.nonce() !== returnedNonce ) {
  725. model.endpointModel.set( 'nonce', returnedNonce );
  726. }
  727. };
  728. }
  729. // Add '?force=true' to use delete method when required.
  730. if ( this.requireForceForDelete && 'delete' === method ) {
  731. model.url = model.url() + '?force=true';
  732. }
  733. return Backbone.sync( method, model, options );
  734. },
  735. /**
  736. * Save is only allowed when the PUT OR POST methods are available for the endpoint.
  737. */
  738. save: function( attrs, options ) {
  739. // Do we have the put method, then execute the save.
  740. if ( _.includes( this.methods, 'PUT' ) || _.includes( this.methods, 'POST' ) ) {
  741. // Proxy the call to the original save function.
  742. return Backbone.Model.prototype.save.call( this, attrs, options );
  743. } else {
  744. // Otherwise bail, disallowing action.
  745. return false;
  746. }
  747. },
  748. /**
  749. * Delete is only allowed when the DELETE method is available for the endpoint.
  750. */
  751. destroy: function( options ) {
  752. // Do we have the DELETE method, then execute the destroy.
  753. if ( _.includes( this.methods, 'DELETE' ) ) {
  754. // Proxy the call to the original save function.
  755. return Backbone.Model.prototype.destroy.call( this, options );
  756. } else {
  757. // Otherwise bail, disallowing action.
  758. return false;
  759. }
  760. }
  761. }
  762. );
  763. /**
  764. * API Schema model. Contains meta information about the API.
  765. */
  766. wp.api.models.Schema = wp.api.WPApiBaseModel.extend(
  767. /** @lends Schema.prototype */
  768. {
  769. defaults: {
  770. _links: {},
  771. namespace: null,
  772. routes: {}
  773. },
  774. initialize: function( attributes, options ) {
  775. var model = this;
  776. options = options || {};
  777. wp.api.WPApiBaseModel.prototype.initialize.call( model, attributes, options );
  778. model.apiRoot = options.apiRoot || wpApiSettings.root;
  779. model.versionString = options.versionString || wpApiSettings.versionString;
  780. },
  781. url: function() {
  782. return this.apiRoot + this.versionString;
  783. }
  784. }
  785. );
  786. })();
  787. ( function() {
  788. 'use strict';
  789. var wpApiSettings = window.wpApiSettings || {};
  790. /**
  791. * Contains basic collection functionality such as pagination.
  792. */
  793. wp.api.WPApiBaseCollection = Backbone.Collection.extend(
  794. /** @lends BaseCollection.prototype */
  795. {
  796. /**
  797. * Setup default state.
  798. */
  799. initialize: function( models, options ) {
  800. this.state = {
  801. data: {},
  802. currentPage: null,
  803. totalPages: null,
  804. totalObjects: null
  805. };
  806. if ( _.isUndefined( options ) ) {
  807. this.parent = '';
  808. } else {
  809. this.parent = options.parent;
  810. }
  811. },
  812. /**
  813. * Extend Backbone.Collection.sync to add nince and pagination support.
  814. *
  815. * Set nonce header before every Backbone sync.
  816. *
  817. * @param {string} method.
  818. * @param {Backbone.Model} model.
  819. * @param {{success}, *} options.
  820. * @returns {*}.
  821. */
  822. sync: function( method, model, options ) {
  823. var beforeSend, success,
  824. self = this;
  825. options = options || {};
  826. beforeSend = options.beforeSend;
  827. // If we have a localized nonce, pass that along with each sync.
  828. if ( 'undefined' !== typeof wpApiSettings.nonce ) {
  829. options.beforeSend = function( xhr ) {
  830. xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
  831. if ( beforeSend ) {
  832. return beforeSend.apply( self, arguments );
  833. }
  834. };
  835. }
  836. // When reading, add pagination data.
  837. if ( 'read' === method ) {
  838. if ( options.data ) {
  839. self.state.data = _.clone( options.data );
  840. delete self.state.data.page;
  841. } else {
  842. self.state.data = options.data = {};
  843. }
  844. if ( 'undefined' === typeof options.data.page ) {
  845. self.state.currentPage = null;
  846. self.state.totalPages = null;
  847. self.state.totalObjects = null;
  848. } else {
  849. self.state.currentPage = options.data.page - 1;
  850. }
  851. success = options.success;
  852. options.success = function( data, textStatus, request ) {
  853. if ( ! _.isUndefined( request ) ) {
  854. self.state.totalPages = parseInt( request.getResponseHeader( 'x-wp-totalpages' ), 10 );
  855. self.state.totalObjects = parseInt( request.getResponseHeader( 'x-wp-total' ), 10 );
  856. }
  857. if ( null === self.state.currentPage ) {
  858. self.state.currentPage = 1;
  859. } else {
  860. self.state.currentPage++;
  861. }
  862. if ( success ) {
  863. return success.apply( this, arguments );
  864. }
  865. };
  866. }
  867. // Continue by calling Bacckbone's sync.
  868. return Backbone.sync( method, model, options );
  869. },
  870. /**
  871. * Fetches the next page of objects if a new page exists.
  872. *
  873. * @param {data: {page}} options.
  874. * @returns {*}.
  875. */
  876. more: function( options ) {
  877. options = options || {};
  878. options.data = options.data || {};
  879. _.extend( options.data, this.state.data );
  880. if ( 'undefined' === typeof options.data.page ) {
  881. if ( ! this.hasMore() ) {
  882. return false;
  883. }
  884. if ( null === this.state.currentPage || this.state.currentPage <= 1 ) {
  885. options.data.page = 2;
  886. } else {
  887. options.data.page = this.state.currentPage + 1;
  888. }
  889. }
  890. return this.fetch( options );
  891. },
  892. /**
  893. * Returns true if there are more pages of objects available.
  894. *
  895. * @returns null|boolean.
  896. */
  897. hasMore: function() {
  898. if ( null === this.state.totalPages ||
  899. null === this.state.totalObjects ||
  900. null === this.state.currentPage ) {
  901. return null;
  902. } else {
  903. return ( this.state.currentPage < this.state.totalPages );
  904. }
  905. }
  906. }
  907. );
  908. } )();
  909. ( function() {
  910. 'use strict';
  911. var Endpoint, initializedDeferreds = {},
  912. wpApiSettings = window.wpApiSettings || {};
  913. /** @namespace wp */
  914. window.wp = window.wp || {};
  915. /** @namespace wp.api */
  916. wp.api = wp.api || {};
  917. // If wpApiSettings is unavailable, try the default.
  918. if ( _.isEmpty( wpApiSettings ) ) {
  919. wpApiSettings.root = window.location.origin + '/wp-json/';
  920. }
  921. Endpoint = Backbone.Model.extend(/** @lends Endpoint.prototype */{
  922. defaults: {
  923. apiRoot: wpApiSettings.root,
  924. versionString: wp.api.versionString,
  925. nonce: null,
  926. schema: null,
  927. models: {},
  928. collections: {}
  929. },
  930. /**
  931. * Initialize the Endpoint model.
  932. */
  933. initialize: function() {
  934. var model = this, deferred;
  935. Backbone.Model.prototype.initialize.apply( model, arguments );
  936. deferred = jQuery.Deferred();
  937. model.schemaConstructed = deferred.promise();
  938. model.schemaModel = new wp.api.models.Schema( null, {
  939. apiRoot: model.get( 'apiRoot' ),
  940. versionString: model.get( 'versionString' ),
  941. nonce: model.get( 'nonce' )
  942. } );
  943. // When the model loads, resolve the promise.
  944. model.schemaModel.once( 'change', function() {
  945. model.constructFromSchema();
  946. deferred.resolve( model );
  947. } );
  948. if ( model.get( 'schema' ) ) {
  949. // Use schema supplied as model attribute.
  950. model.schemaModel.set( model.schemaModel.parse( model.get( 'schema' ) ) );
  951. } else if (
  952. ! _.isUndefined( sessionStorage ) &&
  953. ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) &&
  954. sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) )
  955. ) {
  956. // Used a cached copy of the schema model if available.
  957. model.schemaModel.set( model.schemaModel.parse( JSON.parse( sessionStorage.getItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ) ) ) ) );
  958. } else {
  959. model.schemaModel.fetch( {
  960. /**
  961. * When the server returns the schema model data, store the data in a sessionCache so we don't
  962. * have to retrieve it again for this session. Then, construct the models and collections based
  963. * on the schema model data.
  964. *
  965. * @callback
  966. */
  967. success: function( newSchemaModel ) {
  968. // Store a copy of the schema model in the session cache if available.
  969. if ( ! _.isUndefined( sessionStorage ) && ( _.isUndefined( wpApiSettings.cacheSchema ) || wpApiSettings.cacheSchema ) ) {
  970. try {
  971. sessionStorage.setItem( 'wp-api-schema-model' + model.get( 'apiRoot' ) + model.get( 'versionString' ), JSON.stringify( newSchemaModel ) );
  972. } catch ( error ) {
  973. // Fail silently, fixes errors in safari private mode.
  974. }
  975. }
  976. },
  977. // Log the error condition.
  978. error: function( err ) {
  979. window.console.log( err );
  980. }
  981. } );
  982. }
  983. },
  984. constructFromSchema: function() {
  985. var routeModel = this, modelRoutes, collectionRoutes, schemaRoot, loadingObjects,
  986. /**
  987. * Set up the model and collection name mapping options. As the schema is built, the
  988. * model and collection names will be adjusted if they are found in the mapping object.
  989. *
  990. * Localizing a variable wpApiSettings.mapping will over-ride the default mapping options.
  991. *
  992. */
  993. mapping = wpApiSettings.mapping || {
  994. models: {
  995. 'Categories': 'Category',
  996. 'Comments': 'Comment',
  997. 'Pages': 'Page',
  998. 'PagesMeta': 'PageMeta',
  999. 'PagesRevisions': 'PageRevision',
  1000. 'Posts': 'Post',
  1001. 'PostsCategories': 'PostCategory',
  1002. 'PostsRevisions': 'PostRevision',
  1003. 'PostsTags': 'PostTag',
  1004. 'Schema': 'Schema',
  1005. 'Statuses': 'Status',
  1006. 'Tags': 'Tag',
  1007. 'Taxonomies': 'Taxonomy',
  1008. 'Types': 'Type',
  1009. 'Users': 'User'
  1010. },
  1011. collections: {
  1012. 'PagesMeta': 'PageMeta',
  1013. 'PagesRevisions': 'PageRevisions',
  1014. 'PostsCategories': 'PostCategories',
  1015. 'PostsMeta': 'PostMeta',
  1016. 'PostsRevisions': 'PostRevisions',
  1017. 'PostsTags': 'PostTags'
  1018. }
  1019. },
  1020. modelEndpoints = routeModel.get( 'modelEndpoints' ),
  1021. modelRegex = new RegExp( '(?:.*[+)]|\/(' + modelEndpoints.join( '|' ) + '))$' );
  1022. /**
  1023. * Iterate thru the routes, picking up models and collections to build. Builds two arrays,
  1024. * one for models and one for collections.
  1025. */
  1026. modelRoutes = [];
  1027. collectionRoutes = [];
  1028. schemaRoot = routeModel.get( 'apiRoot' ).replace( wp.api.utils.getRootUrl(), '' );
  1029. loadingObjects = {};
  1030. /**
  1031. * Tracking objects for models and collections.
  1032. */
  1033. loadingObjects.models = {};
  1034. loadingObjects.collections = {};
  1035. _.each( routeModel.schemaModel.get( 'routes' ), function( route, index ) {
  1036. // Skip the schema root if included in the schema.
  1037. if ( index !== routeModel.get( ' versionString' ) &&
  1038. index !== schemaRoot &&
  1039. index !== ( '/' + routeModel.get( 'versionString' ).slice( 0, -1 ) )
  1040. ) {
  1041. // Single items end with a regex, or a special case word.
  1042. if ( modelRegex.test( index ) ) {
  1043. modelRoutes.push( { index: index, route: route } );
  1044. } else {
  1045. // Collections end in a name.
  1046. collectionRoutes.push( { index: index, route: route } );
  1047. }
  1048. }
  1049. } );
  1050. /**
  1051. * Construct the models.
  1052. *
  1053. * Base the class name on the route endpoint.
  1054. */
  1055. _.each( modelRoutes, function( modelRoute ) {
  1056. // Extract the name and any parent from the route.
  1057. var modelClassName,
  1058. routeName = wp.api.utils.extractRoutePart( modelRoute.index, 2, routeModel.get( 'versionString' ), true ),
  1059. parentName = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), false ),
  1060. routeEnd = wp.api.utils.extractRoutePart( modelRoute.index, 1, routeModel.get( 'versionString' ), true );
  1061. // Clear the parent part of the rouite if its actually the version string.
  1062. if ( parentName === routeModel.get( 'versionString' ) ) {
  1063. parentName = '';
  1064. }
  1065. // Handle the special case of the 'me' route.
  1066. if ( 'me' === routeEnd ) {
  1067. routeName = 'me';
  1068. }
  1069. // If the model has a parent in its route, add that to its class name.
  1070. if ( '' !== parentName && parentName !== routeName ) {
  1071. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1072. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  1073. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  1074. // Return a constructed url based on the parent and id.
  1075. url: function() {
  1076. var url =
  1077. routeModel.get( 'apiRoot' ) +
  1078. routeModel.get( 'versionString' ) +
  1079. parentName + '/' +
  1080. ( ( _.isUndefined( this.get( 'parent' ) ) || 0 === this.get( 'parent' ) ) ?
  1081. ( _.isUndefined( this.get( 'parent_post' ) ) ? '' : this.get( 'parent_post' ) + '/' ) :
  1082. this.get( 'parent' ) + '/' ) +
  1083. routeName;
  1084. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  1085. url += '/' + this.get( 'id' );
  1086. }
  1087. return url;
  1088. },
  1089. // Track nonces on the Endpoint 'routeModel'.
  1090. nonce: function() {
  1091. return routeModel.get( 'nonce' );
  1092. },
  1093. endpointModel: routeModel,
  1094. // Include a reference to the original route object.
  1095. route: modelRoute,
  1096. // Include a reference to the original class name.
  1097. name: modelClassName,
  1098. // Include the array of route methods for easy reference.
  1099. methods: modelRoute.route.methods,
  1100. // Include the array of route endpoints for easy reference.
  1101. endpoints: modelRoute.route.endpoints
  1102. } );
  1103. } else {
  1104. // This is a model without a parent in its route
  1105. modelClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1106. modelClassName = mapping.models[ modelClassName ] || modelClassName;
  1107. loadingObjects.models[ modelClassName ] = wp.api.WPApiBaseModel.extend( {
  1108. // Function that returns a constructed url based on the id.
  1109. url: function() {
  1110. var url = routeModel.get( 'apiRoot' ) +
  1111. routeModel.get( 'versionString' ) +
  1112. ( ( 'me' === routeName ) ? 'users/me' : routeName );
  1113. if ( ! _.isUndefined( this.get( 'id' ) ) ) {
  1114. url += '/' + this.get( 'id' );
  1115. }
  1116. return url;
  1117. },
  1118. // Track nonces at the Endpoint level.
  1119. nonce: function() {
  1120. return routeModel.get( 'nonce' );
  1121. },
  1122. endpointModel: routeModel,
  1123. // Include a reference to the original route object.
  1124. route: modelRoute,
  1125. // Include a reference to the original class name.
  1126. name: modelClassName,
  1127. // Include the array of route methods for easy reference.
  1128. methods: modelRoute.route.methods,
  1129. // Include the array of route endpoints for easy reference.
  1130. endpoints: modelRoute.route.endpoints
  1131. } );
  1132. }
  1133. // Add defaults to the new model, pulled form the endpoint.
  1134. wp.api.utils.decorateFromRoute(
  1135. modelRoute.route.endpoints,
  1136. loadingObjects.models[ modelClassName ],
  1137. routeModel.get( 'versionString' )
  1138. );
  1139. } );
  1140. /**
  1141. * Construct the collections.
  1142. *
  1143. * Base the class name on the route endpoint.
  1144. */
  1145. _.each( collectionRoutes, function( collectionRoute ) {
  1146. // Extract the name and any parent from the route.
  1147. var collectionClassName, modelClassName,
  1148. routeName = collectionRoute.index.slice( collectionRoute.index.lastIndexOf( '/' ) + 1 ),
  1149. parentName = wp.api.utils.extractRoutePart( collectionRoute.index, 1, routeModel.get( 'versionString' ), false );
  1150. // If the collection has a parent in its route, add that to its class name.
  1151. if ( '' !== parentName && parentName !== routeName && routeModel.get( 'versionString' ) !== parentName ) {
  1152. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( parentName ) + wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1153. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1154. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1155. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1156. // Function that returns a constructed url passed on the parent.
  1157. url: function() {
  1158. return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) +
  1159. parentName + '/' + this.parent + '/' +
  1160. routeName;
  1161. },
  1162. // Specify the model that this collection contains.
  1163. model: function( attrs, options ) {
  1164. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1165. },
  1166. // Include a reference to the original class name.
  1167. name: collectionClassName,
  1168. // Include a reference to the original route object.
  1169. route: collectionRoute,
  1170. // Include the array of route methods for easy reference.
  1171. methods: collectionRoute.route.methods
  1172. } );
  1173. } else {
  1174. // This is a collection without a parent in its route.
  1175. collectionClassName = wp.api.utils.capitalizeAndCamelCaseDashes( routeName );
  1176. modelClassName = mapping.models[ collectionClassName ] || collectionClassName;
  1177. collectionClassName = mapping.collections[ collectionClassName ] || collectionClassName;
  1178. loadingObjects.collections[ collectionClassName ] = wp.api.WPApiBaseCollection.extend( {
  1179. // For the url of a root level collection, use a string.
  1180. url: function() {
  1181. return routeModel.get( 'apiRoot' ) + routeModel.get( 'versionString' ) + routeName;
  1182. },
  1183. // Specify the model that this collection contains.
  1184. model: function( attrs, options ) {
  1185. return new loadingObjects.models[ modelClassName ]( attrs, options );
  1186. },
  1187. // Include a reference to the original class name.
  1188. name: collectionClassName,
  1189. // Include a reference to the original route object.
  1190. route: collectionRoute,
  1191. // Include the array of route methods for easy reference.
  1192. methods: collectionRoute.route.methods
  1193. } );
  1194. }
  1195. // Add defaults to the new model, pulled form the endpoint.
  1196. wp.api.utils.decorateFromRoute( collectionRoute.route.endpoints, loadingObjects.collections[ collectionClassName ] );
  1197. } );
  1198. // Add mixins and helpers for each of the models.
  1199. _.each( loadingObjects.models, function( model, index ) {
  1200. loadingObjects.models[ index ] = wp.api.utils.addMixinsAndHelpers( model, index, loadingObjects );
  1201. } );
  1202. // Set the routeModel models and collections.
  1203. routeModel.set( 'models', loadingObjects.models );
  1204. routeModel.set( 'collections', loadingObjects.collections );
  1205. }
  1206. } );
  1207. wp.api.endpoints = new Backbone.Collection();
  1208. /**
  1209. * Initialize the wp-api, optionally passing the API root.
  1210. *
  1211. * @param {object} [args]
  1212. * @param {string} [args.apiRoot] The api root. Optional, defaults to wpApiSettings.root.
  1213. * @param {string} [args.versionString] The version string. Optional, defaults to wpApiSettings.root.
  1214. * @param {object} [args.schema] The schema. Optional, will be fetched from API if not provided.
  1215. */
  1216. wp.api.init = function( args ) {
  1217. var endpoint, attributes = {}, deferred, promise;
  1218. args = args || {};
  1219. attributes.nonce = args.nonce || wpApiSettings.nonce || '';
  1220. attributes.apiRoot = args.apiRoot || wpApiSettings.root || '/wp-json';
  1221. attributes.versionString = args.versionString || wpApiSettings.versionString || 'wp/v2/';
  1222. attributes.schema = args.schema || null;
  1223. attributes.modelEndpoints = args.modelEndpoints || [ 'me', 'settings' ];
  1224. if ( ! attributes.schema && attributes.apiRoot === wpApiSettings.root && attributes.versionString === wpApiSettings.versionString ) {
  1225. attributes.schema = wpApiSettings.schema;
  1226. }
  1227. if ( ! initializedDeferreds[ attributes.apiRoot + attributes.versionString ] ) {
  1228. // Look for an existing copy of this endpoint
  1229. endpoint = wp.api.endpoints.findWhere( { 'apiRoot': attributes.apiRoot, 'versionString': attributes.versionString } );
  1230. if ( ! endpoint ) {
  1231. endpoint = new Endpoint( attributes );
  1232. }
  1233. deferred = jQuery.Deferred();
  1234. promise = deferred.promise();
  1235. endpoint.schemaConstructed.done( function( resolvedEndpoint ) {
  1236. wp.api.endpoints.add( resolvedEndpoint );
  1237. // Map the default endpoints, extending any already present items (including Schema model).
  1238. wp.api.models = _.extend( wp.api.models, resolvedEndpoint.get( 'models' ) );
  1239. wp.api.collections = _.extend( wp.api.collections, resolvedEndpoint.get( 'collections' ) );
  1240. deferred.resolve( resolvedEndpoint );
  1241. } );
  1242. initializedDeferreds[ attributes.apiRoot + attributes.versionString ] = promise;
  1243. }
  1244. return initializedDeferreds[ attributes.apiRoot + attributes.versionString ];
  1245. };
  1246. /**
  1247. * Construct the default endpoints and add to an endpoints collection.
  1248. */
  1249. // The wp.api.init function returns a promise that will resolve with the endpoint once it is ready.
  1250. wp.api.loadPromise = wp.api.init();
  1251. } )();