@patronage/launch-wpgraphql 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ # @patronage/launch-wpgraphql
2
+
3
+ ## 0.1.1
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [1aaa0e3]
8
+ - Updated dependencies [fe5c197]
9
+ - @patronage/launch-logging@0.3.0
10
+ - @patronage/access@0.2.1
11
+
12
+ ## 0.1.0
13
+
14
+ ### Minor Changes
15
+
16
+ - b0bd828: First npm releases. `@patronage/launch-images` (formerly the private `@launch/images`) serves CMS images through the Cloudflare Images binding. `@patronage/launch-logging` publishes the Worker wide-event wrapper and the Cloudflare log-store helpers. `@patronage/launch-wpgraphql` is the framework-neutral WPGraphQL transport taken out of the headless WordPress front-end: Access service token and preview identity, persisted query IDs, Smart Cache tags, typed read errors and `upstream.wordpress` timing.
17
+
18
+ ### Patch Changes
19
+
20
+ - Updated dependencies [b0bd828]
21
+ - @patronage/launch-logging@0.1.0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Patronage
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @patronage/launch-wpgraphql
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The WordPress side of a headless front-end on Workers, with no framework code: it works under the App Router, the Pages Router or a plain Worker. [`apps/web-wordpress`](../../apps/web-wordpress) is the reference that uses it.
4
+
5
+ | Export | Use |
6
+ | --- | --- |
7
+ | `createWordPressFetch(config)` | One fetch for every WordPress request (GraphQL and original media). Sends the Cloudflare Access service token when one is configured (none for local Docker; half a token fails closed), refuses other origins, doesn't follow redirects, and throws when Access refuses. For previews, pass the editor's Access JWT as the third argument: it is verified and forwarded with a gateway proof, the `patronage-access` mu-plugin's contract. Each request counts toward `upstream.wordpress` on the wide event from `@patronage/launch-logging`. |
8
+ | `readGraphQLData(response)` | A WPGraphQL response's `data`, or a `WordPressQueryError` (`code` `http`, `graphql` or `empty`, with `status` for HTTP) so a caller that caches reads never caches a failure. |
9
+ | `persistedQueryId(document)`, `persistedQueryBody(id, variablesJson)` | Send a GraphQL Code Generator document (client preset with `persistedDocuments`) by its SHA-256, for WPGraphQL Smart Cache's registered queries. |
10
+ | `smartCacheTags(header)`, `pathTag(path)`, `WORDPRESS_CACHE_TAG` | Cache tags from a response's `X-GraphQL-Keys` (node, `list:` and `skipped:` keys only) and for a front-end path, matching what the `patronage-headless-revalidate` mu-plugin sends. |
11
+
12
+ ## Example
13
+
14
+ ```ts
15
+ import {
16
+ createWordPressFetch,
17
+ persistedQueryBody,
18
+ persistedQueryId,
19
+ readGraphQLData,
20
+ smartCacheTags,
21
+ } from "@patronage/launch-wpgraphql";
22
+
23
+ const wordpressFetch = createWordPressFetch({
24
+ origin: process.env.WORDPRESS_URL!,
25
+ accessClientId: process.env.WORDPRESS_ACCESS_CLIENT_ID,
26
+ accessClientSecret: process.env.WORDPRESS_ACCESS_CLIENT_SECRET,
27
+ });
28
+
29
+ const response = await wordpressFetch(`${process.env.WORDPRESS_URL}/graphql`, {
30
+ method: "POST",
31
+ headers: { "content-type": "application/json" },
32
+ body: persistedQueryBody(
33
+ persistedQueryId(PageQuery),
34
+ JSON.stringify({ uri })
35
+ ),
36
+ });
37
+ const data = await readGraphQLData<PageQueryResult>(response);
38
+ const tags = smartCacheTags(response.headers.get("x-graphql-keys"));
39
+ ```
40
+
41
+ Under the App Router, wrap the read in `"use cache"` and pass `tags` to `cacheTag`. Under the Pages Router, wrap it in `unstable_cache` with the same tags. Run vinext's cache on KV (`kvDataAdapter`) so a revalidation reaches every isolate.
42
+
43
+ Needs `nodejs_compat` on Workers, for the request timing's `AsyncLocalStorage`.
@@ -0,0 +1,92 @@
1
+ import { DocumentNode } from "graphql";
2
+ /**
3
+ * Every cached WordPress read carries this tag, so revalidating it expires
4
+ * every read and every page. WordPress sends it when Smart Cache purges
5
+ * everything (a settings change, "Purge Cache Now").
6
+ */
7
+ export declare const WORDPRESS_CACHE_TAG = "wordpress";
8
+ /**
9
+ * The cache tags for a WPGraphQL response: the WPGraphQL Smart Cache keys in
10
+ * its X-GraphQL-Keys header that WordPress purges when the posts, terms,
11
+ * menus or settings behind them change.
12
+ */
13
+ export declare const smartCacheTags: (header: string | null) => string[];
14
+ /**
15
+ * The tag for a front-end path, on the content read of that path. A path with
16
+ * nothing published at it has no node keys, so this tag is what replaces its
17
+ * cached "not found" when a post is published there. Trailing slashes are
18
+ * dropped, so /about/ (a WordPress URI) and /about (what WordPress sends) match,
19
+ * and percent escapes are uppercased: WordPress writes them in lowercase,
20
+ * encodeURIComponent in uppercase.
21
+ */
22
+ export declare const pathTag: (path: string) => string;
23
+ /**
24
+ * The persisted query ID of a codegen document. WPGraphQL Smart Cache runs a
25
+ * registered query by that ID, so requests never carry query text. Throws
26
+ * for a document without one.
27
+ */
28
+ export declare const persistedQueryId: (document: DocumentNode) => string;
29
+ /**
30
+ * The JSON body of a persisted query request. Variables are passed as
31
+ * already-serialized JSON so a caller that keys a cache on them serializes
32
+ * them once.
33
+ */
34
+ export declare const persistedQueryBody: (id: string, variablesJson?: string) => string;
35
+ /** Why a WPGraphQL read failed. HTTP errors carry the status. */
36
+ type WordPressQueryErrorCode = "empty" | "graphql" | "http";
37
+ /**
38
+ * A failed WPGraphQL read. Thrown for an HTTP error, a response with GraphQL
39
+ * errors, or one without data, so a caller that caches reads never caches a
40
+ * failure. The message names the status or the GraphQL error messages, never
41
+ * the query, its variables or credentials.
42
+ */
43
+ export declare class WordPressQueryError extends Error {
44
+ readonly code: WordPressQueryErrorCode;
45
+ readonly status: number | undefined;
46
+ constructor(code: WordPressQueryErrorCode, message: string, status?: number);
47
+ }
48
+ /**
49
+ * Reads a WPGraphQL response's `data`, or throws a WordPressQueryError for an
50
+ * HTTP error, GraphQL errors or a missing `data`.
51
+ */
52
+ export declare const readGraphQLData: <Result>(response: Response) => Promise<Result>;
53
+ /** Where WordPress is and how to get past Cloudflare Access to reach it. */
54
+ interface WordPressTransportConfig {
55
+ /** The WordPress origin, such as `https://cms.example.org`. */
56
+ origin: string;
57
+ /**
58
+ * The Access service token. Leave both empty for a WordPress without
59
+ * Access (local Docker); setting only one fails closed.
60
+ */
61
+ accessClientId?: string;
62
+ accessClientSecret?: string;
63
+ /** Previews only: the secret that binds a forwarded editor JWT to this front-end. */
64
+ accessProofSecret?: string;
65
+ /** Previews only: the Access team domain and the preview application's AUD. */
66
+ accessTeamDomain?: string;
67
+ accessPreviewAudience?: string;
68
+ /** The `upstream.<name>` the reads count toward on the wide event. */
69
+ upstreamName?: string;
70
+ /** Injected for tests; defaults to the global fetch. */
71
+ fetch?: typeof fetch;
72
+ }
73
+ /**
74
+ * A fetch to WordPress: `previewJwt` is the editor's Access JWT, forwarded
75
+ * with a gateway proof for preview reads. Pass undefined for public reads.
76
+ */
77
+ type WordPressFetch = (input: string, init?: RequestInit, previewJwt?: string | null) => Promise<Response>;
78
+ /**
79
+ * Builds the one transport a front-end uses for every WordPress request:
80
+ * GraphQL reads and original media alike.
81
+ *
82
+ * - Refuses URLs on any other origin, so credentials can't leak.
83
+ * - Sends the Access service token when one is configured, and turns an
84
+ * Access login redirect into an error instead of following it.
85
+ * - For previews, verifies the editor's Access JWT and forwards it with a
86
+ * gateway proof (the patronage-access mu-plugin's contract).
87
+ * - Counts each request toward `upstream.<name>` (default `wordpress`) on
88
+ * the request's wide event from `@patronage/launch-logging`. A 5xx counts as an
89
+ * error; callers still check the status themselves.
90
+ */
91
+ export declare const createWordPressFetch: (config: WordPressTransportConfig) => WordPressFetch;
92
+ export type { WordPressFetch, WordPressQueryErrorCode, WordPressTransportConfig };
package/dist/index.js ADDED
@@ -0,0 +1,147 @@
1
+ import { z } from "zod";
2
+ import { accessFetch, isAccessRejection, verifyAccessJwt } from "@patronage/access";
3
+ import { timeUpstream } from "@patronage/launch-logging";
4
+ // src/cache-tags.ts
5
+ /**
6
+ * Every cached WordPress read carries this tag, so revalidating it expires
7
+ * every read and every page. WordPress sends it when Smart Cache purges
8
+ * everything (a settings change, "Purge Cache Now").
9
+ */
10
+ const WORDPRESS_CACHE_TAG = "wordpress";
11
+ const PATH_TAG_PREFIX = "path:";
12
+ const TRAILING_SLASHES = /\/+$/u;
13
+ const PERCENT_ESCAPE = /%[\da-f]{2}/giu;
14
+ const QUERY_HASH = /^[\da-f]{64}$/u;
15
+ const WHITESPACE = /\s+/u;
16
+ /**
17
+ * Keys every response carries (the query hash, graphql:Query and
18
+ * operation:<name>) would turn any purge into a purge of everything, so only
19
+ * node keys (global IDs), list:<type> and skipped:<type> become tags.
20
+ */
21
+ const isNodeOrListKey = (key) => key.length > 0 && key !== "graphql:Query" && !key.startsWith("operation:") && !QUERY_HASH.test(key);
22
+ /**
23
+ * The cache tags for a WPGraphQL response: the WPGraphQL Smart Cache keys in
24
+ * its X-GraphQL-Keys header that WordPress purges when the posts, terms,
25
+ * menus or settings behind them change.
26
+ */
27
+ const smartCacheTags = (header) => [...new Set((header ?? "").split(WHITESPACE).filter(isNodeOrListKey))];
28
+ /**
29
+ * The tag for a front-end path, on the content read of that path. A path with
30
+ * nothing published at it has no node keys, so this tag is what replaces its
31
+ * cached "not found" when a post is published there. Trailing slashes are
32
+ * dropped, so /about/ (a WordPress URI) and /about (what WordPress sends) match,
33
+ * and percent escapes are uppercased: WordPress writes them in lowercase,
34
+ * encodeURIComponent in uppercase.
35
+ */
36
+ const pathTag = (path) => `${PATH_TAG_PREFIX}${path.replaceAll(PERCENT_ESCAPE, (escape) => escape.toUpperCase()).replace(TRAILING_SLASHES, "") || "/"}`;
37
+ // src/persisted.ts
38
+ /**
39
+ * What GraphQL Code Generator's client preset adds to a document when
40
+ * `persistedDocuments` is on: the operation's SHA-256, as `sha256:<hex>`.
41
+ */
42
+ const PersistedDocument = z.object({ __meta__: z.object({ hash: z.string().transform((hash) => hash.replace(/^sha256:/u, "")).pipe(z.string().regex(/^[\da-f]{64}$/u)) }) });
43
+ /**
44
+ * The persisted query ID of a codegen document. WPGraphQL Smart Cache runs a
45
+ * registered query by that ID, so requests never carry query text. Throws
46
+ * for a document without one.
47
+ */
48
+ const persistedQueryId = (document) => {
49
+ const parsed = PersistedDocument.safeParse(document);
50
+ if (!parsed.success) throw new TypeError("GraphQL document has no persisted query hash; run codegen with persistedDocuments.");
51
+ return parsed.data.__meta__.hash;
52
+ };
53
+ /**
54
+ * The JSON body of a persisted query request. Variables are passed as
55
+ * already-serialized JSON so a caller that keys a cache on them serializes
56
+ * them once.
57
+ */
58
+ const persistedQueryBody = (id, variablesJson = "{}") => `{"queryId":${JSON.stringify(id)},"variables":${variablesJson}}`;
59
+ // src/response.ts
60
+ /**
61
+ * A failed WPGraphQL read. Thrown for an HTTP error, a response with GraphQL
62
+ * errors, or one without data, so a caller that caches reads never caches a
63
+ * failure. The message names the status or the GraphQL error messages, never
64
+ * the query, its variables or credentials.
65
+ */
66
+ var WordPressQueryError = class extends Error {
67
+ code;
68
+ status;
69
+ constructor(code, message, status) {
70
+ super(message);
71
+ this.name = "WordPressQueryError";
72
+ this.code = code;
73
+ this.status = status;
74
+ }
75
+ };
76
+ /**
77
+ * Reads a WPGraphQL response's `data`, or throws a WordPressQueryError for an
78
+ * HTTP error, GraphQL errors or a missing `data`.
79
+ */
80
+ const readGraphQLData = async (response) => {
81
+ if (!response.ok) {
82
+ await response.body?.cancel();
83
+ throw new WordPressQueryError("http", `WPGraphQL answered ${response.status} ${response.statusText}`.trim(), response.status);
84
+ }
85
+ const body = await response.json();
86
+ if (body.errors?.length) throw new WordPressQueryError("graphql", `WPGraphQL: ${body.errors.map((error) => error.message ?? "error").join("; ")}`);
87
+ if (body.data === void 0 || body.data === null) throw new WordPressQueryError("empty", "WPGraphQL returned no data");
88
+ return body.data;
89
+ };
90
+ // src/transport.ts
91
+ const TRAILING_SLASH = /\/+$/u;
92
+ /**
93
+ * Builds the one transport a front-end uses for every WordPress request:
94
+ * GraphQL reads and original media alike.
95
+ *
96
+ * - Refuses URLs on any other origin, so credentials can't leak.
97
+ * - Sends the Access service token when one is configured, and turns an
98
+ * Access login redirect into an error instead of following it.
99
+ * - For previews, verifies the editor's Access JWT and forwards it with a
100
+ * gateway proof (the patronage-access mu-plugin's contract).
101
+ * - Counts each request toward `upstream.<name>` (default `wordpress`) on
102
+ * the request's wide event from `@patronage/launch-logging`. A 5xx counts as an
103
+ * error; callers still check the status themselves.
104
+ */
105
+ const createWordPressFetch = (config) => {
106
+ const { origin } = new URL(config.origin.replace(TRAILING_SLASH, ""));
107
+ const clientId = config.accessClientId ?? "";
108
+ const clientSecret = config.accessClientSecret ?? "";
109
+ const transport = config.fetch ?? ((input, init) => fetch(input, init));
110
+ const send = async (input, init, previewJwt) => {
111
+ if (new URL(input).origin !== origin) throw new Error("WordPress credentials cannot be sent to another origin.");
112
+ if (!(clientId || clientSecret)) return transport(input, init);
113
+ if (!(clientId && clientSecret)) throw new Error("WordPress Access service token is incomplete.");
114
+ let forward;
115
+ if (previewJwt !== void 0) {
116
+ if (!config.accessProofSecret) throw new Error("WordPress previews need the Access gateway proof secret.");
117
+ const verified = await verifyAccessJwt(previewJwt, {
118
+ audience: config.accessPreviewAudience ?? "",
119
+ teamDomain: config.accessTeamDomain ?? ""
120
+ });
121
+ if (!verified.ok || verified.identity.kind !== "user" || !previewJwt) throw new Error("WordPress previews require a verified Access user.");
122
+ forward = {
123
+ jwt: previewJwt,
124
+ proofSecret: config.accessProofSecret
125
+ };
126
+ }
127
+ const options = {
128
+ fetch: transport,
129
+ serviceToken: {
130
+ clientId,
131
+ clientSecret
132
+ }
133
+ };
134
+ if (forward) options.forward = forward;
135
+ const response = await accessFetch(input, {
136
+ ...init,
137
+ redirect: "manual"
138
+ }, options);
139
+ if (isAccessRejection(response)) {
140
+ await response.body?.cancel();
141
+ throw new Error("Cloudflare Access refused the WordPress request.");
142
+ }
143
+ return response;
144
+ };
145
+ return (input, init, previewJwt) => timeUpstream(config.upstreamName ?? "wordpress", () => send(input, init ?? {}, previewJwt), (response) => response.status >= 500);
146
+ };
147
+ export { WORDPRESS_CACHE_TAG, WordPressQueryError, createWordPressFetch, pathTag, persistedQueryBody, persistedQueryId, readGraphQLData, smartCacheTags };
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@patronage/launch-wpgraphql",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.1",
4
+ "description": "A framework-neutral WPGraphQL transport for headless WordPress front-ends on Workers: Access service tokens and preview identity, persisted query IDs, WPGraphQL Smart Cache tags, typed errors and upstream timing.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/patronage/launch.git",
9
+ "directory": "packages/wpgraphql"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "CHANGELOG.md"
14
+ ],
15
+ "type": "module",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "dependencies": {
26
+ "@patronage/access": "0.2.1",
27
+ "@patronage/launch-logging": "0.3.0",
28
+ "zod": "4.6.7"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "24.19.2",
32
+ "graphql": "17.1.0",
33
+ "tsdown": "0.23.7",
34
+ "vitest": "5.1.0"
35
+ },
36
+ "peerDependencies": {
37
+ "graphql": ">=16"
38
+ },
39
+ "engines": {
40
+ "node": ">=22.18.0"
41
+ },
42
+ "scripts": {
43
+ "build": "tsdown",
44
+ "test": "vitest run",
45
+ "typecheck": "tsc --noEmit"
46
+ }
6
47
  }