fix: prevent asset conflicts between React and Grid.js versions

Add coexistence checks to all enqueue methods to prevent loading
both React and Grid.js assets simultaneously.

Changes:
- ReactAdmin.php: Only enqueue React assets when ?react=1
- Init.php: Skip Grid.js when React active on admin pages
- Form.php, Coupon.php, Access.php: Restore classic assets when ?react=0
- Customer.php, Product.php, License.php: Add coexistence checks

Now the toggle between Classic and React versions works correctly.

Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
dwindown
2026-04-18 17:02:14 +07:00
parent bd9cdac02e
commit e8fbfb14c1
74973 changed files with 6658406 additions and 71 deletions

212
node_modules/@wordpress/api-fetch/CHANGELOG.md generated vendored Normal file
View File

@@ -0,0 +1,212 @@
<!-- Learn how to maintain this file at https://github.com/WordPress/gutenberg/tree/HEAD/packages#maintaining-changelogs. -->
## Unreleased
## 6.55.0 (2024-05-16)
## 6.54.0 (2024-05-02)
## 6.53.0 (2024-04-19)
## 6.52.0 (2024-04-03)
## 6.51.0 (2024-03-21)
## 6.50.0 (2024-03-06)
## 6.49.0 (2024-02-21)
## 6.48.0 (2024-02-09)
## 6.47.0 (2024-01-24)
## 6.46.0 (2024-01-10)
## 6.45.0 (2023-12-13)
## 6.44.0 (2023-11-29)
## 6.43.0 (2023-11-16)
## 6.42.0 (2023-11-02)
## 6.41.0 (2023-10-18)
## 6.40.0 (2023-10-05)
## 6.39.0 (2023-09-20)
## 6.38.0 (2023-08-31)
## 6.37.0 (2023-08-16)
## 6.36.0 (2023-08-10)
## 6.35.0 (2023-07-20)
## 6.34.0 (2023-07-05)
## 6.33.0 (2023-06-23)
## 6.32.0 (2023-06-07)
## 6.31.0 (2023-05-24)
## 6.30.0 (2023-05-10)
## 6.29.0 (2023-04-26)
## 6.28.0 (2023-04-12)
## 6.27.0 (2023-03-29)
## 6.26.0 (2023-03-15)
## 6.25.0 (2023-03-01)
## 6.24.0 (2023-02-15)
## 6.23.0 (2023-02-01)
## 6.22.0 (2023-01-11)
## 6.21.0 (2023-01-02)
## 6.20.0 (2022-12-14)
## 6.19.0 (2022-11-16)
## 6.18.0 (2022-11-02)
## 6.17.0 (2022-10-19)
## 6.16.0 (2022-10-05)
## 6.15.0 (2022-09-21)
## 6.14.0 (2022-09-13)
## 6.13.0 (2022-08-24)
## 6.12.0 (2022-08-10)
## 6.11.0 (2022-07-27)
## 6.10.0 (2022-07-13)
## 6.9.0 (2022-06-29)
## 6.8.0 (2022-06-15)
## 6.7.0 (2022-06-01)
## 6.6.0 (2022-05-18)
## 6.5.0 (2022-05-04)
## 6.4.0 (2022-04-21)
## 6.3.0 (2022-04-08)
## 6.2.0 (2022-03-23)
## 6.1.0 (2022-03-11)
## 6.0.0 (2022-01-27)
### Breaking changes
`OPTIONS` requests handled by the preloading middleware are now resolved as `window.Response` objects if you explicitly set `parse: false` (for consistency with how GET requests are resolved). They used to be resolved as `Plain Old JavaScript Objects`.
## 5.2.5 (2021-11-07)
### Internal
- Removed `getStablePath` function. Please use `normalizePath` from `@wordpress/url` package instead ([#35992](https://github.com/WordPress/gutenberg/pull/35992)).``
## 5.2.0 (2021-07-21)
### New feature
- `AbortError` being thrown by the default fetch handler can now be caught and handled separately in user-land. Add documentation about aborting a request ([#32530](https://github.com/WordPress/gutenberg/pull/32530)).
## 5.1.0 (2021-05-20)
## 5.0.0 (2021-05-14)
### Breaking Changes
- Drop support for Internet Explorer 11 ([#31110](https://github.com/WordPress/gutenberg/pull/31110)). Learn more at https://make.wordpress.org/core/2021/04/22/ie-11-support-phase-out-plan/.
- Increase the minimum Node.js version to v12 matching Long Term Support releases ([#31270](https://github.com/WordPress/gutenberg/pull/31270)). Learn more at https://nodejs.org/en/about/releases/.
## 4.0.0 (2021-04-29)
### Breaking Changes
- `OPTIONS` requests which are handled by the preloading middleware are no longer resolved as unparsed responses unless you explicitly set `parse: false`, for consistency with other request methods. If you expect an unparsed response, add `{ parse: false }` to your request options to preserve the previous behavior.
## 3.23.1 (2021-04-15)
### Bug Fixes
- Align exported type names with the DefinitelyTyped type names and actually export those types.
## 3.23.0 (2021-04-06)
### New Feature
- Publish TypeScript definitions.
## 3.22.0 (2021-03-17)
## 3.8.1 (2019-04-22)
- Added deprecation to `useApiFetch` hook.
- Added `@wordpress/deprecation` package to add deprecation notice to `useApiFetch` hook.
## 3.8.0 (2019-12-19)
### Bug Fixes
- Resolves an issue with `createPreloadingMiddleware` where the preloaded data is assumed to be provided with keys matching the internal normalized value.
## 3.0.0 (2019-03-06)
### Breaking Changes
- A created nonce middleware will no longer automatically listen for `heartbeat.tick` actions. Assign to the new `nonce` middleware property instead.
### New Feature
- The function returned by `createNonceMiddleware` includes an assignable `nonce` property corresponding to the active nonce to be used.
- Default fetch handler can be overridden with a custom fetch handler
## 2.2.6 (2018-12-12)
## 2.2.5 (2018-11-20)
## 2.2.4 (2018-11-15)
## 2.2.3 (2018-11-12)
## 2.2.2 (2018-11-03)
## 2.2.1 (2018-10-30)
## 2.2.0 (2018-10-29)
### New Feature
- Always request data in the user's locale ([#10862](https://github.com/WordPress/gutenberg/pull/10862)).
## 2.1.0 (2018-10-22)
### New Feature
- Support `per_page=-1` paginated requests.
## 2.0.0 (2018-09-05)
### Breaking Change
- Change how required built-ins are polyfilled with Babel 7 ([#9171](https://github.com/WordPress/gutenberg/pull/9171)). If you're using an environment that has limited or no support for ES2015+ such as lower versions of IE then using [core-js](https://github.com/zloirock/core-js) or [@babel/polyfill](https://babeljs.io/docs/en/next/babel-polyfill) will add support for these methods.

788
node_modules/@wordpress/api-fetch/LICENSE.md generated vendored Normal file
View File

@@ -0,0 +1,788 @@
## Gutenberg
Copyright 2016-2024 by the contributors
**License for Contributions (on and after April 15, 2021)**
All code contributed to the Gutenberg project is dual-licensed,
and released under both of the following licenses:
the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the “GPL”)
and the Mozilla Public License, Version 2.0 (the “MPL”).
**Project License**
The Gutenberg project license is not affected by the License for Contributions (as
discussed in the [Dual License section](#dual-license) below). The Gutenberg project
continues to be free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the Free
Software Foundation; either version 2 of the License or (at your option) any
later version (the “GPL”).
This program incorporates work covered by the following copyright and
permission notices:
b2 is (c) 2001, 2002 Michel Valdrighi - m@tidakada.com -
http://tidakada.com
Wherever third party code has been used, credit has been given in the code's
comments.
b2 is released under the GPL
and
WordPress - Web publishing software
Copyright 2003-2010 by the contributors
WordPress is released under the GPL
### Dual License
**We are currently in the process of changing Gutenbergs software license from
GPL to a dual license: GPL and MPL.**
**This process involves two independent steps (1) obtaining permission for dual
licensing from contributors of already contributed Gutenberg code and (2)
dual licensing of all contributions to Gutenberg that are made on or after
April 15, 2021.**
**For part (1): Were reaching out to everyone who has contributed code, prior
to April 15, 2021, and asking that they agree to dual license their
contribution to the project. We expect this process to be completed by
mid-year, 2021.**
**For part (2): We have changed the license for contributed code to this
repository to make clear that all contributions on or after April 15, 2021
will be made under the dual-license.**
**When we have received all necessary rights and permissions to dual license
the pre-April 15, 2021 code of the Gutenberg project (Part 1 above), you will
have the option to use and distribute all of the Gutenberg project under
either the GPL or MPL license. At this time we will change the “Project
License” to the following:**
The Gutenberg project is free software; you can redistribute it and/or modify
it under the terms of either of the following licenses:
1. the GNU General Public License as published by the Free Software Foundation;
either version 2 of the License or (at your option) any later version (the
“GPL”) OR
2. the Mozilla Public License Version 2.0 (the “MPL”).
---
## Full Text of Referenced Licenses
1. [GNU General Public License, Version 2](#gnu-general-public-license-version-2)
2. [Mozilla Public License, Version 2.0](#mozilla-public-license-version-20)
## GNU General Public License, Version 2
### GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
### Preamble
The licenses for most software are designed to take away your freedom
to share and change it. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if
you distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on,
we want its recipients to know that what they have is not the
original, so that any problems introduced by others will not reflect
on the original authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at
all.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
**0.** This License applies to any program or other work which
contains a notice placed by the copyright holder saying it may be
distributed under the terms of this General Public License. The
"Program", below, refers to any such program or work, and a "work
based on the Program" means either the Program or any derivative work
under copyright law: that is to say, a work containing the Program or
a portion of it, either verbatim or with modifications and/or
translated into another language. (Hereinafter, translation is
included without limitation in the term "modification".) Each licensee
is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the Program
(independent of having been made by running the Program). Whether that
is true depends on what the Program does.
**1.** You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a
fee.
**2.** You may modify your copy or copies of the Program or any
portion of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
**a)** You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
**b)** You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any part
thereof, to be licensed as a whole at no charge to all third parties
under the terms of this License.
**c)** If the modified program normally reads commands interactively
when run, you must cause it, when started running for such interactive
use in the most ordinary way, to print or display an announcement
including an appropriate copyright notice and a notice that there is
no warranty (or else, saying that you provide a warranty) and that
users may redistribute the program under these conditions, and telling
the user how to view a copy of this License. (Exception: if the
Program itself is interactive but does not normally print such an
announcement, your work based on the Program is not required to print
an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
**3.** You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
**a)** Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections 1
and 2 above on a medium customarily used for software interchange; or,
**b)** Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your cost of
physically performing source distribution, a complete machine-readable
copy of the corresponding source code, to be distributed under the
terms of Sections 1 and 2 above on a medium customarily used for
software interchange; or,
**c)** Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is allowed
only for noncommercial distribution and only if you received the
program in object code or executable form with such an offer, in
accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
**4.** You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt otherwise
to copy, modify, sublicense or distribute the Program is void, and
will automatically terminate your rights under this License. However,
parties who have received copies, or rights, from you under this
License will not have their licenses terminated so long as such
parties remain in full compliance.
**5.** You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
**6.** Each time you redistribute the Program (or any work based on
the Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
**7.** If, as a consequence of a court judgment or allegation of
patent infringement or for any other reason (not limited to patent
issues), conditions are imposed on you (whether by court order,
agreement or otherwise) that contradict the conditions of this
License, they do not excuse you from the conditions of this License.
If you cannot distribute so as to satisfy simultaneously your
obligations under this License and any other pertinent obligations,
then as a consequence you may not distribute the Program at all. For
example, if a patent license would not permit royalty-free
redistribution of the Program by all those who receive copies directly
or indirectly through you, then the only way you could satisfy both it
and this License would be to refrain entirely from distribution of the
Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
**8.** If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
**9.** The Free Software Foundation may publish revised and/or new
versions of the General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Program does not specify a
version number of this License, you may choose any version ever
published by the Free Software Foundation.
**10.** If you wish to incorporate parts of the Program into other
free programs whose distribution conditions are different, write to
the author to ask for permission. For software which is copyrighted by
the Free Software Foundation, write to the Free Software Foundation;
we sometimes make exceptions for this. Our decision will be guided by
the two goals of preserving the free status of all derivatives of our
free software and of promoting the sharing and reuse of software
generally.
**NO WARRANTY**
**11.** BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
**12.** IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
### END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
one line to give the program's name and an idea of what it does.
Copyright (C) yyyy name of author
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
Also add information on how to contact you by electronic and paper
mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details
type `show w'. This is free software, and you are welcome
to redistribute it under certain conditions; type `show c'
for details.
The hypothetical commands \`show w' and \`show c' should show the
appropriate parts of the General Public License. Of course, the
commands you use may be called something other than \`show w' and
\`show c'; they could even be mouse-clicks or menu items--whatever
suits your program.
You should also get your employer (if you work as a programmer) or
your school, if any, to sign a "copyright disclaimer" for the program,
if necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright
interest in the program `Gnomovision'
(which makes passes at compilers) written
by James Hacker.
signature of Ty Coon, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library,
you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use the
[GNU Lesser General Public
License](http://www.gnu.org/licenses/lgpl.html) instead of this
License.
---
## Mozilla Public License, Version 2.0
### 1. Definitions
**1.1. “Contributor”**
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
**1.2. “Contributor Version”**
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
**1.3. “Contribution”**
means Covered Software of a particular Contributor.
**1.4. “Covered Software”**
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
**1.5. “Incompatible With Secondary Licenses”**
means
- **(a)** that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
- **(b)** that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
**1.6. “Executable Form”**
means any form of the work other than Source Code Form.
**1.7. “Larger Work”**
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
**1.8. “License”**
means this document.
**1.9. “Licensable”**
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
**1.10. “Modifications”**
means any of the following:
- **(a)** any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
- **(b)** any new file in Source Code Form that contains any Covered
Software.
**1.11. “Patent Claims” of a Contributor**
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
**1.12. “Secondary License”**
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
**1.13. “Source Code Form”**
means the form of the work preferred for making modifications.
**1.14. “You” (or “Your”)**
means an individual or a legal entity exercising rights under this
License. For legal entities, “You” includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, “control” means **(a)** the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or **(b)** ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
### 2. License Grants and Conditions
#### 2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
- **(a)** under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
- **(b)** under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
#### 2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
#### 2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
- **(a)** for any code that a Contributor has removed from Covered Software;
or
- **(b)** for infringements caused by: **(i)** Your and any other third party's
modifications of Covered Software, or **(ii)** the combination of its
Contributions with other software (except as part of its Contributor
Version); or
- **(c)** under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
#### 2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
#### 2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
#### 2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
#### 2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
### 3. Responsibilities
#### 3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
#### 3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
- **(a)** such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
- **(b)** You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
#### 3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
#### 3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
#### 3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
### 4. Inability to Comply Due to Statute or Regulation
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: **(a)** comply with
the terms of this License to the maximum extent possible; and **(b)**
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
### 5. Termination
**5.1.** The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated **(a)** provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and **(b)** on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
**5.2.** If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
**5.3.** In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
### 6. Disclaimer of Warranty
> Covered Software is provided under this License on an “as is”
> basis, without warranty of any kind, either expressed, implied, or
> statutory, including, without limitation, warranties that the
> Covered Software is free of defects, merchantable, fit for a
> particular purpose or non-infringing. The entire risk as to the
> quality and performance of the Covered Software is with You.
> Should any Covered Software prove defective in any respect, You
> (not any Contributor) assume the cost of any necessary servicing,
> repair, or correction. This disclaimer of warranty constitutes an
> essential part of this License. No use of any Covered Software is
> authorized under this License except under this disclaimer.
### 7. Limitation of Liability
> Under no circumstances and under no legal theory, whether tort
> (including negligence), contract, or otherwise, shall any
> Contributor, or anyone who distributes Covered Software as
> permitted above, be liable to You for any direct, indirect,
> special, incidental, or consequential damages of any character
> including, without limitation, damages for lost profits, loss of
> goodwill, work stoppage, computer failure or malfunction, or any
> and all other commercial damages or losses, even if such party
> shall have been informed of the possibility of such damages. This
> limitation of liability shall not apply to liability for death or
> personal injury resulting from such party's negligence to the
> extent applicable law prohibits such limitation. Some
> jurisdictions do not allow the exclusion or limitation of
> incidental or consequential damages, so this exclusion and
> limitation may not apply to You.
### 8. Litigation
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
### 9. Miscellaneous
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
### 10. Versions of the License
#### 10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
#### 10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
#### 10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
#### 10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
## Exhibit A - Source Code Form License Notice
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
## Exhibit B - “Incompatible With Secondary Licenses” Notice
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

171
node_modules/@wordpress/api-fetch/README.md generated vendored Normal file
View File

@@ -0,0 +1,171 @@
# API Fetch
Utility to make WordPress REST API requests. It's a wrapper around `window.fetch`.
## Installation
Install the module
```bash
npm install @wordpress/api-fetch --save
```
_This package assumes that your code will run in an **ES2015+** environment. If you're using an environment that has limited or no support for such language features and APIs, you should include [the polyfill shipped in `@wordpress/babel-preset-default`](https://github.com/WordPress/gutenberg/tree/HEAD/packages/babel-preset-default#polyfill) in your code._
## Usage
### GET
```js
import apiFetch from '@wordpress/api-fetch';
apiFetch( { path: '/wp/v2/posts' } ).then( ( posts ) => {
console.log( posts );
} );
```
### GET with Query Args
```js
import apiFetch from '@wordpress/api-fetch';
import { addQueryArgs } from '@wordpress/url';
const queryParams = { include: [1,2,3] }; // Return posts with ID = 1,2,3.
apiFetch( { path: addQueryArgs( '/wp/v2/posts', queryParams ) } ).then( ( posts ) => {
console.log( posts );
} );
```
### POST
```js
apiFetch( {
path: '/wp/v2/posts/1',
method: 'POST',
data: { title: 'New Post Title' },
} ).then( ( res ) => {
console.log( res );
} );
```
### Options
`apiFetch` supports and passes through all [options of the `fetch` global](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch).
Additionally, the following options are available:
#### `path` (`string`)
Shorthand to be used in place of `url`, appended to the REST API root URL for the current site.
#### `url` (`string`)
Absolute URL to the endpoint from which to fetch.
#### `parse` (`boolean`, default `true`)
Unlike `fetch`, the `Promise` return value of `apiFetch` will resolve to the parsed JSON result. Disable this behavior by passing `parse` as `false`.
#### `data` (`object`)
Sent on `POST` or `PUT` requests only. Shorthand to be used in place of `body`, accepts an object value to be stringified to JSON.
### Aborting a request
Aborting a request can be achieved through the use of [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) in the same way as you would when using the native `fetch` API.
For legacy browsers that don't support `AbortController`, you can either:
- Provide your own polyfill of `AbortController` if you still want it to be abortable.
- Ignore it as shown in the example below.
**Example**
```js
const controller =
typeof AbortController === 'undefined' ? undefined : new AbortController();
apiFetch( { path: '/wp/v2/posts', signal: controller?.signal } ).catch(
( error ) => {
// If the browser doesn't support AbortController then the code below will never log.
// However, in most cases this should be fine as it can be considered to be a progressive enhancement.
if ( error.name === 'AbortError' ) {
console.log( 'Request has been aborted' );
}
}
);
controller?.abort();
```
### Middlewares
the `api-fetch` package supports middlewares. Middlewares are functions you can use to wrap the `apiFetch` calls to perform any pre/post process to the API requests.
**Example**
```js
import apiFetch from '@wordpress/api-fetch';
apiFetch.use( ( options, next ) => {
const start = Date.now();
const result = next( options );
result.then( () => {
console.log( 'The request took ' + ( Date.now() - start ) + 'ms' );
} );
return result;
} );
```
### Built-in middlewares
The `api-fetch` package provides built-in middlewares you can use to provide a `nonce` and a custom `rootURL`.
**Nonce middleware**
```js
import apiFetch from '@wordpress/api-fetch';
const nonce = 'nonce value';
apiFetch.use( apiFetch.createNonceMiddleware( nonce ) );
```
The function returned by `createNonceMiddleware` includes a `nonce` property corresponding to the actively used nonce. You may also assign to this property if you have a fresh nonce value to use.
**Root URL middleware**
```js
import apiFetch from '@wordpress/api-fetch';
const rootURL = 'http://my-wordpress-site/wp-json/';
apiFetch.use( apiFetch.createRootURLMiddleware( rootURL ) );
```
### Custom fetch handler
The `api-fetch` package uses `window.fetch` for making the requests but you can use a custom fetch handler by using the `setFetchHandler` method. The custom fetch handler will receive the `options` passed to the `apiFetch` calls.
**Example**
The example below uses a custom fetch handler for making all the requests with [`axios`](https://github.com/axios/axios).
```js
import apiFetch from '@wordpress/api-fetch';
import axios from 'axios';
apiFetch.setFetchHandler( ( options ) => {
const { url, path, data, method } = options;
return axios( {
url: url || path,
method,
data,
} );
} );
```
## Contributing to this package
This is an individual package that's part of the Gutenberg project. The project is organized as a monorepo. It's made up of multiple self-contained software packages, each with a specific purpose. The packages in this monorepo are published to [npm](https://www.npmjs.com/) and used by [WordPress](https://make.wordpress.org/core/) as well as other software projects.
To find out more about contributing to this package or Gutenberg as a whole, please read the project's main [contributor guide](https://github.com/WordPress/gutenberg/tree/HEAD/CONTRIBUTING.md).
<br /><br /><p align="center"><img src="https://s.w.org/style/images/codeispoetry.png?1" alt="Code is Poetry." /></p>

178
node_modules/@wordpress/api-fetch/build-module/index.js generated vendored Normal file
View File

@@ -0,0 +1,178 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import createNonceMiddleware from './middlewares/nonce';
import createRootURLMiddleware from './middlewares/root-url';
import createPreloadingMiddleware from './middlewares/preloading';
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import namespaceEndpointMiddleware from './middlewares/namespace-endpoint';
import httpV1Middleware from './middlewares/http-v1';
import userLocaleMiddleware from './middlewares/user-locale';
import mediaUploadMiddleware from './middlewares/media-upload';
import createThemePreviewMiddleware from './middlewares/theme-preview';
import { parseResponseAndNormalizeError, parseAndThrowError } from './utils/response';
/**
* Default set of header values which should be sent with every request unless
* explicitly provided through apiFetch options.
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
//
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1'
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include'
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [userLocaleMiddleware, namespaceEndpointMiddleware, httpV1Middleware, fetchAllMiddleware];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware(middleware) {
middlewares.unshift(middleware);
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
*
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = nextOptions => {
const {
url,
path,
data,
parse = true,
...remainingOptions
} = nextOptions;
let {
body,
headers
} = nextOptions;
// Merge explicitly-provided headers with default values.
headers = {
...DEFAULT_HEADERS,
...headers
};
// The `data` property is a shorthand for sending a JSON body.
if (data) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
const responsePromise = window.fetch(
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href, {
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers
});
return responsePromise.then(value => Promise.resolve(value).then(checkStatus).catch(response => parseAndThrowError(response, parse)).then(response => parseResponseAndNormalizeError(response, parse)), err => {
// Re-throw AbortError for the users to handle it themselves.
if (err && err.name === 'AbortError') {
throw err;
}
// Otherwise, there is most likely no network connection.
// Unfortunately the message might depend on the browser.
throw {
code: 'fetch_error',
message: __('You are probably offline.')
};
});
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler(newFetchHandler) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch(options) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
return workingOptions => middleware(workingOptions, next);
}, fetchHandler);
return enhancedHandler(options).catch(error => {
if (error.code !== 'rest_cookie_invalid_nonce') {
return Promise.reject(error);
}
// If the nonce is invalid, refresh it and try again.
return window
// @ts-ignore
.fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
return apiFetch(options);
});
});
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = createNonceMiddleware;
apiFetch.createPreloadingMiddleware = createPreloadingMiddleware;
apiFetch.createRootURLMiddleware = createRootURLMiddleware;
apiFetch.fetchAllMiddleware = fetchAllMiddleware;
apiFetch.mediaUploadMiddleware = mediaUploadMiddleware;
apiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;
export default apiFetch;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,125 @@
/**
* WordPress dependencies
*/
import { addQueryArgs } from '@wordpress/url';
/**
* Internal dependencies
*/
import apiFetch from '..';
/**
* Apply query arguments to both URL and Path, whichever is present.
*
* @param {import('../types').APIFetchOptions} props
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ({
path,
url,
...options
}, queryArgs) => ({
...options,
url: url && addQueryArgs(url, queryArgs),
path: path && addQueryArgs(path, queryArgs)
});
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = linkHeader => {
if (!linkHeader) {
return {};
}
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
return match ? {
next: match[1]
} : {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = response => {
const {
next
} = parseLinkHeader(response.headers.get('link'));
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = options => {
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async (options, next) => {
if (options.parse === false) {
// If a consumer has opted out of parsing, do not apply middleware.
return next(options);
}
if (!requestContainsUnboundedQuery(options)) {
// If neither url nor path is requesting all items, do not apply middleware.
return next(options);
}
// Retrieve requested page of results.
const response = await apiFetch({
...modifyQuery(options, {
per_page: 100
}),
// Ensure headers are returned for page 1.
parse: false
});
const results = await parseResponse(response);
if (!Array.isArray(results)) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl(response);
if (!nextPage) {
// There are no further pages to request.
return results;
}
// Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults = /** @type {any[]} */[].concat(results);
while (nextPage) {
const nextResponse = await apiFetch({
...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
// Ensure we still get headers so we can identify the next page.
parse: false
});
const nextResults = await parseResponse(nextResponse);
mergedResults = mergedResults.concat(nextResults);
nextPage = getNextPageUrl(nextResponse);
}
return mergedResults;
};
export default fetchAllMiddleware;
//# sourceMappingURL=fetch-all-middleware.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,44 @@
/**
* Set of HTTP methods which are eligible to be overridden.
*
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
/**
* Default request method.
*
* "A request has an associated method (a method). Unless stated otherwise it
* is `GET`."
*
* @see https://fetch.spec.whatwg.org/#requests
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = (options, next) => {
const {
method = DEFAULT_METHOD
} = options;
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
options = {
...options,
headers: {
...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json'
},
method: 'POST'
};
}
return next(options);
};
export default httpV1Middleware;
//# sourceMappingURL=http-v1.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers"],"sources":["@wordpress/api-fetch/src/middlewares/http-v1.js"],"sourcesContent":["/**\n * Set of HTTP methods which are eligible to be overridden.\n *\n * @type {Set<string>}\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n *\n * @type {string}\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst httpV1Middleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAG,IAAIC,GAAG,CAAE,CAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAG,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,cAAc,GAAG,KAAK;;AAE5B;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC7C,MAAM;IAAEC,MAAM,GAAGJ;EAAe,CAAC,GAAGE,OAAO;EAC3C,IAAKJ,gBAAgB,CAACO,GAAG,CAAED,MAAM,CAACE,WAAW,CAAC,CAAE,CAAC,EAAG;IACnDJ,OAAO,GAAG;MACT,GAAGA,OAAO;MACVK,OAAO,EAAE;QACR,GAAGL,OAAO,CAACK,OAAO;QAClB,wBAAwB,EAAEH,MAAM;QAChC,cAAc,EAAE;MACjB,CAAC;MACDA,MAAM,EAAE;IACT,CAAC;EACF;EAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAED,eAAeD,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,77 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import { parseAndThrowError, parseResponseAndNormalizeError } from '../utils/response';
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest(options) {
const isCreateMethod = !!options.method && options.method === 'POST';
const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
return isMediaEndpoint && isCreateMethod;
}
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = (options, next) => {
if (!isMediaUploadRequest(options)) {
return next(options);
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = attachmentId => {
retries++;
return next({
path: `/wp/v2/media/${attachmentId}/post-process`,
method: 'POST',
data: {
action: 'create-image-subsizes'
},
parse: false
}).catch(() => {
if (retries < maxRetries) {
return postProcess(attachmentId);
}
next({
path: `/wp/v2/media/${attachmentId}?force=true`,
method: 'DELETE'
});
return Promise.reject();
});
};
return next({
...options,
parse: false
}).catch(response => {
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
if (options.parse !== false) {
return Promise.reject({
code: 'post_process',
message: __('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
});
}
return Promise.reject(response);
});
}
return parseAndThrowError(response, options.parse);
}).then(response => parseResponseAndNormalizeError(response, options.parse));
};
export default mediaUploadMiddleware;
//# sourceMappingURL=media-upload.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["__","parseAndThrowError","parseResponseAndNormalizeError","isMediaUploadRequest","options","isCreateMethod","method","isMediaEndpoint","path","indexOf","url","mediaUploadMiddleware","next","retries","maxRetries","postProcess","attachmentId","data","action","parse","catch","Promise","reject","response","headers","get","status","code","message","then"],"sources":["@wordpress/api-fetch/src/middlewares/media-upload.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Internal dependencies\n */\nimport {\n\tparseAndThrowError,\n\tparseResponseAndNormalizeError,\n} from '../utils/response';\n\n/**\n * @param {import('../types').APIFetchOptions} options\n * @return {boolean} True if the request is for media upload.\n */\nfunction isMediaUploadRequest( options ) {\n\tconst isCreateMethod = !! options.method && options.method === 'POST';\n\tconst isMediaEndpoint =\n\t\t( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||\n\t\t( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );\n\n\treturn isMediaEndpoint && isCreateMethod;\n}\n\n/**\n * Middleware handling media upload failures and retries.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst mediaUploadMiddleware = ( options, next ) => {\n\tif ( ! isMediaUploadRequest( options ) ) {\n\t\treturn next( options );\n\t}\n\n\tlet retries = 0;\n\tconst maxRetries = 5;\n\n\t/**\n\t * @param {string} attachmentId\n\t * @return {Promise<any>} Processed post response.\n\t */\n\tconst postProcess = ( attachmentId ) => {\n\t\tretries++;\n\t\treturn next( {\n\t\t\tpath: `/wp/v2/media/${ attachmentId }/post-process`,\n\t\t\tmethod: 'POST',\n\t\t\tdata: { action: 'create-image-subsizes' },\n\t\t\tparse: false,\n\t\t} ).catch( () => {\n\t\t\tif ( retries < maxRetries ) {\n\t\t\t\treturn postProcess( attachmentId );\n\t\t\t}\n\t\t\tnext( {\n\t\t\t\tpath: `/wp/v2/media/${ attachmentId }?force=true`,\n\t\t\t\tmethod: 'DELETE',\n\t\t\t} );\n\n\t\t\treturn Promise.reject();\n\t\t} );\n\t};\n\n\treturn next( { ...options, parse: false } )\n\t\t.catch( ( response ) => {\n\t\t\tconst attachmentId = response.headers.get(\n\t\t\t\t'x-wp-upload-attachment-id'\n\t\t\t);\n\t\t\tif (\n\t\t\t\tresponse.status >= 500 &&\n\t\t\t\tresponse.status < 600 &&\n\t\t\t\tattachmentId\n\t\t\t) {\n\t\t\t\treturn postProcess( attachmentId ).catch( () => {\n\t\t\t\t\tif ( options.parse !== false ) {\n\t\t\t\t\t\treturn Promise.reject( {\n\t\t\t\t\t\t\tcode: 'post_process',\n\t\t\t\t\t\t\tmessage: __(\n\t\t\t\t\t\t\t\t'Media upload failed. If this is a photo or a large image, please scale it down and try again.'\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t} );\n\t\t\t\t\t}\n\n\t\t\t\t\treturn Promise.reject( response );\n\t\t\t\t} );\n\t\t\t}\n\t\t\treturn parseAndThrowError( response, options.parse );\n\t\t} )\n\t\t.then( ( response ) =>\n\t\t\tparseResponseAndNormalizeError( response, options.parse )\n\t\t);\n};\n\nexport default mediaUploadMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAE,QAAQ,iBAAiB;;AAEpC;AACA;AACA;AACA,SACCC,kBAAkB,EAClBC,8BAA8B,QACxB,mBAAmB;;AAE1B;AACA;AACA;AACA;AACA,SAASC,oBAAoBA,CAAEC,OAAO,EAAG;EACxC,MAAMC,cAAc,GAAG,CAAC,CAAED,OAAO,CAACE,MAAM,IAAIF,OAAO,CAACE,MAAM,KAAK,MAAM;EACrE,MAAMC,eAAe,GAClB,CAAC,CAAEH,OAAO,CAACI,IAAI,IAAIJ,OAAO,CAACI,IAAI,CAACC,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAC,IAChE,CAAC,CAAEL,OAAO,CAACM,GAAG,IAAIN,OAAO,CAACM,GAAG,CAACD,OAAO,CAAE,cAAe,CAAC,KAAK,CAAC,CAAG;EAEnE,OAAOF,eAAe,IAAIF,cAAc;AACzC;;AAEA;AACA;AACA;AACA;AACA;AACA,MAAMM,qBAAqB,GAAGA,CAAEP,OAAO,EAAEQ,IAAI,KAAM;EAClD,IAAK,CAAET,oBAAoB,CAAEC,OAAQ,CAAC,EAAG;IACxC,OAAOQ,IAAI,CAAER,OAAQ,CAAC;EACvB;EAEA,IAAIS,OAAO,GAAG,CAAC;EACf,MAAMC,UAAU,GAAG,CAAC;;EAEpB;AACD;AACA;AACA;EACC,MAAMC,WAAW,GAAKC,YAAY,IAAM;IACvCH,OAAO,EAAE;IACT,OAAOD,IAAI,CAAE;MACZJ,IAAI,EAAG,gBAAgBQ,YAAc,eAAc;MACnDV,MAAM,EAAE,MAAM;MACdW,IAAI,EAAE;QAAEC,MAAM,EAAE;MAAwB,CAAC;MACzCC,KAAK,EAAE;IACR,CAAE,CAAC,CAACC,KAAK,CAAE,MAAM;MAChB,IAAKP,OAAO,GAAGC,UAAU,EAAG;QAC3B,OAAOC,WAAW,CAAEC,YAAa,CAAC;MACnC;MACAJ,IAAI,CAAE;QACLJ,IAAI,EAAG,gBAAgBQ,YAAc,aAAY;QACjDV,MAAM,EAAE;MACT,CAAE,CAAC;MAEH,OAAOe,OAAO,CAACC,MAAM,CAAC,CAAC;IACxB,CAAE,CAAC;EACJ,CAAC;EAED,OAAOV,IAAI,CAAE;IAAE,GAAGR,OAAO;IAAEe,KAAK,EAAE;EAAM,CAAE,CAAC,CACzCC,KAAK,CAAIG,QAAQ,IAAM;IACvB,MAAMP,YAAY,GAAGO,QAAQ,CAACC,OAAO,CAACC,GAAG,CACxC,2BACD,CAAC;IACD,IACCF,QAAQ,CAACG,MAAM,IAAI,GAAG,IACtBH,QAAQ,CAACG,MAAM,GAAG,GAAG,IACrBV,YAAY,EACX;MACD,OAAOD,WAAW,CAAEC,YAAa,CAAC,CAACI,KAAK,CAAE,MAAM;QAC/C,IAAKhB,OAAO,CAACe,KAAK,KAAK,KAAK,EAAG;UAC9B,OAAOE,OAAO,CAACC,MAAM,CAAE;YACtBK,IAAI,EAAE,cAAc;YACpBC,OAAO,EAAE5B,EAAE,CACV,+FACD;UACD,CAAE,CAAC;QACJ;QAEA,OAAOqB,OAAO,CAACC,MAAM,CAAEC,QAAS,CAAC;MAClC,CAAE,CAAC;IACJ;IACA,OAAOtB,kBAAkB,CAAEsB,QAAQ,EAAEnB,OAAO,CAACe,KAAM,CAAC;EACrD,CAAE,CAAC,CACFU,IAAI,CAAIN,QAAQ,IAChBrB,8BAA8B,CAAEqB,QAAQ,EAAEnB,OAAO,CAACe,KAAM,CACzD,CAAC;AACH,CAAC;AAED,eAAeR,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,24 @@
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = (options, next) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
endpointTrimmed = options.endpoint.replace(/^\//, '');
if (endpointTrimmed) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next({
...options,
path
});
};
export default namespaceAndEndpointMiddleware;
//# sourceMappingURL=namespace-endpoint.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["namespaceAndEndpointMiddleware","options","next","path","namespaceTrimmed","endpointTrimmed","namespace","endpoint","replace"],"sources":["@wordpress/api-fetch/src/middlewares/namespace-endpoint.js"],"sourcesContent":["/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst namespaceAndEndpointMiddleware = ( options, next ) => {\n\tlet path = options.path;\n\tlet namespaceTrimmed, endpointTrimmed;\n\n\tif (\n\t\ttypeof options.namespace === 'string' &&\n\t\ttypeof options.endpoint === 'string'\n\t) {\n\t\tnamespaceTrimmed = options.namespace.replace( /^\\/|\\/$/g, '' );\n\t\tendpointTrimmed = options.endpoint.replace( /^\\//, '' );\n\t\tif ( endpointTrimmed ) {\n\t\t\tpath = namespaceTrimmed + '/' + endpointTrimmed;\n\t\t} else {\n\t\t\tpath = namespaceTrimmed;\n\t\t}\n\t}\n\n\tdelete options.namespace;\n\tdelete options.endpoint;\n\n\treturn next( {\n\t\t...options,\n\t\tpath,\n\t} );\n};\n\nexport default namespaceAndEndpointMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,MAAMA,8BAA8B,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC3D,IAAIC,IAAI,GAAGF,OAAO,CAACE,IAAI;EACvB,IAAIC,gBAAgB,EAAEC,eAAe;EAErC,IACC,OAAOJ,OAAO,CAACK,SAAS,KAAK,QAAQ,IACrC,OAAOL,OAAO,CAACM,QAAQ,KAAK,QAAQ,EACnC;IACDH,gBAAgB,GAAGH,OAAO,CAACK,SAAS,CAACE,OAAO,CAAE,UAAU,EAAE,EAAG,CAAC;IAC9DH,eAAe,GAAGJ,OAAO,CAACM,QAAQ,CAACC,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;IACvD,IAAKH,eAAe,EAAG;MACtBF,IAAI,GAAGC,gBAAgB,GAAG,GAAG,GAAGC,eAAe;IAChD,CAAC,MAAM;MACNF,IAAI,GAAGC,gBAAgB;IACxB;EACD;EAEA,OAAOH,OAAO,CAACK,SAAS;EACxB,OAAOL,OAAO,CAACM,QAAQ;EAEvB,OAAOL,IAAI,CAAE;IACZ,GAAGD,OAAO;IACVE;EACD,CAAE,CAAC;AACJ,CAAC;AAED,eAAeH,8BAA8B","ignoreList":[]}

View File

@@ -0,0 +1,33 @@
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware(nonce) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
const middleware = (options, next) => {
const {
headers = {}
} = options;
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for (const headerName in headers) {
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
return next(options);
}
}
return next({
...options,
headers: {
...headers,
'X-WP-Nonce': middleware.nonce
}
});
};
middleware.nonce = nonce;
return middleware;
}
export default createNonceMiddleware;
//# sourceMappingURL=nonce.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createNonceMiddleware","nonce","middleware","options","next","headers","headerName","toLowerCase"],"sources":["@wordpress/api-fetch/src/middlewares/nonce.js"],"sourcesContent":["/**\n * @param {string} nonce\n * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.\n */\nfunction createNonceMiddleware( nonce ) {\n\t/**\n\t * @type {import('../types').APIFetchMiddleware & { nonce: string }}\n\t */\n\tconst middleware = ( options, next ) => {\n\t\tconst { headers = {} } = options;\n\n\t\t// If an 'X-WP-Nonce' header (or any case-insensitive variation\n\t\t// thereof) was specified, no need to add a nonce header.\n\t\tfor ( const headerName in headers ) {\n\t\t\tif (\n\t\t\t\theaderName.toLowerCase() === 'x-wp-nonce' &&\n\t\t\t\theaders[ headerName ] === middleware.nonce\n\t\t\t) {\n\t\t\t\treturn next( options );\n\t\t\t}\n\t\t}\n\n\t\treturn next( {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...headers,\n\t\t\t\t'X-WP-Nonce': middleware.nonce,\n\t\t\t},\n\t\t} );\n\t};\n\n\tmiddleware.nonce = nonce;\n\n\treturn middleware;\n}\n\nexport default createNonceMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA;AACA,SAASA,qBAAqBA,CAAEC,KAAK,EAAG;EACvC;AACD;AACA;EACC,MAAMC,UAAU,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;IACvC,MAAM;MAAEC,OAAO,GAAG,CAAC;IAAE,CAAC,GAAGF,OAAO;;IAEhC;IACA;IACA,KAAM,MAAMG,UAAU,IAAID,OAAO,EAAG;MACnC,IACCC,UAAU,CAACC,WAAW,CAAC,CAAC,KAAK,YAAY,IACzCF,OAAO,CAAEC,UAAU,CAAE,KAAKJ,UAAU,CAACD,KAAK,EACzC;QACD,OAAOG,IAAI,CAAED,OAAQ,CAAC;MACvB;IACD;IAEA,OAAOC,IAAI,CAAE;MACZ,GAAGD,OAAO;MACVE,OAAO,EAAE;QACR,GAAGA,OAAO;QACV,YAAY,EAAEH,UAAU,CAACD;MAC1B;IACD,CAAE,CAAC;EACJ,CAAC;EAEDC,UAAU,CAACD,KAAK,GAAGA,KAAK;EAExB,OAAOC,UAAU;AAClB;AAEA,eAAeF,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,64 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware(preloadedData) {
const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [normalizePath(path), data]));
return (options, next) => {
const {
parse = true
} = options;
/** @type {string | void} */
let rawPath = options.path;
if (!rawPath && options.url) {
const {
rest_route: pathFromQuery,
...queryArgs
} = getQueryArgs(options.url);
if (typeof pathFromQuery === 'string') {
rawPath = addQueryArgs(pathFromQuery, queryArgs);
}
}
if (typeof rawPath !== 'string') {
return next(options);
}
const method = options.method || 'GET';
const path = normalizePath(rawPath);
if ('GET' === method && cache[path]) {
const cacheData = cache[path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[path];
return prepareResponse(cacheData, !!parse);
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
const cacheData = cache[method][path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[method][path];
return prepareResponse(cacheData, !!parse);
}
return next(options);
};
}
/**
* This is a helper function that sends a success response.
*
* @param {Record<string, any>} responseData
* @param {boolean} parse
* @return {Promise<any>} Promise with the response.
*/
function prepareResponse(responseData, parse) {
return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
status: 200,
statusText: 'OK',
headers: responseData.headers
}));
}
export default createPreloadingMiddleware;
//# sourceMappingURL=preloading.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["addQueryArgs","getQueryArgs","normalizePath","createPreloadingMiddleware","preloadedData","cache","Object","fromEntries","entries","map","path","data","options","next","parse","rawPath","url","rest_route","pathFromQuery","queryArgs","method","cacheData","prepareResponse","responseData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers"],"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.fromEntries(\n\t\tObject.entries( preloadedData ).map( ( [ path, data ] ) => [\n\t\t\tnormalizePath( path ),\n\t\t\tdata,\n\t\t] )\n\t);\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\t/** @type {string | void} */\n\t\tlet rawPath = options.path;\n\t\tif ( ! rawPath && options.url ) {\n\t\t\tconst { rest_route: pathFromQuery, ...queryArgs } = getQueryArgs(\n\t\t\t\toptions.url\n\t\t\t);\n\n\t\t\tif ( typeof pathFromQuery === 'string' ) {\n\t\t\t\trawPath = addQueryArgs( pathFromQuery, queryArgs );\n\t\t\t}\n\t\t}\n\n\t\tif ( typeof rawPath !== 'string' ) {\n\t\t\treturn next( options );\n\t\t}\n\n\t\tconst method = options.method || 'GET';\n\t\tconst path = normalizePath( rawPath );\n\n\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t} else if (\n\t\t\t'OPTIONS' === method &&\n\t\t\tcache[ method ] &&\n\t\t\tcache[ method ][ path ]\n\t\t) {\n\t\t\tconst cacheData = cache[ method ][ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ method ][ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\n/**\n * This is a helper function that sends a success response.\n *\n * @param {Record<string, any>} responseData\n * @param {boolean} parse\n * @return {Promise<any>} Promise with the response.\n */\nfunction prepareResponse( responseData, parse ) {\n\treturn Promise.resolve(\n\t\tparse\n\t\t\t? responseData.body\n\t\t\t: new window.Response( JSON.stringify( responseData.body ), {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\theaders: responseData.headers,\n\t\t\t } )\n\t);\n}\n\nexport default createPreloadingMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,YAAY,EAAEC,YAAY,EAAEC,aAAa,QAAQ,gBAAgB;;AAE1E;AACA;AACA;AACA;AACA,SAASC,0BAA0BA,CAAEC,aAAa,EAAG;EACpD,MAAMC,KAAK,GAAGC,MAAM,CAACC,WAAW,CAC/BD,MAAM,CAACE,OAAO,CAAEJ,aAAc,CAAC,CAACK,GAAG,CAAE,CAAE,CAAEC,IAAI,EAAEC,IAAI,CAAE,KAAM,CAC1DT,aAAa,CAAEQ,IAAK,CAAC,EACrBC,IAAI,CACH,CACH,CAAC;EAED,OAAO,CAAEC,OAAO,EAAEC,IAAI,KAAM;IAC3B,MAAM;MAAEC,KAAK,GAAG;IAAK,CAAC,GAAGF,OAAO;IAChC;IACA,IAAIG,OAAO,GAAGH,OAAO,CAACF,IAAI;IAC1B,IAAK,CAAEK,OAAO,IAAIH,OAAO,CAACI,GAAG,EAAG;MAC/B,MAAM;QAAEC,UAAU,EAAEC,aAAa;QAAE,GAAGC;MAAU,CAAC,GAAGlB,YAAY,CAC/DW,OAAO,CAACI,GACT,CAAC;MAED,IAAK,OAAOE,aAAa,KAAK,QAAQ,EAAG;QACxCH,OAAO,GAAGf,YAAY,CAAEkB,aAAa,EAAEC,SAAU,CAAC;MACnD;IACD;IAEA,IAAK,OAAOJ,OAAO,KAAK,QAAQ,EAAG;MAClC,OAAOF,IAAI,CAAED,OAAQ,CAAC;IACvB;IAEA,MAAMQ,MAAM,GAAGR,OAAO,CAACQ,MAAM,IAAI,KAAK;IACtC,MAAMV,IAAI,GAAGR,aAAa,CAAEa,OAAQ,CAAC;IAErC,IAAK,KAAK,KAAKK,MAAM,IAAIf,KAAK,CAAEK,IAAI,CAAE,EAAG;MACxC,MAAMW,SAAS,GAAGhB,KAAK,CAAEK,IAAI,CAAE;;MAE/B;MACA,OAAOL,KAAK,CAAEK,IAAI,CAAE;MAEpB,OAAOY,eAAe,CAAED,SAAS,EAAE,CAAC,CAAEP,KAAM,CAAC;IAC9C,CAAC,MAAM,IACN,SAAS,KAAKM,MAAM,IACpBf,KAAK,CAAEe,MAAM,CAAE,IACff,KAAK,CAAEe,MAAM,CAAE,CAAEV,IAAI,CAAE,EACtB;MACD,MAAMW,SAAS,GAAGhB,KAAK,CAAEe,MAAM,CAAE,CAAEV,IAAI,CAAE;;MAEzC;MACA,OAAOL,KAAK,CAAEe,MAAM,CAAE,CAAEV,IAAI,CAAE;MAE9B,OAAOY,eAAe,CAAED,SAAS,EAAE,CAAC,CAAEP,KAAM,CAAC;IAC9C;IAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;EACvB,CAAC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASU,eAAeA,CAAEC,YAAY,EAAET,KAAK,EAAG;EAC/C,OAAOU,OAAO,CAACC,OAAO,CACrBX,KAAK,GACFS,YAAY,CAACG,IAAI,GACjB,IAAIC,MAAM,CAACC,QAAQ,CAAEC,IAAI,CAACC,SAAS,CAAEP,YAAY,CAACG,IAAK,CAAC,EAAE;IAC1DK,MAAM,EAAE,GAAG;IACXC,UAAU,EAAE,IAAI;IAChBC,OAAO,EAAEV,YAAY,CAACU;EACtB,CAAE,CACN,CAAC;AACF;AAEA,eAAe9B,0BAA0B","ignoreList":[]}

View File

@@ -0,0 +1,36 @@
/**
* Internal dependencies
*/
import namespaceAndEndpointMiddleware from './namespace-endpoint';
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = rootURL => (options, next) => {
return namespaceAndEndpointMiddleware(options, optionsWithPath => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if (typeof path === 'string') {
apiRoot = rootURL;
if (-1 !== rootURL.indexOf('?')) {
path = path.replace('?', '&');
}
path = path.replace(/^\//, '');
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
path = path.replace('?', '&');
}
url = apiRoot + path;
}
return next({
...optionsWithPath,
url
});
});
};
export default createRootURLMiddleware;
//# sourceMappingURL=root-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["namespaceAndEndpointMiddleware","createRootURLMiddleware","rootURL","options","next","optionsWithPath","url","path","apiRoot","indexOf","replace"],"sources":["@wordpress/api-fetch/src/middlewares/root-url.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport namespaceAndEndpointMiddleware from './namespace-endpoint';\n\n/**\n * @param {string} rootURL\n * @return {import('../types').APIFetchMiddleware} Root URL middleware.\n */\nconst createRootURLMiddleware = ( rootURL ) => ( options, next ) => {\n\treturn namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {\n\t\tlet url = optionsWithPath.url;\n\t\tlet path = optionsWithPath.path;\n\t\tlet apiRoot;\n\n\t\tif ( typeof path === 'string' ) {\n\t\t\tapiRoot = rootURL;\n\n\t\t\tif ( -1 !== rootURL.indexOf( '?' ) ) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\tpath = path.replace( /^\\//, '' );\n\n\t\t\t// API root may already include query parameter prefix if site is\n\t\t\t// configured to use plain permalinks.\n\t\t\tif (\n\t\t\t\t'string' === typeof apiRoot &&\n\t\t\t\t-1 !== apiRoot.indexOf( '?' )\n\t\t\t) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\turl = apiRoot + path;\n\t\t}\n\n\t\treturn next( {\n\t\t\t...optionsWithPath,\n\t\t\turl,\n\t\t} );\n\t} );\n};\n\nexport default createRootURLMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,OAAOA,8BAA8B,MAAM,sBAAsB;;AAEjE;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAAKC,OAAO,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACnE,OAAOJ,8BAA8B,CAAEG,OAAO,EAAIE,eAAe,IAAM;IACtE,IAAIC,GAAG,GAAGD,eAAe,CAACC,GAAG;IAC7B,IAAIC,IAAI,GAAGF,eAAe,CAACE,IAAI;IAC/B,IAAIC,OAAO;IAEX,IAAK,OAAOD,IAAI,KAAK,QAAQ,EAAG;MAC/BC,OAAO,GAAGN,OAAO;MAEjB,IAAK,CAAC,CAAC,KAAKA,OAAO,CAACO,OAAO,CAAE,GAAI,CAAC,EAAG;QACpCF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAH,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;;MAEhC;MACA;MACA,IACC,QAAQ,KAAK,OAAOF,OAAO,IAC3B,CAAC,CAAC,KAAKA,OAAO,CAACC,OAAO,CAAE,GAAI,CAAC,EAC5B;QACDF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAJ,GAAG,GAAGE,OAAO,GAAGD,IAAI;IACrB;IAEA,OAAOH,IAAI,CAAE;MACZ,GAAGC,eAAe;MAClBC;IACD,CAAE,CAAC;EACJ,CAAE,CAAC;AACJ,CAAC;AAED,eAAeL,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,40 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
*
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
* then bypass this middleware.
*
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = themePath => (options, next) => {
if (typeof options.url === 'string') {
const wpThemePreview = getQueryArg(options.url, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.url = addQueryArgs(options.url, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.url = removeQueryArgs(options.url, 'wp_theme_preview');
}
}
if (typeof options.path === 'string') {
const wpThemePreview = getQueryArg(options.path, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.path = addQueryArgs(options.path, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.path = removeQueryArgs(options.path, 'wp_theme_preview');
}
}
return next(options);
};
export default createThemePreviewMiddleware;
//# sourceMappingURL=theme-preview.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["addQueryArgs","getQueryArg","removeQueryArgs","createThemePreviewMiddleware","themePath","options","next","url","wpThemePreview","undefined","wp_theme_preview","path"],"sources":["@wordpress/api-fetch/src/middlewares/theme-preview.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';\n\n/**\n * This appends a `wp_theme_preview` parameter to the REST API request URL if\n * the admin URL contains a `theme` GET parameter.\n *\n * If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,\n * then bypass this middleware.\n *\n * @param {Record<string, any>} themePath\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nconst createThemePreviewMiddleware = ( themePath ) => ( options, next ) => {\n\tif ( typeof options.url === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.url, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.url = addQueryArgs( options.url, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.url = removeQueryArgs( options.url, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\tif ( typeof options.path === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.path, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.path = addQueryArgs( options.path, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.path = removeQueryArgs( options.path, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\treturn next( options );\n};\n\nexport default createThemePreviewMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,YAAY,EAAEC,WAAW,EAAEC,eAAe,QAAQ,gBAAgB;;AAE3E;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,4BAA4B,GAAKC,SAAS,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC1E,IAAK,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,EAAG;IACtC,MAAMC,cAAc,GAAGP,WAAW,CAAEI,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACrE,IAAKC,cAAc,KAAKC,SAAS,EAAG;MACnCJ,OAAO,CAACE,GAAG,GAAGP,YAAY,CAAEK,OAAO,CAACE,GAAG,EAAE;QACxCG,gBAAgB,EAAEN;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACE,GAAG,GAAGL,eAAe,CAAEG,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACjE;EACD;EAEA,IAAK,OAAOF,OAAO,CAACM,IAAI,KAAK,QAAQ,EAAG;IACvC,MAAMH,cAAc,GAAGP,WAAW,CAAEI,OAAO,CAACM,IAAI,EAAE,kBAAmB,CAAC;IACtE,IAAKH,cAAc,KAAKC,SAAS,EAAG;MACnCJ,OAAO,CAACM,IAAI,GAAGX,YAAY,CAAEK,OAAO,CAACM,IAAI,EAAE;QAC1CD,gBAAgB,EAAEN;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACM,IAAI,GAAGT,eAAe,CAAEG,OAAO,CAACM,IAAI,EAAE,kBAAmB,CAAC;IACnE;EACD;EAEA,OAAOL,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAED,eAAeF,4BAA4B","ignoreList":[]}

View File

@@ -0,0 +1,23 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, hasQueryArg } from '@wordpress/url';
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = (options, next) => {
if (typeof options.url === 'string' && !hasQueryArg(options.url, '_locale')) {
options.url = addQueryArgs(options.url, {
_locale: 'user'
});
}
if (typeof options.path === 'string' && !hasQueryArg(options.path, '_locale')) {
options.path = addQueryArgs(options.path, {
_locale: 'user'
});
}
return next(options);
};
export default userLocaleMiddleware;
//# sourceMappingURL=user-locale.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["addQueryArgs","hasQueryArg","userLocaleMiddleware","options","next","url","_locale","path"],"sources":["@wordpress/api-fetch/src/middlewares/user-locale.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, hasQueryArg } from '@wordpress/url';\n\n/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst userLocaleMiddleware = ( options, next ) => {\n\tif (\n\t\ttypeof options.url === 'string' &&\n\t\t! hasQueryArg( options.url, '_locale' )\n\t) {\n\t\toptions.url = addQueryArgs( options.url, { _locale: 'user' } );\n\t}\n\n\tif (\n\t\ttypeof options.path === 'string' &&\n\t\t! hasQueryArg( options.path, '_locale' )\n\t) {\n\t\toptions.path = addQueryArgs( options.path, { _locale: 'user' } );\n\t}\n\n\treturn next( options );\n};\n\nexport default userLocaleMiddleware;\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,YAAY,EAAEC,WAAW,QAAQ,gBAAgB;;AAE1D;AACA;AACA;AACA,MAAMC,oBAAoB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACjD,IACC,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,IAC/B,CAAEJ,WAAW,CAAEE,OAAO,CAACE,GAAG,EAAE,SAAU,CAAC,EACtC;IACDF,OAAO,CAACE,GAAG,GAAGL,YAAY,CAAEG,OAAO,CAACE,GAAG,EAAE;MAAEC,OAAO,EAAE;IAAO,CAAE,CAAC;EAC/D;EAEA,IACC,OAAOH,OAAO,CAACI,IAAI,KAAK,QAAQ,IAChC,CAAEN,WAAW,CAAEE,OAAO,CAACI,IAAI,EAAE,SAAU,CAAC,EACvC;IACDJ,OAAO,CAACI,IAAI,GAAGP,YAAY,CAAEG,OAAO,CAACI,IAAI,EAAE;MAAED,OAAO,EAAE;IAAO,CAAE,CAAC;EACjE;EAEA,OAAOF,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAED,eAAeD,oBAAoB","ignoreList":[]}

View File

@@ -0,0 +1,2 @@
export {};
//# sourceMappingURL=types.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":[],"sources":["@wordpress/api-fetch/src/types.ts"],"sourcesContent":["export interface APIFetchOptions extends RequestInit {\n\t// Override headers, we only accept it as an object due to the `nonce` middleware\n\theaders?: Record< string, string >;\n\tpath?: string;\n\turl?: string;\n\t/**\n\t * @default true\n\t */\n\tparse?: boolean;\n\tdata?: any;\n\tnamespace?: string;\n\tendpoint?: string;\n}\n\nexport type APIFetchMiddleware = (\n\toptions: APIFetchOptions,\n\tnext: ( nextOptions: APIFetchOptions ) => Promise< any >\n) => Promise< any >;\n"],"mappings":"","ignoreList":[]}

View File

@@ -0,0 +1,75 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Parses the apiFetch response.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const parseResponse = (response, shouldParseResponse = true) => {
if (shouldParseResponse) {
if (response.status === 204) {
return null;
}
return response.json ? response.json() : Promise.reject(response);
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
*
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = response => {
const invalidJsonError = {
code: 'invalid_json',
message: __('The response is not a valid JSON response.')
};
if (!response || !response.json) {
throw invalidJsonError;
}
return response.json().catch(() => {
throw invalidJsonError;
});
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any>} Parsed response.
*/
export const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
return Promise.resolve(parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
export function parseAndThrowError(response, shouldParseResponse = true) {
if (!shouldParseResponse) {
throw response;
}
return parseJsonAndNormalizeError(response).then(error => {
const unknownError = {
code: 'unknown_error',
message: __('An unknown error occurred.')
};
throw error || unknownError;
});
}
//# sourceMappingURL=response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["__","parseResponse","response","shouldParseResponse","status","json","Promise","reject","parseJsonAndNormalizeError","invalidJsonError","code","message","catch","parseResponseAndNormalizeError","resolve","res","parseAndThrowError","then","error","unknownError"],"sources":["@wordpress/api-fetch/src/utils/response.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Parses the apiFetch response.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any> | null | Response} Parsed response.\n */\nconst parseResponse = ( response, shouldParseResponse = true ) => {\n\tif ( shouldParseResponse ) {\n\t\tif ( response.status === 204 ) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn response.json ? response.json() : Promise.reject( response );\n\t}\n\n\treturn response;\n};\n\n/**\n * Calls the `json` function on the Response, throwing an error if the response\n * doesn't have a json function or if parsing the json itself fails.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response.\n */\nconst parseJsonAndNormalizeError = ( response ) => {\n\tconst invalidJsonError = {\n\t\tcode: 'invalid_json',\n\t\tmessage: __( 'The response is not a valid JSON response.' ),\n\t};\n\n\tif ( ! response || ! response.json ) {\n\t\tthrow invalidJsonError;\n\t}\n\n\treturn response.json().catch( () => {\n\t\tthrow invalidJsonError;\n\t} );\n};\n\n/**\n * Parses the apiFetch response properly and normalize response errors.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any>} Parsed response.\n */\nexport const parseResponseAndNormalizeError = (\n\tresponse,\n\tshouldParseResponse = true\n) => {\n\treturn Promise.resolve(\n\t\tparseResponse( response, shouldParseResponse )\n\t).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) );\n};\n\n/**\n * Parses a response, throwing an error if parsing the response fails.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n * @return {Promise<any>} Parsed response.\n */\nexport function parseAndThrowError( response, shouldParseResponse = true ) {\n\tif ( ! shouldParseResponse ) {\n\t\tthrow response;\n\t}\n\n\treturn parseJsonAndNormalizeError( response ).then( ( error ) => {\n\t\tconst unknownError = {\n\t\t\tcode: 'unknown_error',\n\t\t\tmessage: __( 'An unknown error occurred.' ),\n\t\t};\n\n\t\tthrow error || unknownError;\n\t} );\n}\n"],"mappings":"AAAA;AACA;AACA;AACA,SAASA,EAAE,QAAQ,iBAAiB;;AAEpC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,aAAa,GAAGA,CAAEC,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,KAAM;EACjE,IAAKA,mBAAmB,EAAG;IAC1B,IAAKD,QAAQ,CAACE,MAAM,KAAK,GAAG,EAAG;MAC9B,OAAO,IAAI;IACZ;IAEA,OAAOF,QAAQ,CAACG,IAAI,GAAGH,QAAQ,CAACG,IAAI,CAAC,CAAC,GAAGC,OAAO,CAACC,MAAM,CAAEL,QAAS,CAAC;EACpE;EAEA,OAAOA,QAAQ;AAChB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMM,0BAA0B,GAAKN,QAAQ,IAAM;EAClD,MAAMO,gBAAgB,GAAG;IACxBC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAEX,EAAE,CAAE,4CAA6C;EAC3D,CAAC;EAED,IAAK,CAAEE,QAAQ,IAAI,CAAEA,QAAQ,CAACG,IAAI,EAAG;IACpC,MAAMI,gBAAgB;EACvB;EAEA,OAAOP,QAAQ,CAACG,IAAI,CAAC,CAAC,CAACO,KAAK,CAAE,MAAM;IACnC,MAAMH,gBAAgB;EACvB,CAAE,CAAC;AACJ,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,MAAMI,8BAA8B,GAAGA,CAC7CX,QAAQ,EACRC,mBAAmB,GAAG,IAAI,KACtB;EACJ,OAAOG,OAAO,CAACQ,OAAO,CACrBb,aAAa,CAAEC,QAAQ,EAAEC,mBAAoB,CAC9C,CAAC,CAACS,KAAK,CAAIG,GAAG,IAAMC,kBAAkB,CAAED,GAAG,EAAEZ,mBAAoB,CAAE,CAAC;AACrE,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,OAAO,SAASa,kBAAkBA,CAAEd,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,EAAG;EAC1E,IAAK,CAAEA,mBAAmB,EAAG;IAC5B,MAAMD,QAAQ;EACf;EAEA,OAAOM,0BAA0B,CAAEN,QAAS,CAAC,CAACe,IAAI,CAAIC,KAAK,IAAM;IAChE,MAAMC,YAAY,GAAG;MACpBT,IAAI,EAAE,eAAe;MACrBC,OAAO,EAAEX,EAAE,CAAE,4BAA6B;IAC3C,CAAC;IAED,MAAMkB,KAAK,IAAIC,YAAY;EAC5B,CAAE,CAAC;AACJ","ignoreList":[]}

View File

@@ -0,0 +1,40 @@
export default apiFetch;
export type APIFetchMiddleware = import('./types').APIFetchMiddleware;
export type APIFetchOptions = import('./types').APIFetchOptions;
export type FetchHandler = (options: import('./types').APIFetchOptions) => Promise<any>;
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
declare function apiFetch<T>(options: import('./types').APIFetchOptions): Promise<T>;
declare namespace apiFetch {
export { registerMiddleware as use };
export { setFetchHandler };
export { createNonceMiddleware };
export { createPreloadingMiddleware };
export { createRootURLMiddleware };
export { fetchAllMiddleware };
export { mediaUploadMiddleware };
export { createThemePreviewMiddleware };
}
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
declare function registerMiddleware(middleware: import('./types').APIFetchMiddleware): void;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
declare function setFetchHandler(newFetchHandler: FetchHandler): void;
import createNonceMiddleware from './middlewares/nonce';
import createPreloadingMiddleware from './middlewares/preloading';
import createRootURLMiddleware from './middlewares/root-url';
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import mediaUploadMiddleware from './middlewares/media-upload';
import createThemePreviewMiddleware from './middlewares/theme-preview';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.js"],"names":[],"mappings":";iCA8Cc,OAAO,SAAS,EAAE,kBAAkB;8BACpC,OAAO,SAAS,EAAE,eAAe;2BAoCjC,CAAC,OAAO,EAAE,OAAO,SAAS,EAAE,eAAe,KAAK,QAAQ,GAAG,CAAC;AAkE1E;;;;GAIG;AACH,sCAHW,OAAO,SAAS,EAAE,eAAe,cAmC3C;;;;;;;;;;;AA/HD;;;;GAIG;AACH,gDAFW,OAAO,SAAS,EAAE,kBAAkB,QAI9C;AAyED;;;;;GAKG;AACH,kDAFW,YAAY,QAItB;kCA3IiC,qBAAqB;uCAEhB,0BAA0B;oCAD7B,wBAAwB;+BAE7B,oCAAoC;kCAIjC,4BAA4B;yCACrB,6BAA6B"}

View File

@@ -0,0 +1,10 @@
export default fetchAllMiddleware;
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
declare const fetchAllMiddleware: import('../types').APIFetchMiddleware;
//# sourceMappingURL=fetch-all-middleware.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"fetch-all-middleware.d.ts","sourceRoot":"","sources":["../../src/middlewares/fetch-all-middleware.js"],"names":[],"mappings":";AAqEA;;;;;;GAMG;AACH,kCAFU,OAAO,UAAU,EAAE,kBAAkB,CAmD7C"}

View File

@@ -0,0 +1,9 @@
export default httpV1Middleware;
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
declare const httpV1Middleware: import('../types').APIFetchMiddleware;
//# sourceMappingURL=http-v1.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"http-v1.d.ts","sourceRoot":"","sources":["../../src/middlewares/http-v1.js"],"names":[],"mappings":";AAmBA;;;;;GAKG;AACH,gCAFU,OAAO,UAAU,EAAE,kBAAkB,CAiB7C"}

View File

@@ -0,0 +1,8 @@
export default mediaUploadMiddleware;
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
declare const mediaUploadMiddleware: import('../types').APIFetchMiddleware;
//# sourceMappingURL=media-upload.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"media-upload.d.ts","sourceRoot":"","sources":["../../src/middlewares/media-upload.js"],"names":[],"mappings":";AA0BA;;;;GAIG;AACH,qCAFU,OAAO,UAAU,EAAE,kBAAkB,CA8D7C"}

View File

@@ -0,0 +1,6 @@
export default namespaceAndEndpointMiddleware;
/**
* @type {import('../types').APIFetchMiddleware}
*/
declare const namespaceAndEndpointMiddleware: import('../types').APIFetchMiddleware;
//# sourceMappingURL=namespace-endpoint.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"namespace-endpoint.d.ts","sourceRoot":"","sources":["../../src/middlewares/namespace-endpoint.js"],"names":[],"mappings":";AAAA;;GAEG;AACH,8CAFU,OAAO,UAAU,EAAE,kBAAkB,CA0B7C"}

View File

@@ -0,0 +1,9 @@
export default createNonceMiddleware;
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
declare function createNonceMiddleware(nonce: string): import('../types').APIFetchMiddleware & {
nonce: string;
};
//# sourceMappingURL=nonce.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"nonce.d.ts","sourceRoot":"","sources":["../../src/middlewares/nonce.js"],"names":[],"mappings":";AAAA;;;GAGG;AACH,8CAHW,MAAM,GACL,OAAO,UAAU,EAAE,kBAAkB,GAAG;IAAE,KAAK,EAAE,MAAM,CAAA;CAAE,CAgCpE"}

View File

@@ -0,0 +1,7 @@
export default createPreloadingMiddleware;
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
declare function createPreloadingMiddleware(preloadedData: Record<string, any>): import('../types').APIFetchMiddleware;
//# sourceMappingURL=preloading.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"preloading.d.ts","sourceRoot":"","sources":["../../src/middlewares/preloading.js"],"names":[],"mappings":";AAKA;;;GAGG;AACH,2DAHW,OAAO,MAAM,EAAE,GAAG,CAAC,GAClB,OAAO,UAAU,EAAE,kBAAkB,CAqDhD"}

View File

@@ -0,0 +1,7 @@
export default createRootURLMiddleware;
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
declare function createRootURLMiddleware(rootURL: string): import('../types').APIFetchMiddleware;
//# sourceMappingURL=root-url.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"root-url.d.ts","sourceRoot":"","sources":["../../src/middlewares/root-url.js"],"names":[],"mappings":";AAKA;;;GAGG;AACH,kDAHW,MAAM,GACL,OAAO,UAAU,EAAE,kBAAkB,CAkChD"}

View File

@@ -0,0 +1,13 @@
export default createThemePreviewMiddleware;
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
*
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
* then bypass this middleware.
*
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
declare function createThemePreviewMiddleware(themePath: Record<string, any>): import('../types').APIFetchMiddleware;
//# sourceMappingURL=theme-preview.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"theme-preview.d.ts","sourceRoot":"","sources":["../../src/middlewares/theme-preview.js"],"names":[],"mappings":";AAKA;;;;;;;;;GASG;AACH,yDAHW,OAAO,MAAM,EAAE,GAAG,CAAC,GAClB,OAAO,UAAU,EAAE,kBAAkB,CA0BhD"}

View File

@@ -0,0 +1,6 @@
export default userLocaleMiddleware;
/**
* @type {import('../types').APIFetchMiddleware}
*/
declare const userLocaleMiddleware: import('../types').APIFetchMiddleware;
//# sourceMappingURL=user-locale.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"user-locale.d.ts","sourceRoot":"","sources":["../../src/middlewares/user-locale.js"],"names":[],"mappings":";AAKA;;GAEG;AACH,oCAFU,OAAO,UAAU,EAAE,kBAAkB,CAkB7C"}

View File

@@ -0,0 +1,14 @@
export interface APIFetchOptions extends RequestInit {
headers?: Record<string, string>;
path?: string;
url?: string;
/**
* @default true
*/
parse?: boolean;
data?: any;
namespace?: string;
endpoint?: string;
}
export type APIFetchMiddleware = (options: APIFetchOptions, next: (nextOptions: APIFetchOptions) => Promise<any>) => Promise<any>;
//# sourceMappingURL=types.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,eAAgB,SAAQ,WAAW;IAEnD,OAAO,CAAC,EAAE,MAAM,CAAE,MAAM,EAAE,MAAM,CAAE,CAAC;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,GAAG,CAAC,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,KAAK,CAAC,EAAE,OAAO,CAAC;IAChB,IAAI,CAAC,EAAE,GAAG,CAAC;IACX,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,MAAM,kBAAkB,GAAG,CAChC,OAAO,EAAE,eAAe,EACxB,IAAI,EAAE,CAAE,WAAW,EAAE,eAAe,KAAM,OAAO,CAAE,GAAG,CAAE,KACpD,OAAO,CAAE,GAAG,CAAE,CAAC"}

View File

@@ -0,0 +1,10 @@
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
export function parseAndThrowError(response: Response, shouldParseResponse?: boolean): Promise<any>;
export function parseResponseAndNormalizeError(response: Response, shouldParseResponse?: boolean): Promise<any>;
//# sourceMappingURL=response.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"response.d.ts","sourceRoot":"","sources":["../../src/utils/response.js"],"names":[],"mappings":"AAgEA;;;;;;GAMG;AACH,6CAJW,QAAQ,wBACR,OAAO,GACN,QAAQ,GAAG,CAAC,CAevB;AA7BM,yDALI,QAAQ,wBACR,OAAO,GAEN,QAAQ,GAAG,CAAC,CASvB"}

185
node_modules/@wordpress/api-fetch/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,185 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _nonce = _interopRequireDefault(require("./middlewares/nonce"));
var _rootUrl = _interopRequireDefault(require("./middlewares/root-url"));
var _preloading = _interopRequireDefault(require("./middlewares/preloading"));
var _fetchAllMiddleware = _interopRequireDefault(require("./middlewares/fetch-all-middleware"));
var _namespaceEndpoint = _interopRequireDefault(require("./middlewares/namespace-endpoint"));
var _httpV = _interopRequireDefault(require("./middlewares/http-v1"));
var _userLocale = _interopRequireDefault(require("./middlewares/user-locale"));
var _mediaUpload = _interopRequireDefault(require("./middlewares/media-upload"));
var _themePreview = _interopRequireDefault(require("./middlewares/theme-preview"));
var _response = require("./utils/response");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Default set of header values which should be sent with every request unless
* explicitly provided through apiFetch options.
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
//
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1'
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include'
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [_userLocale.default, _namespaceEndpoint.default, _httpV.default, _fetchAllMiddleware.default];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware(middleware) {
middlewares.unshift(middleware);
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
*
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = response => {
if (response.status >= 200 && response.status < 300) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = nextOptions => {
const {
url,
path,
data,
parse = true,
...remainingOptions
} = nextOptions;
let {
body,
headers
} = nextOptions;
// Merge explicitly-provided headers with default values.
headers = {
...DEFAULT_HEADERS,
...headers
};
// The `data` property is a shorthand for sending a JSON body.
if (data) {
body = JSON.stringify(data);
headers['Content-Type'] = 'application/json';
}
const responsePromise = window.fetch(
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href, {
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers
});
return responsePromise.then(value => Promise.resolve(value).then(checkStatus).catch(response => (0, _response.parseAndThrowError)(response, parse)).then(response => (0, _response.parseResponseAndNormalizeError)(response, parse)), err => {
// Re-throw AbortError for the users to handle it themselves.
if (err && err.name === 'AbortError') {
throw err;
}
// Otherwise, there is most likely no network connection.
// Unfortunately the message might depend on the browser.
throw {
code: 'fetch_error',
message: (0, _i18n.__)('You are probably offline.')
};
});
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler(newFetchHandler) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch(options) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight(( /** @type {FetchHandler} */next, middleware) => {
return workingOptions => middleware(workingOptions, next);
}, fetchHandler);
return enhancedHandler(options).catch(error => {
if (error.code !== 'rest_cookie_invalid_nonce') {
return Promise.reject(error);
}
// If the nonce is invalid, refresh it and try again.
return window
// @ts-ignore
.fetch(apiFetch.nonceEndpoint).then(checkStatus).then(data => data.text()).then(text => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
return apiFetch(options);
});
});
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = _nonce.default;
apiFetch.createPreloadingMiddleware = _preloading.default;
apiFetch.createRootURLMiddleware = _rootUrl.default;
apiFetch.fetchAllMiddleware = _fetchAllMiddleware.default;
apiFetch.mediaUploadMiddleware = _mediaUpload.default;
apiFetch.createThemePreviewMiddleware = _themePreview.default;
var _default = exports.default = apiFetch;
//# sourceMappingURL=index.js.map

1
node_modules/@wordpress/api-fetch/build/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,132 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
var _ = _interopRequireDefault(require(".."));
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* Apply query arguments to both URL and Path, whichever is present.
*
* @param {import('../types').APIFetchOptions} props
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ({
path,
url,
...options
}, queryArgs) => ({
...options,
url: url && (0, _url.addQueryArgs)(url, queryArgs),
path: path && (0, _url.addQueryArgs)(path, queryArgs)
});
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = response => response.json ? response.json() : Promise.reject(response);
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = linkHeader => {
if (!linkHeader) {
return {};
}
const match = linkHeader.match(/<([^>]+)>; rel="next"/);
return match ? {
next: match[1]
} : {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = response => {
const {
next
} = parseLinkHeader(response.headers.get('link'));
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = options => {
const pathIsUnbounded = !!options.path && options.path.indexOf('per_page=-1') !== -1;
const urlIsUnbounded = !!options.url && options.url.indexOf('per_page=-1') !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async (options, next) => {
if (options.parse === false) {
// If a consumer has opted out of parsing, do not apply middleware.
return next(options);
}
if (!requestContainsUnboundedQuery(options)) {
// If neither url nor path is requesting all items, do not apply middleware.
return next(options);
}
// Retrieve requested page of results.
const response = await (0, _.default)({
...modifyQuery(options, {
per_page: 100
}),
// Ensure headers are returned for page 1.
parse: false
});
const results = await parseResponse(response);
if (!Array.isArray(results)) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl(response);
if (!nextPage) {
// There are no further pages to request.
return results;
}
// Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults = /** @type {any[]} */[].concat(results);
while (nextPage) {
const nextResponse = await (0, _.default)({
...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
// Ensure we still get headers so we can identify the next page.
parse: false
});
const nextResults = await parseResponse(nextResponse);
mergedResults = mergedResults.concat(nextResults);
nextPage = getNextPageUrl(nextResponse);
}
return mergedResults;
};
var _default = exports.default = fetchAllMiddleware;
//# sourceMappingURL=fetch-all-middleware.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* Set of HTTP methods which are eligible to be overridden.
*
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set(['PATCH', 'PUT', 'DELETE']);
/**
* Default request method.
*
* "A request has an associated method (a method). Unless stated otherwise it
* is `GET`."
*
* @see https://fetch.spec.whatwg.org/#requests
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = (options, next) => {
const {
method = DEFAULT_METHOD
} = options;
if (OVERRIDE_METHODS.has(method.toUpperCase())) {
options = {
...options,
headers: {
...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json'
},
method: 'POST'
};
}
return next(options);
};
var _default = exports.default = httpV1Middleware;
//# sourceMappingURL=http-v1.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["OVERRIDE_METHODS","Set","DEFAULT_METHOD","httpV1Middleware","options","next","method","has","toUpperCase","headers","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/http-v1.js"],"sourcesContent":["/**\n * Set of HTTP methods which are eligible to be overridden.\n *\n * @type {Set<string>}\n */\nconst OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );\n\n/**\n * Default request method.\n *\n * \"A request has an associated method (a method). Unless stated otherwise it\n * is `GET`.\"\n *\n * @see https://fetch.spec.whatwg.org/#requests\n *\n * @type {string}\n */\nconst DEFAULT_METHOD = 'GET';\n\n/**\n * API Fetch middleware which overrides the request method for HTTP v1\n * compatibility leveraging the REST API X-HTTP-Method-Override header.\n *\n * @type {import('../types').APIFetchMiddleware}\n */\nconst httpV1Middleware = ( options, next ) => {\n\tconst { method = DEFAULT_METHOD } = options;\n\tif ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {\n\t\toptions = {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...options.headers,\n\t\t\t\t'X-HTTP-Method-Override': method,\n\t\t\t\t'Content-Type': 'application/json',\n\t\t\t},\n\t\t\tmethod: 'POST',\n\t\t};\n\t}\n\n\treturn next( options );\n};\n\nexport default httpV1Middleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA,MAAMA,gBAAgB,GAAG,IAAIC,GAAG,CAAE,CAAE,OAAO,EAAE,KAAK,EAAE,QAAQ,CAAG,CAAC;;AAEhE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,cAAc,GAAG,KAAK;;AAE5B;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,gBAAgB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC7C,MAAM;IAAEC,MAAM,GAAGJ;EAAe,CAAC,GAAGE,OAAO;EAC3C,IAAKJ,gBAAgB,CAACO,GAAG,CAAED,MAAM,CAACE,WAAW,CAAC,CAAE,CAAC,EAAG;IACnDJ,OAAO,GAAG;MACT,GAAGA,OAAO;MACVK,OAAO,EAAE;QACR,GAAGL,OAAO,CAACK,OAAO;QAClB,wBAAwB,EAAEH,MAAM;QAChC,cAAc,EAAE;MACjB,CAAC;MACDA,MAAM,EAAE;IACT,CAAC;EACF;EAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaT,gBAAgB","ignoreList":[]}

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _i18n = require("@wordpress/i18n");
var _response = require("../utils/response");
/**
* WordPress dependencies
*/
/**
* Internal dependencies
*/
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest(options) {
const isCreateMethod = !!options.method && options.method === 'POST';
const isMediaEndpoint = !!options.path && options.path.indexOf('/wp/v2/media') !== -1 || !!options.url && options.url.indexOf('/wp/v2/media') !== -1;
return isMediaEndpoint && isCreateMethod;
}
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = (options, next) => {
if (!isMediaUploadRequest(options)) {
return next(options);
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = attachmentId => {
retries++;
return next({
path: `/wp/v2/media/${attachmentId}/post-process`,
method: 'POST',
data: {
action: 'create-image-subsizes'
},
parse: false
}).catch(() => {
if (retries < maxRetries) {
return postProcess(attachmentId);
}
next({
path: `/wp/v2/media/${attachmentId}?force=true`,
method: 'DELETE'
});
return Promise.reject();
});
};
return next({
...options,
parse: false
}).catch(response => {
const attachmentId = response.headers.get('x-wp-upload-attachment-id');
if (response.status >= 500 && response.status < 600 && attachmentId) {
return postProcess(attachmentId).catch(() => {
if (options.parse !== false) {
return Promise.reject({
code: 'post_process',
message: (0, _i18n.__)('Media upload failed. If this is a photo or a large image, please scale it down and try again.')
});
}
return Promise.reject(response);
});
}
return (0, _response.parseAndThrowError)(response, options.parse);
}).then(response => (0, _response.parseResponseAndNormalizeError)(response, options.parse));
};
var _default = exports.default = mediaUploadMiddleware;
//# sourceMappingURL=media-upload.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = (options, next) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (typeof options.namespace === 'string' && typeof options.endpoint === 'string') {
namespaceTrimmed = options.namespace.replace(/^\/|\/$/g, '');
endpointTrimmed = options.endpoint.replace(/^\//, '');
if (endpointTrimmed) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next({
...options,
path
});
};
var _default = exports.default = namespaceAndEndpointMiddleware;
//# sourceMappingURL=namespace-endpoint.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["namespaceAndEndpointMiddleware","options","next","path","namespaceTrimmed","endpointTrimmed","namespace","endpoint","replace","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/namespace-endpoint.js"],"sourcesContent":["/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst namespaceAndEndpointMiddleware = ( options, next ) => {\n\tlet path = options.path;\n\tlet namespaceTrimmed, endpointTrimmed;\n\n\tif (\n\t\ttypeof options.namespace === 'string' &&\n\t\ttypeof options.endpoint === 'string'\n\t) {\n\t\tnamespaceTrimmed = options.namespace.replace( /^\\/|\\/$/g, '' );\n\t\tendpointTrimmed = options.endpoint.replace( /^\\//, '' );\n\t\tif ( endpointTrimmed ) {\n\t\t\tpath = namespaceTrimmed + '/' + endpointTrimmed;\n\t\t} else {\n\t\t\tpath = namespaceTrimmed;\n\t\t}\n\t}\n\n\tdelete options.namespace;\n\tdelete options.endpoint;\n\n\treturn next( {\n\t\t...options,\n\t\tpath,\n\t} );\n};\n\nexport default namespaceAndEndpointMiddleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA,MAAMA,8BAA8B,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC3D,IAAIC,IAAI,GAAGF,OAAO,CAACE,IAAI;EACvB,IAAIC,gBAAgB,EAAEC,eAAe;EAErC,IACC,OAAOJ,OAAO,CAACK,SAAS,KAAK,QAAQ,IACrC,OAAOL,OAAO,CAACM,QAAQ,KAAK,QAAQ,EACnC;IACDH,gBAAgB,GAAGH,OAAO,CAACK,SAAS,CAACE,OAAO,CAAE,UAAU,EAAE,EAAG,CAAC;IAC9DH,eAAe,GAAGJ,OAAO,CAACM,QAAQ,CAACC,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;IACvD,IAAKH,eAAe,EAAG;MACtBF,IAAI,GAAGC,gBAAgB,GAAG,GAAG,GAAGC,eAAe;IAChD,CAAC,MAAM;MACNF,IAAI,GAAGC,gBAAgB;IACxB;EACD;EAEA,OAAOH,OAAO,CAACK,SAAS;EACxB,OAAOL,OAAO,CAACM,QAAQ;EAEvB,OAAOL,IAAI,CAAE;IACZ,GAAGD,OAAO;IACVE;EACD,CAAE,CAAC;AACJ,CAAC;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaX,8BAA8B","ignoreList":[]}

View File

@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware(nonce) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
const middleware = (options, next) => {
const {
headers = {}
} = options;
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for (const headerName in headers) {
if (headerName.toLowerCase() === 'x-wp-nonce' && headers[headerName] === middleware.nonce) {
return next(options);
}
}
return next({
...options,
headers: {
...headers,
'X-WP-Nonce': middleware.nonce
}
});
};
middleware.nonce = nonce;
return middleware;
}
var _default = exports.default = createNonceMiddleware;
//# sourceMappingURL=nonce.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["createNonceMiddleware","nonce","middleware","options","next","headers","headerName","toLowerCase","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/nonce.js"],"sourcesContent":["/**\n * @param {string} nonce\n * @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.\n */\nfunction createNonceMiddleware( nonce ) {\n\t/**\n\t * @type {import('../types').APIFetchMiddleware & { nonce: string }}\n\t */\n\tconst middleware = ( options, next ) => {\n\t\tconst { headers = {} } = options;\n\n\t\t// If an 'X-WP-Nonce' header (or any case-insensitive variation\n\t\t// thereof) was specified, no need to add a nonce header.\n\t\tfor ( const headerName in headers ) {\n\t\t\tif (\n\t\t\t\theaderName.toLowerCase() === 'x-wp-nonce' &&\n\t\t\t\theaders[ headerName ] === middleware.nonce\n\t\t\t) {\n\t\t\t\treturn next( options );\n\t\t\t}\n\t\t}\n\n\t\treturn next( {\n\t\t\t...options,\n\t\t\theaders: {\n\t\t\t\t...headers,\n\t\t\t\t'X-WP-Nonce': middleware.nonce,\n\t\t\t},\n\t\t} );\n\t};\n\n\tmiddleware.nonce = nonce;\n\n\treturn middleware;\n}\n\nexport default createNonceMiddleware;\n"],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA,SAASA,qBAAqBA,CAAEC,KAAK,EAAG;EACvC;AACD;AACA;EACC,MAAMC,UAAU,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;IACvC,MAAM;MAAEC,OAAO,GAAG,CAAC;IAAE,CAAC,GAAGF,OAAO;;IAEhC;IACA;IACA,KAAM,MAAMG,UAAU,IAAID,OAAO,EAAG;MACnC,IACCC,UAAU,CAACC,WAAW,CAAC,CAAC,KAAK,YAAY,IACzCF,OAAO,CAAEC,UAAU,CAAE,KAAKJ,UAAU,CAACD,KAAK,EACzC;QACD,OAAOG,IAAI,CAAED,OAAQ,CAAC;MACvB;IACD;IAEA,OAAOC,IAAI,CAAE;MACZ,GAAGD,OAAO;MACVE,OAAO,EAAE;QACR,GAAGA,OAAO;QACV,YAAY,EAAEH,UAAU,CAACD;MAC1B;IACD,CAAE,CAAC;EACJ,CAAC;EAEDC,UAAU,CAACD,KAAK,GAAGA,KAAK;EAExB,OAAOC,UAAU;AAClB;AAAC,IAAAM,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcV,qBAAqB","ignoreList":[]}

View File

@@ -0,0 +1,70 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware(preloadedData) {
const cache = Object.fromEntries(Object.entries(preloadedData).map(([path, data]) => [(0, _url.normalizePath)(path), data]));
return (options, next) => {
const {
parse = true
} = options;
/** @type {string | void} */
let rawPath = options.path;
if (!rawPath && options.url) {
const {
rest_route: pathFromQuery,
...queryArgs
} = (0, _url.getQueryArgs)(options.url);
if (typeof pathFromQuery === 'string') {
rawPath = (0, _url.addQueryArgs)(pathFromQuery, queryArgs);
}
}
if (typeof rawPath !== 'string') {
return next(options);
}
const method = options.method || 'GET';
const path = (0, _url.normalizePath)(rawPath);
if ('GET' === method && cache[path]) {
const cacheData = cache[path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[path];
return prepareResponse(cacheData, !!parse);
} else if ('OPTIONS' === method && cache[method] && cache[method][path]) {
const cacheData = cache[method][path];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[method][path];
return prepareResponse(cacheData, !!parse);
}
return next(options);
};
}
/**
* This is a helper function that sends a success response.
*
* @param {Record<string, any>} responseData
* @param {boolean} parse
* @return {Promise<any>} Promise with the response.
*/
function prepareResponse(responseData, parse) {
return Promise.resolve(parse ? responseData.body : new window.Response(JSON.stringify(responseData.body), {
status: 200,
statusText: 'OK',
headers: responseData.headers
}));
}
var _default = exports.default = createPreloadingMiddleware;
//# sourceMappingURL=preloading.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","createPreloadingMiddleware","preloadedData","cache","Object","fromEntries","entries","map","path","data","normalizePath","options","next","parse","rawPath","url","rest_route","pathFromQuery","queryArgs","getQueryArgs","addQueryArgs","method","cacheData","prepareResponse","responseData","Promise","resolve","body","window","Response","JSON","stringify","status","statusText","headers","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/preloading.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';\n\n/**\n * @param {Record<string, any>} preloadedData\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nfunction createPreloadingMiddleware( preloadedData ) {\n\tconst cache = Object.fromEntries(\n\t\tObject.entries( preloadedData ).map( ( [ path, data ] ) => [\n\t\t\tnormalizePath( path ),\n\t\t\tdata,\n\t\t] )\n\t);\n\n\treturn ( options, next ) => {\n\t\tconst { parse = true } = options;\n\t\t/** @type {string | void} */\n\t\tlet rawPath = options.path;\n\t\tif ( ! rawPath && options.url ) {\n\t\t\tconst { rest_route: pathFromQuery, ...queryArgs } = getQueryArgs(\n\t\t\t\toptions.url\n\t\t\t);\n\n\t\t\tif ( typeof pathFromQuery === 'string' ) {\n\t\t\t\trawPath = addQueryArgs( pathFromQuery, queryArgs );\n\t\t\t}\n\t\t}\n\n\t\tif ( typeof rawPath !== 'string' ) {\n\t\t\treturn next( options );\n\t\t}\n\n\t\tconst method = options.method || 'GET';\n\t\tconst path = normalizePath( rawPath );\n\n\t\tif ( 'GET' === method && cache[ path ] ) {\n\t\t\tconst cacheData = cache[ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t} else if (\n\t\t\t'OPTIONS' === method &&\n\t\t\tcache[ method ] &&\n\t\t\tcache[ method ][ path ]\n\t\t) {\n\t\t\tconst cacheData = cache[ method ][ path ];\n\n\t\t\t// Unsetting the cache key ensures that the data is only used a single time.\n\t\t\tdelete cache[ method ][ path ];\n\n\t\t\treturn prepareResponse( cacheData, !! parse );\n\t\t}\n\n\t\treturn next( options );\n\t};\n}\n\n/**\n * This is a helper function that sends a success response.\n *\n * @param {Record<string, any>} responseData\n * @param {boolean} parse\n * @return {Promise<any>} Promise with the response.\n */\nfunction prepareResponse( responseData, parse ) {\n\treturn Promise.resolve(\n\t\tparse\n\t\t\t? responseData.body\n\t\t\t: new window.Response( JSON.stringify( responseData.body ), {\n\t\t\t\t\tstatus: 200,\n\t\t\t\t\tstatusText: 'OK',\n\t\t\t\t\theaders: responseData.headers,\n\t\t\t } )\n\t);\n}\n\nexport default createPreloadingMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,SAASC,0BAA0BA,CAAEC,aAAa,EAAG;EACpD,MAAMC,KAAK,GAAGC,MAAM,CAACC,WAAW,CAC/BD,MAAM,CAACE,OAAO,CAAEJ,aAAc,CAAC,CAACK,GAAG,CAAE,CAAE,CAAEC,IAAI,EAAEC,IAAI,CAAE,KAAM,CAC1D,IAAAC,kBAAa,EAAEF,IAAK,CAAC,EACrBC,IAAI,CACH,CACH,CAAC;EAED,OAAO,CAAEE,OAAO,EAAEC,IAAI,KAAM;IAC3B,MAAM;MAAEC,KAAK,GAAG;IAAK,CAAC,GAAGF,OAAO;IAChC;IACA,IAAIG,OAAO,GAAGH,OAAO,CAACH,IAAI;IAC1B,IAAK,CAAEM,OAAO,IAAIH,OAAO,CAACI,GAAG,EAAG;MAC/B,MAAM;QAAEC,UAAU,EAAEC,aAAa;QAAE,GAAGC;MAAU,CAAC,GAAG,IAAAC,iBAAY,EAC/DR,OAAO,CAACI,GACT,CAAC;MAED,IAAK,OAAOE,aAAa,KAAK,QAAQ,EAAG;QACxCH,OAAO,GAAG,IAAAM,iBAAY,EAAEH,aAAa,EAAEC,SAAU,CAAC;MACnD;IACD;IAEA,IAAK,OAAOJ,OAAO,KAAK,QAAQ,EAAG;MAClC,OAAOF,IAAI,CAAED,OAAQ,CAAC;IACvB;IAEA,MAAMU,MAAM,GAAGV,OAAO,CAACU,MAAM,IAAI,KAAK;IACtC,MAAMb,IAAI,GAAG,IAAAE,kBAAa,EAAEI,OAAQ,CAAC;IAErC,IAAK,KAAK,KAAKO,MAAM,IAAIlB,KAAK,CAAEK,IAAI,CAAE,EAAG;MACxC,MAAMc,SAAS,GAAGnB,KAAK,CAAEK,IAAI,CAAE;;MAE/B;MACA,OAAOL,KAAK,CAAEK,IAAI,CAAE;MAEpB,OAAOe,eAAe,CAAED,SAAS,EAAE,CAAC,CAAET,KAAM,CAAC;IAC9C,CAAC,MAAM,IACN,SAAS,KAAKQ,MAAM,IACpBlB,KAAK,CAAEkB,MAAM,CAAE,IACflB,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE,EACtB;MACD,MAAMc,SAAS,GAAGnB,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE;;MAEzC;MACA,OAAOL,KAAK,CAAEkB,MAAM,CAAE,CAAEb,IAAI,CAAE;MAE9B,OAAOe,eAAe,CAAED,SAAS,EAAE,CAAC,CAAET,KAAM,CAAC;IAC9C;IAEA,OAAOD,IAAI,CAAED,OAAQ,CAAC;EACvB,CAAC;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAASY,eAAeA,CAAEC,YAAY,EAAEX,KAAK,EAAG;EAC/C,OAAOY,OAAO,CAACC,OAAO,CACrBb,KAAK,GACFW,YAAY,CAACG,IAAI,GACjB,IAAIC,MAAM,CAACC,QAAQ,CAAEC,IAAI,CAACC,SAAS,CAAEP,YAAY,CAACG,IAAK,CAAC,EAAE;IAC1DK,MAAM,EAAE,GAAG;IACXC,UAAU,EAAE,IAAI;IAChBC,OAAO,EAAEV,YAAY,CAACU;EACtB,CAAE,CACN,CAAC;AACF;AAAC,IAAAC,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEcpC,0BAA0B","ignoreList":[]}

View File

@@ -0,0 +1,43 @@
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _namespaceEndpoint = _interopRequireDefault(require("./namespace-endpoint"));
/**
* Internal dependencies
*/
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = rootURL => (options, next) => {
return (0, _namespaceEndpoint.default)(options, optionsWithPath => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if (typeof path === 'string') {
apiRoot = rootURL;
if (-1 !== rootURL.indexOf('?')) {
path = path.replace('?', '&');
}
path = path.replace(/^\//, '');
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if ('string' === typeof apiRoot && -1 !== apiRoot.indexOf('?')) {
path = path.replace('?', '&');
}
url = apiRoot + path;
}
return next({
...optionsWithPath,
url
});
});
};
var _default = exports.default = createRootURLMiddleware;
//# sourceMappingURL=root-url.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_namespaceEndpoint","_interopRequireDefault","require","createRootURLMiddleware","rootURL","options","next","namespaceAndEndpointMiddleware","optionsWithPath","url","path","apiRoot","indexOf","replace","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/root-url.js"],"sourcesContent":["/**\n * Internal dependencies\n */\nimport namespaceAndEndpointMiddleware from './namespace-endpoint';\n\n/**\n * @param {string} rootURL\n * @return {import('../types').APIFetchMiddleware} Root URL middleware.\n */\nconst createRootURLMiddleware = ( rootURL ) => ( options, next ) => {\n\treturn namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {\n\t\tlet url = optionsWithPath.url;\n\t\tlet path = optionsWithPath.path;\n\t\tlet apiRoot;\n\n\t\tif ( typeof path === 'string' ) {\n\t\t\tapiRoot = rootURL;\n\n\t\t\tif ( -1 !== rootURL.indexOf( '?' ) ) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\tpath = path.replace( /^\\//, '' );\n\n\t\t\t// API root may already include query parameter prefix if site is\n\t\t\t// configured to use plain permalinks.\n\t\t\tif (\n\t\t\t\t'string' === typeof apiRoot &&\n\t\t\t\t-1 !== apiRoot.indexOf( '?' )\n\t\t\t) {\n\t\t\t\tpath = path.replace( '?', '&' );\n\t\t\t}\n\n\t\t\turl = apiRoot + path;\n\t\t}\n\n\t\treturn next( {\n\t\t\t...optionsWithPath,\n\t\t\turl,\n\t\t} );\n\t} );\n};\n\nexport default createRootURLMiddleware;\n"],"mappings":";;;;;;;AAGA,IAAAA,kBAAA,GAAAC,sBAAA,CAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA,MAAMC,uBAAuB,GAAKC,OAAO,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACnE,OAAO,IAAAC,0BAA8B,EAAEF,OAAO,EAAIG,eAAe,IAAM;IACtE,IAAIC,GAAG,GAAGD,eAAe,CAACC,GAAG;IAC7B,IAAIC,IAAI,GAAGF,eAAe,CAACE,IAAI;IAC/B,IAAIC,OAAO;IAEX,IAAK,OAAOD,IAAI,KAAK,QAAQ,EAAG;MAC/BC,OAAO,GAAGP,OAAO;MAEjB,IAAK,CAAC,CAAC,KAAKA,OAAO,CAACQ,OAAO,CAAE,GAAI,CAAC,EAAG;QACpCF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAH,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,KAAK,EAAE,EAAG,CAAC;;MAEhC;MACA;MACA,IACC,QAAQ,KAAK,OAAOF,OAAO,IAC3B,CAAC,CAAC,KAAKA,OAAO,CAACC,OAAO,CAAE,GAAI,CAAC,EAC5B;QACDF,IAAI,GAAGA,IAAI,CAACG,OAAO,CAAE,GAAG,EAAE,GAAI,CAAC;MAChC;MAEAJ,GAAG,GAAGE,OAAO,GAAGD,IAAI;IACrB;IAEA,OAAOJ,IAAI,CAAE;MACZ,GAAGE,eAAe;MAClBC;IACD,CAAE,CAAC;EACJ,CAAE,CAAC;AACJ,CAAC;AAAC,IAAAK,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEab,uBAAuB","ignoreList":[]}

View File

@@ -0,0 +1,46 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
*
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
* then bypass this middleware.
*
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = themePath => (options, next) => {
if (typeof options.url === 'string') {
const wpThemePreview = (0, _url.getQueryArg)(options.url, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.url = (0, _url.addQueryArgs)(options.url, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.url = (0, _url.removeQueryArgs)(options.url, 'wp_theme_preview');
}
}
if (typeof options.path === 'string') {
const wpThemePreview = (0, _url.getQueryArg)(options.path, 'wp_theme_preview');
if (wpThemePreview === undefined) {
options.path = (0, _url.addQueryArgs)(options.path, {
wp_theme_preview: themePath
});
} else if (wpThemePreview === '') {
options.path = (0, _url.removeQueryArgs)(options.path, 'wp_theme_preview');
}
}
return next(options);
};
var _default = exports.default = createThemePreviewMiddleware;
//# sourceMappingURL=theme-preview.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","createThemePreviewMiddleware","themePath","options","next","url","wpThemePreview","getQueryArg","undefined","addQueryArgs","wp_theme_preview","removeQueryArgs","path","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/theme-preview.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';\n\n/**\n * This appends a `wp_theme_preview` parameter to the REST API request URL if\n * the admin URL contains a `theme` GET parameter.\n *\n * If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,\n * then bypass this middleware.\n *\n * @param {Record<string, any>} themePath\n * @return {import('../types').APIFetchMiddleware} Preloading middleware.\n */\nconst createThemePreviewMiddleware = ( themePath ) => ( options, next ) => {\n\tif ( typeof options.url === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.url, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.url = addQueryArgs( options.url, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.url = removeQueryArgs( options.url, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\tif ( typeof options.path === 'string' ) {\n\t\tconst wpThemePreview = getQueryArg( options.path, 'wp_theme_preview' );\n\t\tif ( wpThemePreview === undefined ) {\n\t\t\toptions.path = addQueryArgs( options.path, {\n\t\t\t\twp_theme_preview: themePath,\n\t\t\t} );\n\t\t} else if ( wpThemePreview === '' ) {\n\t\t\toptions.path = removeQueryArgs( options.path, 'wp_theme_preview' );\n\t\t}\n\t}\n\n\treturn next( options );\n};\n\nexport default createThemePreviewMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,4BAA4B,GAAKC,SAAS,IAAM,CAAEC,OAAO,EAAEC,IAAI,KAAM;EAC1E,IAAK,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,EAAG;IACtC,MAAMC,cAAc,GAAG,IAAAC,gBAAW,EAAEJ,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACrE,IAAKC,cAAc,KAAKE,SAAS,EAAG;MACnCL,OAAO,CAACE,GAAG,GAAG,IAAAI,iBAAY,EAAEN,OAAO,CAACE,GAAG,EAAE;QACxCK,gBAAgB,EAAER;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACE,GAAG,GAAG,IAAAM,oBAAe,EAAER,OAAO,CAACE,GAAG,EAAE,kBAAmB,CAAC;IACjE;EACD;EAEA,IAAK,OAAOF,OAAO,CAACS,IAAI,KAAK,QAAQ,EAAG;IACvC,MAAMN,cAAc,GAAG,IAAAC,gBAAW,EAAEJ,OAAO,CAACS,IAAI,EAAE,kBAAmB,CAAC;IACtE,IAAKN,cAAc,KAAKE,SAAS,EAAG;MACnCL,OAAO,CAACS,IAAI,GAAG,IAAAH,iBAAY,EAAEN,OAAO,CAACS,IAAI,EAAE;QAC1CF,gBAAgB,EAAER;MACnB,CAAE,CAAC;IACJ,CAAC,MAAM,IAAKI,cAAc,KAAK,EAAE,EAAG;MACnCH,OAAO,CAACS,IAAI,GAAG,IAAAD,oBAAe,EAAER,OAAO,CAACS,IAAI,EAAE,kBAAmB,CAAC;IACnE;EACD;EAEA,OAAOR,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAU,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEad,4BAA4B","ignoreList":[]}

View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _url = require("@wordpress/url");
/**
* WordPress dependencies
*/
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = (options, next) => {
if (typeof options.url === 'string' && !(0, _url.hasQueryArg)(options.url, '_locale')) {
options.url = (0, _url.addQueryArgs)(options.url, {
_locale: 'user'
});
}
if (typeof options.path === 'string' && !(0, _url.hasQueryArg)(options.path, '_locale')) {
options.path = (0, _url.addQueryArgs)(options.path, {
_locale: 'user'
});
}
return next(options);
};
var _default = exports.default = userLocaleMiddleware;
//# sourceMappingURL=user-locale.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_url","require","userLocaleMiddleware","options","next","url","hasQueryArg","addQueryArgs","_locale","path","_default","exports","default"],"sources":["@wordpress/api-fetch/src/middlewares/user-locale.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { addQueryArgs, hasQueryArg } from '@wordpress/url';\n\n/**\n * @type {import('../types').APIFetchMiddleware}\n */\nconst userLocaleMiddleware = ( options, next ) => {\n\tif (\n\t\ttypeof options.url === 'string' &&\n\t\t! hasQueryArg( options.url, '_locale' )\n\t) {\n\t\toptions.url = addQueryArgs( options.url, { _locale: 'user' } );\n\t}\n\n\tif (\n\t\ttypeof options.path === 'string' &&\n\t\t! hasQueryArg( options.path, '_locale' )\n\t) {\n\t\toptions.path = addQueryArgs( options.path, { _locale: 'user' } );\n\t}\n\n\treturn next( options );\n};\n\nexport default userLocaleMiddleware;\n"],"mappings":";;;;;;AAGA,IAAAA,IAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA,MAAMC,oBAAoB,GAAGA,CAAEC,OAAO,EAAEC,IAAI,KAAM;EACjD,IACC,OAAOD,OAAO,CAACE,GAAG,KAAK,QAAQ,IAC/B,CAAE,IAAAC,gBAAW,EAAEH,OAAO,CAACE,GAAG,EAAE,SAAU,CAAC,EACtC;IACDF,OAAO,CAACE,GAAG,GAAG,IAAAE,iBAAY,EAAEJ,OAAO,CAACE,GAAG,EAAE;MAAEG,OAAO,EAAE;IAAO,CAAE,CAAC;EAC/D;EAEA,IACC,OAAOL,OAAO,CAACM,IAAI,KAAK,QAAQ,IAChC,CAAE,IAAAH,gBAAW,EAAEH,OAAO,CAACM,IAAI,EAAE,SAAU,CAAC,EACvC;IACDN,OAAO,CAACM,IAAI,GAAG,IAAAF,iBAAY,EAAEJ,OAAO,CAACM,IAAI,EAAE;MAAED,OAAO,EAAE;IAAO,CAAE,CAAC;EACjE;EAEA,OAAOJ,IAAI,CAAED,OAAQ,CAAC;AACvB,CAAC;AAAC,IAAAO,QAAA,GAAAC,OAAA,CAAAC,OAAA,GAEaV,oBAAoB","ignoreList":[]}

6
node_modules/@wordpress/api-fetch/build/types.js generated vendored Normal file
View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
//# sourceMappingURL=types.js.map

1
node_modules/@wordpress/api-fetch/build/types.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"names":[],"sources":["@wordpress/api-fetch/src/types.ts"],"sourcesContent":["export interface APIFetchOptions extends RequestInit {\n\t// Override headers, we only accept it as an object due to the `nonce` middleware\n\theaders?: Record< string, string >;\n\tpath?: string;\n\turl?: string;\n\t/**\n\t * @default true\n\t */\n\tparse?: boolean;\n\tdata?: any;\n\tnamespace?: string;\n\tendpoint?: string;\n}\n\nexport type APIFetchMiddleware = (\n\toptions: APIFetchOptions,\n\tnext: ( nextOptions: APIFetchOptions ) => Promise< any >\n) => Promise< any >;\n"],"mappings":"","ignoreList":[]}

View File

@@ -0,0 +1,83 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.parseAndThrowError = parseAndThrowError;
exports.parseResponseAndNormalizeError = void 0;
var _i18n = require("@wordpress/i18n");
/**
* WordPress dependencies
*/
/**
* Parses the apiFetch response.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const parseResponse = (response, shouldParseResponse = true) => {
if (shouldParseResponse) {
if (response.status === 204) {
return null;
}
return response.json ? response.json() : Promise.reject(response);
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
*
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = response => {
const invalidJsonError = {
code: 'invalid_json',
message: (0, _i18n.__)('The response is not a valid JSON response.')
};
if (!response || !response.json) {
throw invalidJsonError;
}
return response.json().catch(() => {
throw invalidJsonError;
});
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any>} Parsed response.
*/
const parseResponseAndNormalizeError = (response, shouldParseResponse = true) => {
return Promise.resolve(parseResponse(response, shouldParseResponse)).catch(res => parseAndThrowError(res, shouldParseResponse));
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
exports.parseResponseAndNormalizeError = parseResponseAndNormalizeError;
function parseAndThrowError(response, shouldParseResponse = true) {
if (!shouldParseResponse) {
throw response;
}
return parseJsonAndNormalizeError(response).then(error => {
const unknownError = {
code: 'unknown_error',
message: (0, _i18n.__)('An unknown error occurred.')
};
throw error || unknownError;
});
}
//# sourceMappingURL=response.js.map

View File

@@ -0,0 +1 @@
{"version":3,"names":["_i18n","require","parseResponse","response","shouldParseResponse","status","json","Promise","reject","parseJsonAndNormalizeError","invalidJsonError","code","message","__","catch","parseResponseAndNormalizeError","resolve","res","parseAndThrowError","exports","then","error","unknownError"],"sources":["@wordpress/api-fetch/src/utils/response.js"],"sourcesContent":["/**\n * WordPress dependencies\n */\nimport { __ } from '@wordpress/i18n';\n\n/**\n * Parses the apiFetch response.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any> | null | Response} Parsed response.\n */\nconst parseResponse = ( response, shouldParseResponse = true ) => {\n\tif ( shouldParseResponse ) {\n\t\tif ( response.status === 204 ) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn response.json ? response.json() : Promise.reject( response );\n\t}\n\n\treturn response;\n};\n\n/**\n * Calls the `json` function on the Response, throwing an error if the response\n * doesn't have a json function or if parsing the json itself fails.\n *\n * @param {Response} response\n * @return {Promise<any>} Parsed response.\n */\nconst parseJsonAndNormalizeError = ( response ) => {\n\tconst invalidJsonError = {\n\t\tcode: 'invalid_json',\n\t\tmessage: __( 'The response is not a valid JSON response.' ),\n\t};\n\n\tif ( ! response || ! response.json ) {\n\t\tthrow invalidJsonError;\n\t}\n\n\treturn response.json().catch( () => {\n\t\tthrow invalidJsonError;\n\t} );\n};\n\n/**\n * Parses the apiFetch response properly and normalize response errors.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n *\n * @return {Promise<any>} Parsed response.\n */\nexport const parseResponseAndNormalizeError = (\n\tresponse,\n\tshouldParseResponse = true\n) => {\n\treturn Promise.resolve(\n\t\tparseResponse( response, shouldParseResponse )\n\t).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) );\n};\n\n/**\n * Parses a response, throwing an error if parsing the response fails.\n *\n * @param {Response} response\n * @param {boolean} shouldParseResponse\n * @return {Promise<any>} Parsed response.\n */\nexport function parseAndThrowError( response, shouldParseResponse = true ) {\n\tif ( ! shouldParseResponse ) {\n\t\tthrow response;\n\t}\n\n\treturn parseJsonAndNormalizeError( response ).then( ( error ) => {\n\t\tconst unknownError = {\n\t\t\tcode: 'unknown_error',\n\t\t\tmessage: __( 'An unknown error occurred.' ),\n\t\t};\n\n\t\tthrow error || unknownError;\n\t} );\n}\n"],"mappings":";;;;;;;AAGA,IAAAA,KAAA,GAAAC,OAAA;AAHA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMC,aAAa,GAAGA,CAAEC,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,KAAM;EACjE,IAAKA,mBAAmB,EAAG;IAC1B,IAAKD,QAAQ,CAACE,MAAM,KAAK,GAAG,EAAG;MAC9B,OAAO,IAAI;IACZ;IAEA,OAAOF,QAAQ,CAACG,IAAI,GAAGH,QAAQ,CAACG,IAAI,CAAC,CAAC,GAAGC,OAAO,CAACC,MAAM,CAAEL,QAAS,CAAC;EACpE;EAEA,OAAOA,QAAQ;AAChB,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA,MAAMM,0BAA0B,GAAKN,QAAQ,IAAM;EAClD,MAAMO,gBAAgB,GAAG;IACxBC,IAAI,EAAE,cAAc;IACpBC,OAAO,EAAE,IAAAC,QAAE,EAAE,4CAA6C;EAC3D,CAAC;EAED,IAAK,CAAEV,QAAQ,IAAI,CAAEA,QAAQ,CAACG,IAAI,EAAG;IACpC,MAAMI,gBAAgB;EACvB;EAEA,OAAOP,QAAQ,CAACG,IAAI,CAAC,CAAC,CAACQ,KAAK,CAAE,MAAM;IACnC,MAAMJ,gBAAgB;EACvB,CAAE,CAAC;AACJ,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,MAAMK,8BAA8B,GAAGA,CAC7CZ,QAAQ,EACRC,mBAAmB,GAAG,IAAI,KACtB;EACJ,OAAOG,OAAO,CAACS,OAAO,CACrBd,aAAa,CAAEC,QAAQ,EAAEC,mBAAoB,CAC9C,CAAC,CAACU,KAAK,CAAIG,GAAG,IAAMC,kBAAkB,CAAED,GAAG,EAAEb,mBAAoB,CAAE,CAAC;AACrE,CAAC;;AAED;AACA;AACA;AACA;AACA;AACA;AACA;AANAe,OAAA,CAAAJ,8BAAA,GAAAA,8BAAA;AAOO,SAASG,kBAAkBA,CAAEf,QAAQ,EAAEC,mBAAmB,GAAG,IAAI,EAAG;EAC1E,IAAK,CAAEA,mBAAmB,EAAG;IAC5B,MAAMD,QAAQ;EACf;EAEA,OAAOM,0BAA0B,CAAEN,QAAS,CAAC,CAACiB,IAAI,CAAIC,KAAK,IAAM;IAChE,MAAMC,YAAY,GAAG;MACpBX,IAAI,EAAE,eAAe;MACrBC,OAAO,EAAE,IAAAC,QAAE,EAAE,4BAA6B;IAC3C,CAAC;IAED,MAAMQ,KAAK,IAAIC,YAAY;EAC5B,CAAE,CAAC;AACJ","ignoreList":[]}

38
node_modules/@wordpress/api-fetch/package.json generated vendored Normal file
View File

@@ -0,0 +1,38 @@
{
"name": "@wordpress/api-fetch",
"version": "6.55.0",
"description": "Utility to make WordPress REST API requests.",
"author": "The WordPress Contributors",
"license": "GPL-2.0-or-later",
"keywords": [
"wordpress",
"gutenberg",
"rest-api",
"fetch"
],
"homepage": "https://github.com/WordPress/gutenberg/tree/HEAD/packages/api-fetch/README.md",
"repository": {
"type": "git",
"url": "https://github.com/WordPress/gutenberg.git",
"directory": "packages/api-fetch"
},
"bugs": {
"url": "https://github.com/WordPress/gutenberg/issues"
},
"engines": {
"node": ">=12"
},
"main": "build/index.js",
"module": "build-module/index.js",
"react-native": "src/index",
"types": "build-types",
"dependencies": {
"@babel/runtime": "^7.16.0",
"@wordpress/i18n": "^4.58.0",
"@wordpress/url": "^3.59.0"
},
"publishConfig": {
"access": "public"
},
"gitHead": "42f38f287506a6b3ed8ccba839b18ad066821044"
}

199
node_modules/@wordpress/api-fetch/src/index.js generated vendored Normal file
View File

@@ -0,0 +1,199 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import createNonceMiddleware from './middlewares/nonce';
import createRootURLMiddleware from './middlewares/root-url';
import createPreloadingMiddleware from './middlewares/preloading';
import fetchAllMiddleware from './middlewares/fetch-all-middleware';
import namespaceEndpointMiddleware from './middlewares/namespace-endpoint';
import httpV1Middleware from './middlewares/http-v1';
import userLocaleMiddleware from './middlewares/user-locale';
import mediaUploadMiddleware from './middlewares/media-upload';
import createThemePreviewMiddleware from './middlewares/theme-preview';
import {
parseResponseAndNormalizeError,
parseAndThrowError,
} from './utils/response';
/**
* Default set of header values which should be sent with every request unless
* explicitly provided through apiFetch options.
*
* @type {Record<string, string>}
*/
const DEFAULT_HEADERS = {
// The backend uses the Accept header as a condition for considering an
// incoming request as a REST request.
//
// See: https://core.trac.wordpress.org/ticket/44534
Accept: 'application/json, */*;q=0.1',
};
/**
* Default set of fetch option values which should be sent with every request
* unless explicitly provided through apiFetch options.
*
* @type {Object}
*/
const DEFAULT_OPTIONS = {
credentials: 'include',
};
/** @typedef {import('./types').APIFetchMiddleware} APIFetchMiddleware */
/** @typedef {import('./types').APIFetchOptions} APIFetchOptions */
/**
* @type {import('./types').APIFetchMiddleware[]}
*/
const middlewares = [
userLocaleMiddleware,
namespaceEndpointMiddleware,
httpV1Middleware,
fetchAllMiddleware,
];
/**
* Register a middleware
*
* @param {import('./types').APIFetchMiddleware} middleware
*/
function registerMiddleware( middleware ) {
middlewares.unshift( middleware );
}
/**
* Checks the status of a response, throwing the Response as an error if
* it is outside the 200 range.
*
* @param {Response} response
* @return {Response} The response if the status is in the 200 range.
*/
const checkStatus = ( response ) => {
if ( response.status >= 200 && response.status < 300 ) {
return response;
}
throw response;
};
/** @typedef {(options: import('./types').APIFetchOptions) => Promise<any>} FetchHandler*/
/**
* @type {FetchHandler}
*/
const defaultFetchHandler = ( nextOptions ) => {
const { url, path, data, parse = true, ...remainingOptions } = nextOptions;
let { body, headers } = nextOptions;
// Merge explicitly-provided headers with default values.
headers = { ...DEFAULT_HEADERS, ...headers };
// The `data` property is a shorthand for sending a JSON body.
if ( data ) {
body = JSON.stringify( data );
headers[ 'Content-Type' ] = 'application/json';
}
const responsePromise = window.fetch(
// Fall back to explicitly passing `window.location` which is the behavior if `undefined` is passed.
url || path || window.location.href,
{
...DEFAULT_OPTIONS,
...remainingOptions,
body,
headers,
}
);
return responsePromise.then(
( value ) =>
Promise.resolve( value )
.then( checkStatus )
.catch( ( response ) => parseAndThrowError( response, parse ) )
.then( ( response ) =>
parseResponseAndNormalizeError( response, parse )
),
( err ) => {
// Re-throw AbortError for the users to handle it themselves.
if ( err && err.name === 'AbortError' ) {
throw err;
}
// Otherwise, there is most likely no network connection.
// Unfortunately the message might depend on the browser.
throw {
code: 'fetch_error',
message: __( 'You are probably offline.' ),
};
}
);
};
/** @type {FetchHandler} */
let fetchHandler = defaultFetchHandler;
/**
* Defines a custom fetch handler for making the requests that will override
* the default one using window.fetch
*
* @param {FetchHandler} newFetchHandler The new fetch handler
*/
function setFetchHandler( newFetchHandler ) {
fetchHandler = newFetchHandler;
}
/**
* @template T
* @param {import('./types').APIFetchOptions} options
* @return {Promise<T>} A promise representing the request processed via the registered middlewares.
*/
function apiFetch( options ) {
// creates a nested function chain that calls all middlewares and finally the `fetchHandler`,
// converting `middlewares = [ m1, m2, m3 ]` into:
// ```
// opts1 => m1( opts1, opts2 => m2( opts2, opts3 => m3( opts3, fetchHandler ) ) );
// ```
const enhancedHandler = middlewares.reduceRight(
( /** @type {FetchHandler} */ next, middleware ) => {
return ( workingOptions ) => middleware( workingOptions, next );
},
fetchHandler
);
return enhancedHandler( options ).catch( ( error ) => {
if ( error.code !== 'rest_cookie_invalid_nonce' ) {
return Promise.reject( error );
}
// If the nonce is invalid, refresh it and try again.
return (
window
// @ts-ignore
.fetch( apiFetch.nonceEndpoint )
.then( checkStatus )
.then( ( data ) => data.text() )
.then( ( text ) => {
// @ts-ignore
apiFetch.nonceMiddleware.nonce = text;
return apiFetch( options );
} )
);
} );
}
apiFetch.use = registerMiddleware;
apiFetch.setFetchHandler = setFetchHandler;
apiFetch.createNonceMiddleware = createNonceMiddleware;
apiFetch.createPreloadingMiddleware = createPreloadingMiddleware;
apiFetch.createRootURLMiddleware = createRootURLMiddleware;
apiFetch.fetchAllMiddleware = fetchAllMiddleware;
apiFetch.mediaUploadMiddleware = mediaUploadMiddleware;
apiFetch.createThemePreviewMiddleware = createThemePreviewMiddleware;
export default apiFetch;

View File

@@ -0,0 +1,128 @@
/**
* WordPress dependencies
*/
import { addQueryArgs } from '@wordpress/url';
/**
* Internal dependencies
*/
import apiFetch from '..';
/**
* Apply query arguments to both URL and Path, whichever is present.
*
* @param {import('../types').APIFetchOptions} props
* @param {Record<string, string | number>} queryArgs
* @return {import('../types').APIFetchOptions} The request with the modified query args
*/
const modifyQuery = ( { path, url, ...options }, queryArgs ) => ( {
...options,
url: url && addQueryArgs( url, queryArgs ),
path: path && addQueryArgs( path, queryArgs ),
} );
/**
* Duplicates parsing functionality from apiFetch.
*
* @param {Response} response
* @return {Promise<any>} Parsed response json.
*/
const parseResponse = ( response ) =>
response.json ? response.json() : Promise.reject( response );
/**
* @param {string | null} linkHeader
* @return {{ next?: string }} The parsed link header.
*/
const parseLinkHeader = ( linkHeader ) => {
if ( ! linkHeader ) {
return {};
}
const match = linkHeader.match( /<([^>]+)>; rel="next"/ );
return match
? {
next: match[ 1 ],
}
: {};
};
/**
* @param {Response} response
* @return {string | undefined} The next page URL.
*/
const getNextPageUrl = ( response ) => {
const { next } = parseLinkHeader( response.headers.get( 'link' ) );
return next;
};
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request contains an unbounded query.
*/
const requestContainsUnboundedQuery = ( options ) => {
const pathIsUnbounded =
!! options.path && options.path.indexOf( 'per_page=-1' ) !== -1;
const urlIsUnbounded =
!! options.url && options.url.indexOf( 'per_page=-1' ) !== -1;
return pathIsUnbounded || urlIsUnbounded;
};
/**
* The REST API enforces an upper limit on the per_page option. To handle large
* collections, apiFetch consumers can pass `per_page=-1`; this middleware will
* then recursively assemble a full response array from all available pages.
*
* @type {import('../types').APIFetchMiddleware}
*/
const fetchAllMiddleware = async ( options, next ) => {
if ( options.parse === false ) {
// If a consumer has opted out of parsing, do not apply middleware.
return next( options );
}
if ( ! requestContainsUnboundedQuery( options ) ) {
// If neither url nor path is requesting all items, do not apply middleware.
return next( options );
}
// Retrieve requested page of results.
const response = await apiFetch( {
...modifyQuery( options, {
per_page: 100,
} ),
// Ensure headers are returned for page 1.
parse: false,
} );
const results = await parseResponse( response );
if ( ! Array.isArray( results ) ) {
// We have no reliable way of merging non-array results.
return results;
}
let nextPage = getNextPageUrl( response );
if ( ! nextPage ) {
// There are no further pages to request.
return results;
}
// Iteratively fetch all remaining pages until no "next" header is found.
let mergedResults = /** @type {any[]} */ ( [] ).concat( results );
while ( nextPage ) {
const nextResponse = await apiFetch( {
...options,
// Ensure the URL for the next page is used instead of any provided path.
path: undefined,
url: nextPage,
// Ensure we still get headers so we can identify the next page.
parse: false,
} );
const nextResults = await parseResponse( nextResponse );
mergedResults = mergedResults.concat( nextResults );
nextPage = getNextPageUrl( nextResponse );
}
return mergedResults;
};
export default fetchAllMiddleware;

View File

@@ -0,0 +1,43 @@
/**
* Set of HTTP methods which are eligible to be overridden.
*
* @type {Set<string>}
*/
const OVERRIDE_METHODS = new Set( [ 'PATCH', 'PUT', 'DELETE' ] );
/**
* Default request method.
*
* "A request has an associated method (a method). Unless stated otherwise it
* is `GET`."
*
* @see https://fetch.spec.whatwg.org/#requests
*
* @type {string}
*/
const DEFAULT_METHOD = 'GET';
/**
* API Fetch middleware which overrides the request method for HTTP v1
* compatibility leveraging the REST API X-HTTP-Method-Override header.
*
* @type {import('../types').APIFetchMiddleware}
*/
const httpV1Middleware = ( options, next ) => {
const { method = DEFAULT_METHOD } = options;
if ( OVERRIDE_METHODS.has( method.toUpperCase() ) ) {
options = {
...options,
headers: {
...options.headers,
'X-HTTP-Method-Override': method,
'Content-Type': 'application/json',
},
method: 'POST',
};
}
return next( options );
};
export default httpV1Middleware;

View File

@@ -0,0 +1,94 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Internal dependencies
*/
import {
parseAndThrowError,
parseResponseAndNormalizeError,
} from '../utils/response';
/**
* @param {import('../types').APIFetchOptions} options
* @return {boolean} True if the request is for media upload.
*/
function isMediaUploadRequest( options ) {
const isCreateMethod = !! options.method && options.method === 'POST';
const isMediaEndpoint =
( !! options.path && options.path.indexOf( '/wp/v2/media' ) !== -1 ) ||
( !! options.url && options.url.indexOf( '/wp/v2/media' ) !== -1 );
return isMediaEndpoint && isCreateMethod;
}
/**
* Middleware handling media upload failures and retries.
*
* @type {import('../types').APIFetchMiddleware}
*/
const mediaUploadMiddleware = ( options, next ) => {
if ( ! isMediaUploadRequest( options ) ) {
return next( options );
}
let retries = 0;
const maxRetries = 5;
/**
* @param {string} attachmentId
* @return {Promise<any>} Processed post response.
*/
const postProcess = ( attachmentId ) => {
retries++;
return next( {
path: `/wp/v2/media/${ attachmentId }/post-process`,
method: 'POST',
data: { action: 'create-image-subsizes' },
parse: false,
} ).catch( () => {
if ( retries < maxRetries ) {
return postProcess( attachmentId );
}
next( {
path: `/wp/v2/media/${ attachmentId }?force=true`,
method: 'DELETE',
} );
return Promise.reject();
} );
};
return next( { ...options, parse: false } )
.catch( ( response ) => {
const attachmentId = response.headers.get(
'x-wp-upload-attachment-id'
);
if (
response.status >= 500 &&
response.status < 600 &&
attachmentId
) {
return postProcess( attachmentId ).catch( () => {
if ( options.parse !== false ) {
return Promise.reject( {
code: 'post_process',
message: __(
'Media upload failed. If this is a photo or a large image, please scale it down and try again.'
),
} );
}
return Promise.reject( response );
} );
}
return parseAndThrowError( response, options.parse );
} )
.then( ( response ) =>
parseResponseAndNormalizeError( response, options.parse )
);
};
export default mediaUploadMiddleware;

View File

@@ -0,0 +1,30 @@
/**
* @type {import('../types').APIFetchMiddleware}
*/
const namespaceAndEndpointMiddleware = ( options, next ) => {
let path = options.path;
let namespaceTrimmed, endpointTrimmed;
if (
typeof options.namespace === 'string' &&
typeof options.endpoint === 'string'
) {
namespaceTrimmed = options.namespace.replace( /^\/|\/$/g, '' );
endpointTrimmed = options.endpoint.replace( /^\//, '' );
if ( endpointTrimmed ) {
path = namespaceTrimmed + '/' + endpointTrimmed;
} else {
path = namespaceTrimmed;
}
}
delete options.namespace;
delete options.endpoint;
return next( {
...options,
path,
} );
};
export default namespaceAndEndpointMiddleware;

View File

@@ -0,0 +1,37 @@
/**
* @param {string} nonce
* @return {import('../types').APIFetchMiddleware & { nonce: string }} A middleware to enhance a request with a nonce.
*/
function createNonceMiddleware( nonce ) {
/**
* @type {import('../types').APIFetchMiddleware & { nonce: string }}
*/
const middleware = ( options, next ) => {
const { headers = {} } = options;
// If an 'X-WP-Nonce' header (or any case-insensitive variation
// thereof) was specified, no need to add a nonce header.
for ( const headerName in headers ) {
if (
headerName.toLowerCase() === 'x-wp-nonce' &&
headers[ headerName ] === middleware.nonce
) {
return next( options );
}
}
return next( {
...options,
headers: {
...headers,
'X-WP-Nonce': middleware.nonce,
},
} );
};
middleware.nonce = nonce;
return middleware;
}
export default createNonceMiddleware;

View File

@@ -0,0 +1,82 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, getQueryArgs, normalizePath } from '@wordpress/url';
/**
* @param {Record<string, any>} preloadedData
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
function createPreloadingMiddleware( preloadedData ) {
const cache = Object.fromEntries(
Object.entries( preloadedData ).map( ( [ path, data ] ) => [
normalizePath( path ),
data,
] )
);
return ( options, next ) => {
const { parse = true } = options;
/** @type {string | void} */
let rawPath = options.path;
if ( ! rawPath && options.url ) {
const { rest_route: pathFromQuery, ...queryArgs } = getQueryArgs(
options.url
);
if ( typeof pathFromQuery === 'string' ) {
rawPath = addQueryArgs( pathFromQuery, queryArgs );
}
}
if ( typeof rawPath !== 'string' ) {
return next( options );
}
const method = options.method || 'GET';
const path = normalizePath( rawPath );
if ( 'GET' === method && cache[ path ] ) {
const cacheData = cache[ path ];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[ path ];
return prepareResponse( cacheData, !! parse );
} else if (
'OPTIONS' === method &&
cache[ method ] &&
cache[ method ][ path ]
) {
const cacheData = cache[ method ][ path ];
// Unsetting the cache key ensures that the data is only used a single time.
delete cache[ method ][ path ];
return prepareResponse( cacheData, !! parse );
}
return next( options );
};
}
/**
* This is a helper function that sends a success response.
*
* @param {Record<string, any>} responseData
* @param {boolean} parse
* @return {Promise<any>} Promise with the response.
*/
function prepareResponse( responseData, parse ) {
return Promise.resolve(
parse
? responseData.body
: new window.Response( JSON.stringify( responseData.body ), {
status: 200,
statusText: 'OK',
headers: responseData.headers,
} )
);
}
export default createPreloadingMiddleware;

View File

@@ -0,0 +1,44 @@
/**
* Internal dependencies
*/
import namespaceAndEndpointMiddleware from './namespace-endpoint';
/**
* @param {string} rootURL
* @return {import('../types').APIFetchMiddleware} Root URL middleware.
*/
const createRootURLMiddleware = ( rootURL ) => ( options, next ) => {
return namespaceAndEndpointMiddleware( options, ( optionsWithPath ) => {
let url = optionsWithPath.url;
let path = optionsWithPath.path;
let apiRoot;
if ( typeof path === 'string' ) {
apiRoot = rootURL;
if ( -1 !== rootURL.indexOf( '?' ) ) {
path = path.replace( '?', '&' );
}
path = path.replace( /^\//, '' );
// API root may already include query parameter prefix if site is
// configured to use plain permalinks.
if (
'string' === typeof apiRoot &&
-1 !== apiRoot.indexOf( '?' )
) {
path = path.replace( '?', '&' );
}
url = apiRoot + path;
}
return next( {
...optionsWithPath,
url,
} );
} );
};
export default createRootURLMiddleware;

View File

@@ -0,0 +1,54 @@
describe( 'Fetch All Middleware', () => {
beforeEach( jest.resetModules );
it( 'should defer with the same options to the next middleware', async () => {
expect.hasAssertions();
const originalOptions = { path: '/posts' };
const next = ( options ) => {
expect( options ).toBe( originalOptions );
return Promise.resolve( 'ok' );
};
await require( '../fetch-all-middleware' ).default(
originalOptions,
next
);
} );
it( 'should paginate the request', async () => {
expect.hasAssertions();
const originalOptions = { url: '/posts?per_page=-1' };
let counter = 1;
jest.doMock( '../../index.js', () => ( options ) => {
const expectedUrl =
counter === 1
? '/posts?per_page=100'
: '/posts?per_page=100&page=2';
expect( options.url ).toBe( expectedUrl );
const response = Promise.resolve( {
status: 200,
headers: {
get() {
return options.url === '/posts?per_page=100'
? '</posts?per_page=100&page=2>; rel="next"'
: '';
},
},
json() {
return Promise.resolve( [ 'item' ] );
},
} );
counter++;
return response;
} );
const result = await require( '../fetch-all-middleware' ).default(
originalOptions,
() => {}
);
expect( result ).toEqual( [ 'item', 'item' ] );
} );
} );

View File

@@ -0,0 +1,39 @@
/**
* Internal dependencies
*/
import httpV1Middleware from '../http-v1';
describe( 'HTTP v1 Middleware', () => {
it( 'should use a POST for a PUT requests', () => {
expect.hasAssertions();
const callback = ( options ) => {
expect( options.method ).toBe( 'POST' );
expect( options.headers[ 'X-HTTP-Method-Override' ] ).toBe( 'PUT' );
};
httpV1Middleware( { method: 'PUT', data: {} }, callback );
} );
it( "shouldn't touch the options for GET requests", () => {
expect.hasAssertions();
const requestOptions = { method: 'GET', path: '/wp/v2/posts' };
const callback = ( options ) => {
expect( options ).toBe( requestOptions );
};
httpV1Middleware( requestOptions, callback );
} );
it( "shouldn't touch the options for an undefined method", () => {
expect.hasAssertions();
const requestOptions = { path: '/wp/v2/posts' };
const callback = ( options ) => {
expect( options ).toBe( requestOptions );
};
httpV1Middleware( requestOptions, callback );
} );
} );

View File

@@ -0,0 +1,35 @@
/**
* Internal dependencies
*/
import mediaUploadMiddleware from '../media-upload';
describe( 'Media Upload Middleware', () => {
it( 'should defer to the next middleware with the same options', () => {
expect.hasAssertions();
const originalOptions = { path: '/wp/v2/media' };
const next = ( options ) => {
expect( options ).toBe( originalOptions );
};
mediaUploadMiddleware( originalOptions, next );
} );
it( 'should change options not to parse', () => {
expect.hasAssertions();
const requestOptions = { method: 'POST', path: '/wp/v2/media' };
const next = ( options ) => {
expect( options.parse ).toBe( false );
return Promise.resolve( {
status: 200,
json() {
return Promise.resolve( [ 'item' ] );
},
} );
};
mediaUploadMiddleware( requestOptions, next );
} );
} );

View File

@@ -0,0 +1,23 @@
/**
* Internal dependencies
*/
import namespaceEndpointMiddleware from '../namespace-endpoint';
describe( 'Namespace & Endpoint middleware', () => {
it( 'should concat the endpoint and namespace into a path property', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
namespace: '/wp/v2',
endpoint: '/posts',
};
const callback = ( options ) => {
expect( options.path ).toBe( 'wp/v2/posts' );
expect( options.namespace ).toBeUndefined();
expect( options.endpoint ).toBeUndefined();
};
namespaceEndpointMiddleware( requestOptions, callback );
} );
} );

View File

@@ -0,0 +1,40 @@
/**
* Internal dependencies
*/
import createNonceMiddleware from '../nonce';
describe( 'Nonce middleware', () => {
it( 'should add a nonce header to the request', () => {
expect.hasAssertions();
const nonce = 'nonce';
const nonceMiddleware = createNonceMiddleware( nonce );
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts',
};
const callback = ( options ) => {
expect( options.headers[ 'X-WP-Nonce' ] ).toBe( nonce );
};
nonceMiddleware( requestOptions, callback );
} );
it( 'should update the nonce in requests with outdated nonces', () => {
expect.hasAssertions();
const nonce = 'new nonce';
const nonceMiddleware = createNonceMiddleware( nonce );
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts',
headers: { 'X-WP-Nonce': 'existing nonce' },
};
const callback = ( options ) => {
expect( options.headers[ 'X-WP-Nonce' ] ).toBe( 'new nonce' );
};
nonceMiddleware( requestOptions, callback );
} );
} );

View File

@@ -0,0 +1,291 @@
/**
* Internal dependencies
*/
import createPreloadingMiddleware from '../preloading';
describe( 'Preloading Middleware', () => {
describe( 'given preloaded data', () => {
describe( 'when data is requested from a preloaded endpoint', () => {
describe( 'and it is requested for the first time', () => {
it( 'should return the preloaded data', () => {
const body = {
status: 'this is the preloaded response',
};
const preloadedData = {
'wp/v2/posts': {
body,
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'GET',
path: 'wp/v2/posts',
};
const response = preloadingMiddleware( requestOptions );
return response.then( ( value ) => {
expect( value ).toEqual( body );
} );
} );
} );
describe( 'and it has already been requested', () => {
it( 'should not return the preloaded data', () => {
const body = {
status: 'this is the preloaded response',
};
const preloadedData = {
'wp/v2/posts': {
body,
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'GET',
path: 'wp/v2/posts',
};
const nextSpy = jest.fn();
preloadingMiddleware( requestOptions, nextSpy );
expect( nextSpy ).not.toHaveBeenCalled();
preloadingMiddleware( requestOptions, nextSpy );
expect( nextSpy ).toHaveBeenCalled();
} );
} );
describe( 'and the OPTIONS request has a parse flag', () => {
it( 'should return the full response if parse: false', () => {
const noResponseMock =
'undefined' === typeof window.Response;
if ( noResponseMock ) {
window.Response = class {
constructor( body, options ) {
this.body = JSON.parse( body );
this.headers = options.headers;
}
};
}
const data = {
body: {
status: 'this is the preloaded response',
},
headers: {
Allow: 'GET, POST',
},
};
const preloadedData = {
OPTIONS: {
'wp/v2/posts': data,
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'OPTIONS',
path: 'wp/v2/posts',
parse: false,
};
const response = preloadingMiddleware( requestOptions );
if ( noResponseMock ) {
delete window.Response;
}
return response.then( ( value ) => {
expect( value ).toEqual( data );
} );
} );
it( 'should return only the response body if parse: true', () => {
const body = {
status: 'this is the preloaded response',
};
const preloadedData = {
OPTIONS: {
'wp/v2/posts': {
body,
headers: {
Allow: 'GET, POST',
},
},
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'OPTIONS',
path: 'wp/v2/posts',
parse: true,
};
const response = preloadingMiddleware( requestOptions );
return response.then( ( value ) => {
expect( value ).toEqual( body );
} );
} );
} );
} );
describe( 'when the requested data is not from a preloaded endpoint', () => {
it( 'should not return preloaded data', () => {
const body = {
status: 'this is the preloaded response',
};
const preloadedData = {
'wp/v2/posts': {
body,
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'GET',
path: 'wp/v2/fake_resource',
};
const nextSpy = jest.fn();
preloadingMiddleware( requestOptions, nextSpy );
expect( nextSpy ).toHaveBeenCalled();
} );
} );
} );
it( 'should normalize on stable path', async () => {
const body = { content: 'example' };
const preloadedData = {
'wp/v2/demo-reverse-alphabetical?foo=bar&baz=quux': { body },
'wp/v2/demo-alphabetical?baz=quux&foo=bar': { body },
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
let requestOptions = {
method: 'GET',
path: 'wp/v2/demo-reverse-alphabetical?baz=quux&foo=bar',
};
let value = await preloadingMiddleware( requestOptions, () => {} );
expect( value ).toEqual( body );
requestOptions = {
method: 'GET',
path: 'wp/v2/demo-alphabetical?foo=bar&baz=quux',
};
value = await preloadingMiddleware( requestOptions, () => {} );
expect( value ).toEqual( body );
} );
it( 'should recognize an urlencoded query param', async () => {
const body = { foo: 'foo', bar: 'bar' };
const preloadingMiddleware = createPreloadingMiddleware( {
'/?_fields=foo,bar': { body },
} );
const response = await preloadingMiddleware(
{
method: 'GET',
path: '/?_fields=foo%2Cbar',
},
() => {}
);
expect( response ).toEqual( body );
} );
it( 'should recognize rest_route query param as path', async () => {
const body = { foo: 'foo' };
const preloadingMiddleware = createPreloadingMiddleware( {
'/': { body },
} );
const response = await preloadingMiddleware(
{
method: 'GET',
url: '/index.php?rest_route=%2F',
},
() => {}
);
expect( response ).toEqual( body );
} );
it( 'should recognize additional query params after rest_route', async () => {
const body = { foo: 'foo', bar: 'bar' };
const preloadingMiddleware = createPreloadingMiddleware( {
'/?_fields=foo,bar': { body },
} );
const response = await preloadingMiddleware(
{
method: 'GET',
url: '/index.php?rest_route=%2F&_fields=foo%2Cbar',
},
() => {}
);
expect( response ).toEqual( body );
} );
it( 'should remove OPTIONS type requests from the cache after the first hit', async () => {
const body = { content: 'example' };
const preloadedData = {
OPTIONS: {
'wp/v2/demo': { body },
},
};
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method: 'OPTIONS',
path: 'wp/v2/demo',
};
const firstMiddleware = jest.fn();
preloadingMiddleware( requestOptions, firstMiddleware );
expect( firstMiddleware ).not.toHaveBeenCalled();
await preloadingMiddleware( requestOptions, firstMiddleware );
const secondMiddleware = jest.fn();
await preloadingMiddleware( requestOptions, secondMiddleware );
expect( secondMiddleware ).toHaveBeenCalledTimes( 1 );
} );
describe.each( [ [ 'GET' ], [ 'OPTIONS' ] ] )( '%s', ( method ) => {
describe.each( [
[ 'all empty', {} ],
[ 'method empty', { [ method ]: {} } ],
] )( '%s', ( label, preloadedData ) => {
it( 'should move to the next middleware if no preloaded data', () => {
const preloadingMiddleware =
createPreloadingMiddleware( preloadedData );
const requestOptions = {
method,
path: 'wp/v2/posts',
};
const callback = ( options ) => {
expect( options ).toBe( requestOptions );
return true;
};
const ret = preloadingMiddleware( requestOptions, callback );
expect( ret ).toBe( true );
} );
} );
} );
} );

View File

@@ -0,0 +1,24 @@
/**
* Internal dependencies
*/
import createRootUrlMiddleware from '../root-url';
describe( 'Root URL middleware', () => {
it( 'should append the root URL', () => {
expect.hasAssertions();
const rootURL = 'http://wp.org/wp-admin/rest/';
const rootURLMiddleware = createRootUrlMiddleware( rootURL );
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts',
};
const callback = ( options ) => {
expect( options.url ).toBe(
'http://wp.org/wp-admin/rest/wp/v2/posts'
);
};
rootURLMiddleware( requestOptions, callback );
} );
} );

View File

@@ -0,0 +1,134 @@
/**
* Internal dependencies
*/
import userLocaleMiddleware from '../user-locale';
describe( 'User locale middleware', () => {
it( 'should append the _locale parameter to the path', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts',
};
const callback = ( options ) => {
expect( options.path ).toBe( '/wp/v2/posts?_locale=user' );
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'should append the _locale parameter to path with existing query argument', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts?foo=bar',
};
const callback = ( options ) => {
expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=user' );
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'does not modify existing single _locale parameter in path', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts?_locale=foo',
};
const callback = ( options ) => {
expect( options.path ).toBe( '/wp/v2/posts?_locale=foo' );
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'does not modify existing _locale parameter in path', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
path: '/wp/v2/posts?foo=bar&_locale=foo',
};
const callback = ( options ) => {
expect( options.path ).toBe( '/wp/v2/posts?foo=bar&_locale=foo' );
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'should append the _locale parameter to the url', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
url: 'http://wp.org/wp-json/wp/v2/posts',
};
const callback = ( options ) => {
expect( options.url ).toBe(
'http://wp.org/wp-json/wp/v2/posts?_locale=user'
);
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'should append the _locale parameter to url with existing query argument', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar',
};
const callback = ( options ) => {
expect( options.url ).toBe(
'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=user'
);
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'does not modify existing single _locale parameter in url', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
url: 'http://wp.org/wp-json/wp/v2/posts?_locale=foo',
};
const callback = ( options ) => {
expect( options.url ).toBe(
'http://wp.org/wp-json/wp/v2/posts?_locale=foo'
);
};
userLocaleMiddleware( requestOptions, callback );
} );
it( 'does not modify existing _locale parameter in url', () => {
expect.hasAssertions();
const requestOptions = {
method: 'GET',
url: 'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo',
};
const callback = ( options ) => {
expect( options.url ).toBe(
'http://wp.org/wp-json/wp/v2/posts?foo=bar&_locale=foo'
);
};
userLocaleMiddleware( requestOptions, callback );
} );
} );

View File

@@ -0,0 +1,42 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, getQueryArg, removeQueryArgs } from '@wordpress/url';
/**
* This appends a `wp_theme_preview` parameter to the REST API request URL if
* the admin URL contains a `theme` GET parameter.
*
* If the REST API request URL has contained the `wp_theme_preview` parameter as `''`,
* then bypass this middleware.
*
* @param {Record<string, any>} themePath
* @return {import('../types').APIFetchMiddleware} Preloading middleware.
*/
const createThemePreviewMiddleware = ( themePath ) => ( options, next ) => {
if ( typeof options.url === 'string' ) {
const wpThemePreview = getQueryArg( options.url, 'wp_theme_preview' );
if ( wpThemePreview === undefined ) {
options.url = addQueryArgs( options.url, {
wp_theme_preview: themePath,
} );
} else if ( wpThemePreview === '' ) {
options.url = removeQueryArgs( options.url, 'wp_theme_preview' );
}
}
if ( typeof options.path === 'string' ) {
const wpThemePreview = getQueryArg( options.path, 'wp_theme_preview' );
if ( wpThemePreview === undefined ) {
options.path = addQueryArgs( options.path, {
wp_theme_preview: themePath,
} );
} else if ( wpThemePreview === '' ) {
options.path = removeQueryArgs( options.path, 'wp_theme_preview' );
}
}
return next( options );
};
export default createThemePreviewMiddleware;

View File

@@ -0,0 +1,27 @@
/**
* WordPress dependencies
*/
import { addQueryArgs, hasQueryArg } from '@wordpress/url';
/**
* @type {import('../types').APIFetchMiddleware}
*/
const userLocaleMiddleware = ( options, next ) => {
if (
typeof options.url === 'string' &&
! hasQueryArg( options.url, '_locale' )
) {
options.url = addQueryArgs( options.url, { _locale: 'user' } );
}
if (
typeof options.path === 'string' &&
! hasQueryArg( options.path, '_locale' )
) {
options.path = addQueryArgs( options.path, { _locale: 'user' } );
}
return next( options );
};
export default userLocaleMiddleware;

291
node_modules/@wordpress/api-fetch/src/test/index.js generated vendored Normal file
View File

@@ -0,0 +1,291 @@
/**
* Internal dependencies
*/
import apiFetch from '../';
/**
* Mock return value for a successful fetch JSON return value.
*
* @return {Promise} Mock return value.
*/
const DEFAULT_FETCH_MOCK_RETURN = Promise.resolve( {
status: 200,
json: () => Promise.resolve( {} ),
} );
describe( 'apiFetch', () => {
const originalFetch = window.fetch;
beforeEach( () => {
window.fetch = jest.fn();
} );
afterAll( () => {
window.fetch = originalFetch;
} );
it( 'should call the API properly', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 200,
json() {
return Promise.resolve( { message: 'ok' } );
},
} )
);
return apiFetch( { path: '/random' } ).then( ( body ) => {
expect( body ).toEqual( { message: 'ok' } );
} );
} );
it( 'should fetch with non-JSON body', () => {
window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN );
const body = 'FormData';
apiFetch( {
path: '/wp/v2/media',
method: 'POST',
body,
} );
expect( window.fetch ).toHaveBeenCalledWith(
'/wp/v2/media?_locale=user',
{
credentials: 'include',
headers: {
Accept: 'application/json, */*;q=0.1',
},
method: 'POST',
body,
}
);
} );
it( 'should fetch with a JSON body', () => {
window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN );
apiFetch( {
path: '/wp/v2/posts',
method: 'POST',
headers: {
'Content-Type': 'text/plain',
},
data: {},
} );
expect( window.fetch ).toHaveBeenCalledWith(
'/wp/v2/posts?_locale=user',
{
body: '{}',
credentials: 'include',
headers: {
Accept: 'application/json, */*;q=0.1',
'Content-Type': 'application/json',
},
method: 'POST',
}
);
} );
it( 'should respect developer-provided options', () => {
window.fetch.mockReturnValue( DEFAULT_FETCH_MOCK_RETURN );
apiFetch( {
path: '/wp/v2/posts',
method: 'POST',
data: {},
credentials: 'omit',
} );
expect( window.fetch ).toHaveBeenCalledWith(
'/wp/v2/posts?_locale=user',
{
body: '{}',
credentials: 'omit',
headers: {
Accept: 'application/json, */*;q=0.1',
'Content-Type': 'application/json',
},
method: 'POST',
}
);
} );
it( 'should return the error message properly', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 400,
json() {
return Promise.resolve( {
code: 'bad_request',
message: 'Bad Request',
} );
},
} )
);
return apiFetch( { path: '/random' } ).catch( ( body ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( body ).toEqual( {
code: 'bad_request',
message: 'Bad Request',
} );
} );
} );
it( 'should return invalid JSON error if no json response', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 200,
} )
);
return apiFetch( { path: '/random' } ).catch( ( body ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( body ).toEqual( {
code: 'invalid_json',
message: 'The response is not a valid JSON response.',
} );
} );
} );
it( 'should return invalid JSON error if response is not valid', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 200,
json() {
return Promise.reject();
},
} )
);
return apiFetch( { path: '/random' } ).catch( ( body ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( body ).toEqual( {
code: 'invalid_json',
message: 'The response is not a valid JSON response.',
} );
} );
} );
it( 'should return offline error when fetch errors', () => {
window.fetch.mockReturnValue( Promise.reject() );
return apiFetch( { path: '/random' } ).catch( ( body ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( body ).toEqual( {
code: 'fetch_error',
message: 'You are probably offline.',
} );
} );
} );
it( 'should throw AbortError when fetch aborts', async () => {
const abortError = new Error();
abortError.name = 'AbortError';
abortError.code = 20;
window.fetch.mockReturnValue( Promise.reject( abortError ) );
const controller = new window.AbortController();
const promise = apiFetch( {
path: '/random',
signal: controller.signal,
} );
controller.abort();
let error;
try {
await promise;
} catch ( err ) {
error = err;
}
expect( error.name ).toBe( 'AbortError' );
} );
it( 'should return null if response has no content status code', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 204,
} )
);
return apiFetch( { path: '/random' } ).catch( ( body ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( body ).toEqual( null );
} );
} );
it( 'should not try to parse the response', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 200,
} )
);
return apiFetch( { path: '/random', parse: false } ).then(
( response ) => {
expect( response ).toEqual( {
status: 200,
} );
}
);
} );
it( 'should not try to parse the error', () => {
window.fetch.mockReturnValue(
Promise.resolve( {
status: 400,
} )
);
return apiFetch( { path: '/random', parse: false } ).catch(
( response ) => {
// eslint-disable-next-line jest/no-conditional-expect
expect( response ).toEqual( {
status: 400,
} );
}
);
} );
it( 'should not use the default fetch handler when using a custom fetch handler', () => {
const customFetchHandler = jest.fn();
apiFetch.setFetchHandler( customFetchHandler );
apiFetch( { path: '/random' } );
expect( window.fetch ).not.toHaveBeenCalled();
expect( customFetchHandler ).toHaveBeenCalledWith( {
path: '/random?_locale=user',
} );
} );
it( 'should run the last-registered user-defined middleware first', () => {
// This could potentially impact other tests in that a lingering
// middleware is left. For the purposes of this test, it is sufficient
// to ensure that the last-registered middleware receives the original
// options object. It also assumes that some built-in middleware would
// either mutate or clone the original options if the extra middleware
// had been pushed to the stack.
expect.assertions( 1 );
const expectedOptions = {};
apiFetch.use( ( actualOptions, next ) => {
expect( actualOptions ).toBe( expectedOptions );
return next( actualOptions );
} );
apiFetch( expectedOptions );
} );
} );

