node-wpapi icon indicating copy to clipboard operation
node-wpapi copied to clipboard

Wordpress 5.9 templates endpoint regex problem

Open paussus opened this issue 3 years ago • 2 comments

Hi,

since updating to wordpress 5.9 (or 5.9.1, can't be sure) the api is not able to bootstrap with the endpoints from the json due to a regex problem. The stack trace is

SyntaxError: Invalid regular expression: /^([^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?$/: Unterminated group at new RegExp (<anonymous>) 
at reduceRouteComponents (...\node_modules\wpapi\lib\route-tree.js:84:3) 
at Array.reduce (<anonymous>) 
at reduceRouteTree (...\node_modules\wpapi\lib\route-tree.js:185:18) 
at ...\node_modules\wpapi\lib\util\object-reduce.js:25:20 at Array.reduce (<anonymous>) 
at module.exports (...\node_modules\wpapi\lib\util\object-reduce.js:24:3) 
at buildRouteTree (...\node_modules\wpapi\lib\route-tree.js:203:9) at WPAPI.bootstrap (...\node_modules\wpapi\wpapi.js:349:23) 
at new WPAPI (...\node_modules\wpapi\wpapi.js:88:4) 
at ...\node_modules\wpapi\wpapi.js:452:11 
...

The result is that the wpapi only contains the default endpoints.

The problem seems to reside in the new templates endpoint regex /wp/v2/templates/(?P<id>([^\/:<>\*\?"\|]+(?:\/[^\/:<>\*\?"\|]+)?)[\/\w-]+) that it is not correctly captured by the named group regex at reduceRouteComponents in route-tree.js . It does not capture one closing ) in namedGroup[2] and so the groupPattern is invalid and fails when building the regular expression. It can be seen in this demo https://regex101.com/r/zGr26D/1. From my understanding the problem seems to arise from the templates regular expression having 3 levels of named patterns.

I guess it happens too with the template-patterns endpoint too.

In case anyone is interested, to solve it temporarely, since I don't need these endpoints, I remove them in wordpress:

function remove_template_endpoints( $endpoints ) {
    foreach ( $endpoints as $endpoint => $details ) {
        if ( fnmatch( '/wp/v2/template*/*', $endpoint ) ) {
            unset( $endpoints[$endpoint] );
        }
    }

    return $endpoints;
}
add_filter( 'rest_endpoints', 'remove_template_endpoints' );

Thanks for the work!

paussus avatar Mar 01 '22 13:03 paussus

I'm experiencing the same issue, but I do need these endpoints for a custom integration. If I can find time, I'll see if I can update the regex pattern

samfreedman avatar Apr 03 '22 11:04 samfreedman

Is it possible to work around this by providing the routes to wpapi instead of using autodiscovery? I've never tried that and, even assuming it could work, I don't know how to do it, so I'm just asking to know if it would make sense to spend time on this kind of workaround.

lucrus73 avatar Apr 12 '22 08:04 lucrus73