@fluxwp/plugin-kit 0.0.0-stage → 0.1.0
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/README.md +97 -2
- package/dist/codegen.js +264 -0
- package/dist/flx-kit.js +476 -0
- package/dist/modules.js +19 -0
- package/dist/vite.js +152 -0
- package/package.json +63 -4
- package/runtime-exports.json +316 -0
- package/src/codegen.ts +117 -0
- package/src/css.d.ts +1 -0
- package/src/modules.ts +23 -0
- package/src/vite.ts +150 -0
- package/types/codegen.d.ts +18 -0
- package/types/modules.d.ts +8 -0
- package/types/vite.d.ts +12 -0
package/README.md
CHANGED
|
@@ -1,3 +1,98 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @fluxwp/plugin-kit
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Add wp-admin React screens to any WordPress plugin, on the same shell as FluxWP's own screens, with typed
|
|
4
|
+
GraphQL operations. Needs the **Flux GraphQL** plugin (0.5+) on the site: it serves GraphQL and loads the
|
|
5
|
+
shared runtime (React, React Query, i18next, `@fluxwp/ui`, `@fluxwp/graphql`) once per page, so your
|
|
6
|
+
bundle carries only your screens (a few KB).
|
|
7
|
+
|
|
8
|
+
## Setup
|
|
9
|
+
|
|
10
|
+
```sh
|
|
11
|
+
bun add -d @fluxwp/plugin-kit react @tanstack/react-query react-i18next typescript vite
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
```
|
|
15
|
+
my-plugin/
|
|
16
|
+
my-plugin.php flx_admin_screen() + flx_gql_persisted_manifests (below)
|
|
17
|
+
graphql/operations/FlxMyOrders.graphql
|
|
18
|
+
graphql/schema.graphql your own types, if the plugin registers any (flx-kit schema-split)
|
|
19
|
+
screens/index.ts export const screens = { 'my-orders': () => import('./Orders') … }
|
|
20
|
+
vite.config.ts
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
```ts
|
|
24
|
+
// vite.config.ts
|
|
25
|
+
import { fluxScreens } from '@fluxwp/plugin-kit/vite';
|
|
26
|
+
export default fluxScreens({ entry: 'my-plugin/screens/index.ts', outDir: 'my-plugin/assets/flux' });
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
flx-kit codegen my-plugin # → my-plugin/screens/generated/{types,operations}.ts + graphql/persisted-queries.json
|
|
31
|
+
vite build # → my-plugin/assets/flux/flux-screens.js (+ chunks, css, chunks.json)
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Screen
|
|
35
|
+
|
|
36
|
+
```tsx
|
|
37
|
+
import { useMemo } from 'react';
|
|
38
|
+
import { useTranslation } from 'react-i18next';
|
|
39
|
+
import { createGraphQLClient } from '@fluxwp/graphql';
|
|
40
|
+
import { FlxGraphQLProvider, useFlxQuery } from '@fluxwp/graphql/react';
|
|
41
|
+
import { useHost } from '@fluxwp/host';
|
|
42
|
+
import { FlxMyOrders } from './generated/operations';
|
|
43
|
+
|
|
44
|
+
export function Orders() {
|
|
45
|
+
const host = useHost();
|
|
46
|
+
const client = useMemo(() => createGraphQLClient({ api: host.client }), [host.client]);
|
|
47
|
+
return <FlxGraphQLProvider client={client} scope={host.scope}><List /></FlxGraphQLProvider>;
|
|
48
|
+
}
|
|
49
|
+
function List() {
|
|
50
|
+
const { t } = useTranslation('my');
|
|
51
|
+
const q = useFlxQuery(FlxMyOrders, {}); // typed from the schema
|
|
52
|
+
return <h1>{t('title')} ({q.data?.flxMyOrders.totalCount ?? '…'})</h1>;
|
|
53
|
+
}
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
`screens/index.ts` may also export `resources` (`{ en: { my: {…} }, tr: { my: {…} } }`) for i18next.
|
|
57
|
+
|
|
58
|
+
## PHP
|
|
59
|
+
|
|
60
|
+
```php
|
|
61
|
+
add_filter( 'flx_gql_persisted_manifests', function ( $m ) {
|
|
62
|
+
$m['my-plugin'] = __DIR__ . '/graphql/persisted-queries.json';
|
|
63
|
+
return $m;
|
|
64
|
+
} );
|
|
65
|
+
add_action( 'admin_menu', function () {
|
|
66
|
+
add_menu_page( 'Orders', 'Orders', 'read', 'my-orders', function () {
|
|
67
|
+
if ( function_exists( 'flx_admin_screen_render' ) && flx_admin_screen_render() ) return;
|
|
68
|
+
echo 'Flux GraphQL is needed for this screen.';
|
|
69
|
+
} );
|
|
70
|
+
if ( function_exists( 'flx_admin_screen' ) ) {
|
|
71
|
+
flx_admin_screen( 'my-orders', array(
|
|
72
|
+
'module' => 'my-orders',
|
|
73
|
+
'assets_dir' => __DIR__ . '/assets/flux/',
|
|
74
|
+
'assets_url' => plugin_dir_url( __FILE__ ) . 'assets/flux/',
|
|
75
|
+
'preload' => array( array( 'FlxMyOrders' ) ), // first data comes with the page
|
|
76
|
+
) );
|
|
77
|
+
}
|
|
78
|
+
}, 20 );
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Your own GraphQL types are registered in PHP with the kit (`flx_gql_type`, `flx_gql_query` … on
|
|
82
|
+
`flx_gql_register`). To type-check against them, export the site's schema with your plugin active and keep
|
|
83
|
+
your part in the plugin:
|
|
84
|
+
|
|
85
|
+
```sh
|
|
86
|
+
wp flx-gql schema --output=schema.graphql --owners=owners.json
|
|
87
|
+
flx-kit schema-split schema.graphql owners.json my-plugin # → my-plugin/graphql/schema.graphql
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
## Rules
|
|
91
|
+
|
|
92
|
+
- Import only what the runtime provides: `react`, `react/jsx-runtime`, `react-dom`, `react-dom/client`,
|
|
93
|
+
`@tanstack/react-query`, `i18next`, `react-i18next`, `@fluxwp/core`, `@fluxwp/tokens`, `@fluxwp/ui`,
|
|
94
|
+
`@fluxwp/graphql`, `@fluxwp/graphql/react`, `@fluxwp/host`. Other `@fluxwp/*` imports fail the build.
|
|
95
|
+
- Operation names start with `Flx`, one operation per file; screen ids are unique (prefix them).
|
|
96
|
+
- Your CSS is scoped under `.flux-root`; `@fluxwp/ui` styles are already on the page.
|
|
97
|
+
|
|
98
|
+
Example plugin: [`example/acme-hello`](https://github.com/FluxWP/FluxWP/tree/main/packages/plugin-kit/example).
|
package/dist/codegen.js
ADDED
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
// packages/plugin-kit/src/codegen.ts
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname, join, relative, resolve } from "node:path";
|
|
4
|
+
import { buildSchema, parse as parse3 } from "graphql";
|
|
5
|
+
import { codegen as gqlCodegen } from "@graphql-codegen/core";
|
|
6
|
+
import * as typescriptOperations from "@graphql-codegen/typescript-operations";
|
|
7
|
+
|
|
8
|
+
// packages/graphql/scripts/lib.ts
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import {
|
|
11
|
+
Kind,
|
|
12
|
+
parse,
|
|
13
|
+
print,
|
|
14
|
+
validate,
|
|
15
|
+
visit
|
|
16
|
+
} from "graphql";
|
|
17
|
+
|
|
18
|
+
class GenerateError extends Error {
|
|
19
|
+
}
|
|
20
|
+
var NAME = /^Flx[A-Z][A-Za-z0-9]*$/;
|
|
21
|
+
function collectOperations(schema, files) {
|
|
22
|
+
const problems = [];
|
|
23
|
+
const byPlugin = new Map;
|
|
24
|
+
for (const f of files) {
|
|
25
|
+
let doc;
|
|
26
|
+
try {
|
|
27
|
+
doc = parse(f.body, { noLocation: false });
|
|
28
|
+
} catch (e) {
|
|
29
|
+
problems.push(`${f.path}: ${e.message}`);
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
const entry = byPlugin.get(f.plugin) ?? { ops: [], frags: new Map };
|
|
33
|
+
byPlugin.set(f.plugin, entry);
|
|
34
|
+
for (const def of doc.definitions) {
|
|
35
|
+
if (def.kind === Kind.OPERATION_DEFINITION) {
|
|
36
|
+
if (def.operation === "subscription")
|
|
37
|
+
problems.push(`${f.path}: subscriptions are not supported`);
|
|
38
|
+
else
|
|
39
|
+
entry.ops.push({ node: def, path: f.path });
|
|
40
|
+
} else if (def.kind === Kind.FRAGMENT_DEFINITION) {
|
|
41
|
+
if (entry.frags.has(def.name.value))
|
|
42
|
+
problems.push(`${f.path}: fragment ${def.name.value} is defined twice in ${f.plugin}`);
|
|
43
|
+
entry.frags.set(def.name.value, def);
|
|
44
|
+
} else {
|
|
45
|
+
problems.push(`${f.path}: only operations and fragments belong in operation files`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const seen = new Map;
|
|
50
|
+
const out = [];
|
|
51
|
+
for (const [plugin, { ops, frags }] of byPlugin) {
|
|
52
|
+
for (const { node, path } of ops) {
|
|
53
|
+
const name = node.name?.value;
|
|
54
|
+
if (!name) {
|
|
55
|
+
problems.push(`${path}: every operation needs a name`);
|
|
56
|
+
continue;
|
|
57
|
+
}
|
|
58
|
+
if (!NAME.test(name))
|
|
59
|
+
problems.push(`${path}: operation ${name} must be PascalCase and start with "Flx"`);
|
|
60
|
+
const other = seen.get(name);
|
|
61
|
+
if (other)
|
|
62
|
+
problems.push(`${path}: operation ${name} is also defined in ${other}`);
|
|
63
|
+
seen.set(name, path);
|
|
64
|
+
const used = new Map;
|
|
65
|
+
const walk = (n) => visit(n, {
|
|
66
|
+
FragmentSpread(s) {
|
|
67
|
+
const name = s.name.value;
|
|
68
|
+
if (used.has(name))
|
|
69
|
+
return;
|
|
70
|
+
const frag = frags.get(name);
|
|
71
|
+
if (!frag) {
|
|
72
|
+
problems.push(`${path}: fragment ${name} is not defined in ${plugin}`);
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
used.set(name, frag);
|
|
76
|
+
walk(frag);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
walk(node);
|
|
80
|
+
const doc = {
|
|
81
|
+
kind: Kind.DOCUMENT,
|
|
82
|
+
definitions: [node, ...[...used.values()].sort((a, b) => a.name.value.localeCompare(b.name.value))]
|
|
83
|
+
};
|
|
84
|
+
for (const err of validate(schema, doc))
|
|
85
|
+
problems.push(`${path}: ${err.message}`);
|
|
86
|
+
const printed = print(stripLocations(doc));
|
|
87
|
+
out.push({ plugin, name, kind: node.operation, document: printed, id: sha256(printed), path });
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (problems.length)
|
|
91
|
+
throw new GenerateError(problems.join(`
|
|
92
|
+
`));
|
|
93
|
+
return out.sort((a, b) => a.name.localeCompare(b.name));
|
|
94
|
+
}
|
|
95
|
+
function stripLocations(doc) {
|
|
96
|
+
return JSON.parse(JSON.stringify(doc, (k, v) => k === "loc" ? undefined : v));
|
|
97
|
+
}
|
|
98
|
+
var sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
99
|
+
function manifests(ops) {
|
|
100
|
+
const by = new Map;
|
|
101
|
+
for (const op of ops) {
|
|
102
|
+
const m = by.get(op.plugin) ?? {};
|
|
103
|
+
m[op.id] = op.document;
|
|
104
|
+
by.set(op.plugin, m);
|
|
105
|
+
}
|
|
106
|
+
const out = new Map;
|
|
107
|
+
for (const [plugin, m] of by) {
|
|
108
|
+
const sorted = Object.fromEntries(Object.entries(m).sort(([a], [b]) => a.localeCompare(b)));
|
|
109
|
+
out.set(plugin, JSON.stringify(sorted, null, 2) + `
|
|
110
|
+
`);
|
|
111
|
+
}
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
var HEADER = "// Generated by packages/graphql/scripts/generate.ts. Do not edit; run `bun run --filter @fluxwp/graphql generate`.\n";
|
|
115
|
+
function typeNames(op) {
|
|
116
|
+
const suffix = op.kind === "query" ? "Query" : "Mutation";
|
|
117
|
+
const base = op.name.endsWith(suffix) ? op.name : op.name + suffix;
|
|
118
|
+
return { result: base, variables: base + "Variables" };
|
|
119
|
+
}
|
|
120
|
+
function operationsModule(ops) {
|
|
121
|
+
const lines = [HEADER, "import type { FlxOperation } from '../operation';"];
|
|
122
|
+
if (ops.length)
|
|
123
|
+
lines.push("import type * as T from './types';");
|
|
124
|
+
lines.push("");
|
|
125
|
+
for (const op of ops) {
|
|
126
|
+
const t = typeNames(op);
|
|
127
|
+
lines.push(`/** ${op.kind} ${op.name} (${op.plugin}, ${op.path}) */`, `export const ${op.name}: FlxOperation<T.${t.result}, T.${t.variables}> = {`, ` id: '${op.id}',`, ` name: '${op.name}',`, ` kind: '${op.kind}',`, ` plugin: '${op.plugin}',`, ` document: ${JSON.stringify(op.document)},`, "};", "");
|
|
128
|
+
}
|
|
129
|
+
if (!ops.length)
|
|
130
|
+
lines.push("export {};", "");
|
|
131
|
+
return lines.join(`
|
|
132
|
+
`);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// packages/graphql/scripts/parts.ts
|
|
136
|
+
import {
|
|
137
|
+
buildASTSchema,
|
|
138
|
+
concatAST,
|
|
139
|
+
getNamedType,
|
|
140
|
+
isInputObjectType,
|
|
141
|
+
isInterfaceType,
|
|
142
|
+
isObjectType,
|
|
143
|
+
isUnionType,
|
|
144
|
+
Kind as Kind2,
|
|
145
|
+
lexicographicSortSchema,
|
|
146
|
+
parse as parse2,
|
|
147
|
+
print as print2,
|
|
148
|
+
printSchema
|
|
149
|
+
} from "graphql";
|
|
150
|
+
var CORE_PART = "packages/graphql/schema/core.graphql";
|
|
151
|
+
function partOrder(a, b) {
|
|
152
|
+
if (a === b)
|
|
153
|
+
return 0;
|
|
154
|
+
if (a === CORE_PART)
|
|
155
|
+
return -1;
|
|
156
|
+
if (b === CORE_PART)
|
|
157
|
+
return 1;
|
|
158
|
+
return a < b ? -1 : 1;
|
|
159
|
+
}
|
|
160
|
+
function assembleSchema(parts) {
|
|
161
|
+
if (!parts.length)
|
|
162
|
+
throw new Error("no schema parts found");
|
|
163
|
+
const docs = [...parts].sort((a, b) => partOrder(a.path, b.path)).map((p) => {
|
|
164
|
+
try {
|
|
165
|
+
return parse2(p.body, { noLocation: true });
|
|
166
|
+
} catch (e) {
|
|
167
|
+
throw new Error(`${p.path}: ${e.message}`);
|
|
168
|
+
}
|
|
169
|
+
});
|
|
170
|
+
return lexicographicSortSchema(buildASTSchema(concatAST(docs)));
|
|
171
|
+
}
|
|
172
|
+
function assembleSdl(parts) {
|
|
173
|
+
return printSchema(assembleSchema(parts)) + `
|
|
174
|
+
`;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// packages/plugin-kit/src/codegen.ts
|
|
178
|
+
var HEADER2 = `// Generated by @fluxwp/plugin-kit (flx-kit codegen). Do not edit.
|
|
179
|
+
`;
|
|
180
|
+
function graphqlFiles(dir) {
|
|
181
|
+
if (!existsSync(dir))
|
|
182
|
+
return [];
|
|
183
|
+
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
|
|
184
|
+
const p = join(dir, e.name);
|
|
185
|
+
if (e.isDirectory())
|
|
186
|
+
return graphqlFiles(p);
|
|
187
|
+
return e.isFile() && e.name.endsWith(".graphql") ? [p] : [];
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
function defaultSchemaPath(from) {
|
|
191
|
+
for (let dir = resolve(from);; dir = dirname(dir)) {
|
|
192
|
+
const p = join(dir, "node_modules/@fluxwp/graphql/schema/full.graphql");
|
|
193
|
+
if (existsSync(p))
|
|
194
|
+
return p;
|
|
195
|
+
if (dirname(dir) === dir)
|
|
196
|
+
break;
|
|
197
|
+
}
|
|
198
|
+
throw new Error("FluxWP schema not found: install @fluxwp/graphql or pass --schema <file>.");
|
|
199
|
+
}
|
|
200
|
+
async function codegen(o) {
|
|
201
|
+
const plugin = resolve(o.plugin);
|
|
202
|
+
const slug = basename(plugin);
|
|
203
|
+
const out = resolve(o.out ?? join(plugin, "screens/generated"));
|
|
204
|
+
const parts = [{ path: CORE_PART, body: readFileSync(o.schema ?? defaultSchemaPath(plugin), "utf8") }];
|
|
205
|
+
const own = join(plugin, "graphql/schema.graphql");
|
|
206
|
+
if (existsSync(own))
|
|
207
|
+
parts.push({ path: `plugins/${slug}/graphql/schema.graphql`, body: readFileSync(own, "utf8") });
|
|
208
|
+
const sdl = assembleSdl(parts);
|
|
209
|
+
const sources = graphqlFiles(join(plugin, "graphql/operations")).sort().map((path) => ({ plugin: slug, path: relative(plugin, path), body: readFileSync(path, "utf8") }));
|
|
210
|
+
const ops = collectOperations(buildSchema(sdl), sources);
|
|
211
|
+
const types = await gqlCodegen({
|
|
212
|
+
filename: "types.ts",
|
|
213
|
+
schema: parse3(sdl),
|
|
214
|
+
documents: ops.map((op) => ({ location: op.path, document: parse3(op.document) })),
|
|
215
|
+
plugins: [{ typescriptOperations: {} }],
|
|
216
|
+
pluginMap: { typescriptOperations },
|
|
217
|
+
config: {
|
|
218
|
+
onlyOperationTypes: true,
|
|
219
|
+
enumsAsTypes: true,
|
|
220
|
+
useTypeImports: true,
|
|
221
|
+
dedupeOperationSuffix: true,
|
|
222
|
+
avoidOptionals: { field: true, inputValue: false, object: true, defaultValue: false },
|
|
223
|
+
maybeValue: "T | null",
|
|
224
|
+
inputMaybeValue: "T | null | undefined",
|
|
225
|
+
strictScalars: true,
|
|
226
|
+
scalars: { ID: "string", FlxJSON: "unknown" },
|
|
227
|
+
defaultScalarType: "unknown",
|
|
228
|
+
skipTypename: false,
|
|
229
|
+
nonOptionalTypename: false
|
|
230
|
+
}
|
|
231
|
+
});
|
|
232
|
+
const opsTs = operationsModule(ops).replace(/^\/\/ Generated by .*\n/, HEADER2).replace("import type { FlxOperation } from '../operation';", "import type { FlxOperation } from '@fluxwp/graphql';");
|
|
233
|
+
const files = new Map([
|
|
234
|
+
[join(out, "types.ts"), HEADER2 + `/* eslint-disable */
|
|
235
|
+
` + types],
|
|
236
|
+
[join(out, "operations.ts"), opsTs]
|
|
237
|
+
]);
|
|
238
|
+
const manifest = manifests(ops).get(slug);
|
|
239
|
+
const manifestPath = join(plugin, "graphql/persisted-queries.json");
|
|
240
|
+
const result = { operations: ops.length, written: [], stale: [] };
|
|
241
|
+
if (manifest) {
|
|
242
|
+
const cur = existsSync(manifestPath) ? readFileSync(manifestPath, "utf8") : null;
|
|
243
|
+
if (cur !== manifest) {
|
|
244
|
+
if (o.check)
|
|
245
|
+
result.stale.push(manifestPath);
|
|
246
|
+
else
|
|
247
|
+
files.set(manifestPath, manifest);
|
|
248
|
+
}
|
|
249
|
+
} else if (existsSync(manifestPath)) {
|
|
250
|
+
result.stale.push(manifestPath);
|
|
251
|
+
}
|
|
252
|
+
for (const [path, body] of files) {
|
|
253
|
+
if (existsSync(path) && readFileSync(path, "utf8") === body)
|
|
254
|
+
continue;
|
|
255
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
256
|
+
writeFileSync(path, body);
|
|
257
|
+
result.written.push(path);
|
|
258
|
+
}
|
|
259
|
+
return result;
|
|
260
|
+
}
|
|
261
|
+
export {
|
|
262
|
+
codegen,
|
|
263
|
+
defaultSchemaPath
|
|
264
|
+
};
|