18
node_modules/@wordpress/api-fetch/src/types.ts generated vendored Normal file
View File

@@ -0,0 +1,18 @@
export interface APIFetchOptions extends RequestInit {
// Override headers, we only accept it as an object due to the `nonce` middleware
headers?: Record< string, string >;
path?: string;
url?: string;
/**
* @default true
*/
parse?: boolean;
data?: any;
namespace?: string;
endpoint?: string;
}
export type APIFetchMiddleware = (
options: APIFetchOptions,
next: ( nextOptions: APIFetchOptions ) => Promise< any >
) => Promise< any >;

View File

@@ -0,0 +1,85 @@
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
/**
* Parses the apiFetch response.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any> | null | Response} Parsed response.
*/
const parseResponse = ( response, shouldParseResponse = true ) => {
if ( shouldParseResponse ) {
if ( response.status === 204 ) {
return null;
}
return response.json ? response.json() : Promise.reject( response );
}
return response;
};
/**
* Calls the `json` function on the Response, throwing an error if the response
* doesn't have a json function or if parsing the json itself fails.
*
* @param {Response} response
* @return {Promise<any>} Parsed response.
*/
const parseJsonAndNormalizeError = ( response ) => {
const invalidJsonError = {
code: 'invalid_json',
message: __( 'The response is not a valid JSON response.' ),
};
if ( ! response || ! response.json ) {
throw invalidJsonError;
}
return response.json().catch( () => {
throw invalidJsonError;
} );
};
/**
* Parses the apiFetch response properly and normalize response errors.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
*
* @return {Promise<any>} Parsed response.
*/
export const parseResponseAndNormalizeError = (
response,
shouldParseResponse = true
) => {
return Promise.resolve(
parseResponse( response, shouldParseResponse )
).catch( ( res ) => parseAndThrowError( res, shouldParseResponse ) );
};
/**
* Parses a response, throwing an error if parsing the response fails.
*
* @param {Response} response
* @param {boolean} shouldParseResponse
* @return {Promise<any>} Parsed response.
*/
export function parseAndThrowError( response, shouldParseResponse = true ) {
if ( ! shouldParseResponse ) {
throw response;
}
return parseJsonAndNormalizeError( response ).then( ( error ) => {
const unknownError = {
code: 'unknown_error',
message: __( 'An unknown error occurred.' ),
};
throw error || unknownError;
} );
}

11
node_modules/@wordpress/api-fetch/tsconfig.json generated vendored Normal file
View File

@@ -0,0 +1,11 @@
{
"$schema": "https://json.schemastore.org/tsconfig.json",
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"rootDir": "src",
"declarationDir": "build-types"
},
"references": [ { "path": "../i18n" }, { "path": "../url" } ],
"include": [ "src/**/*" ],
"exclude": [ "**/test/**/*" ]
}

File diff suppressed because one or more lines are too long