@wp-operations/wp-ops 0.1.0 → 0.2.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.
@@ -0,0 +1,310 @@
1
+ import crypto from 'crypto';
2
+ import fs from 'fs';
3
+ import http from 'http';
4
+ import path from 'path';
5
+ import { Readable } from 'stream';
6
+ import { pipeline } from 'stream/promises';
7
+ import { execFileSync } from 'child_process';
8
+ import pc from 'picocolors';
9
+ import { app as loadApp, ide } from '../deps.js';
10
+ import { UsageError } from '../args.js';
11
+ import { runComposer } from './platform.js';
12
+
13
+ const FETCH_EVERY_MS = 3000;
14
+ const BUSY_MS = 60000;
15
+ const NAVIGATION = /text\/html/;
16
+
17
+ function git(cwd, args) {
18
+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
19
+ }
20
+
21
+ function tryGit(cwd, args) {
22
+ try {
23
+ return git(cwd, args);
24
+ } catch {
25
+ return '';
26
+ }
27
+ }
28
+
29
+ function hashFile(file) {
30
+ return fs.existsSync(file) ? crypto.createHash('sha1').update(fs.readFileSync(file)).digest('hex') : '';
31
+ }
32
+
33
+ function needsVendor(dir) {
34
+ try {
35
+ const data = JSON.parse(fs.readFileSync(path.join(dir, 'composer.json'), 'utf8'));
36
+ return Object.keys(data.require ?? {}).some((name) => name.includes('/'));
37
+ } catch {
38
+ return false;
39
+ }
40
+ }
41
+
42
+ function composerInstall(dir, log) {
43
+ log(pc.dim(` composer install (${dir})`));
44
+ try {
45
+ runComposer(dir, ['install', '--no-interaction', '--no-progress', '--no-dev']);
46
+ } catch (error) {
47
+ throw new Error(`composer install failed in ${dir}: ${error.message}`);
48
+ }
49
+ }
50
+
51
+ function parseHeaders(req) {
52
+ const headers = {};
53
+ for (let i = 0; i < req.rawHeaders.length; i += 2) {
54
+ headers[req.rawHeaders[i].toLowerCase()] = req.rawHeaders[i + 1];
55
+ }
56
+ return headers;
57
+ }
58
+
59
+ function readBody(req) {
60
+ return new Promise((resolve, reject) => {
61
+ const chunks = [];
62
+ req.on('data', (chunk) => chunks.push(chunk));
63
+ req.on('end', () => resolve(new Uint8Array(Buffer.concat(chunks))));
64
+ req.on('error', reject);
65
+ });
66
+ }
67
+
68
+ function sendJson(res, status, body) {
69
+ res.writeHead(status, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
70
+ res.end(JSON.stringify(body));
71
+ }
72
+
73
+ /**
74
+ * The sandbox runtime the platform theme leases: one HTTP server that
75
+ * answers health checks at --health (Bearer token optional) and serves
76
+ * every app of the platform repository at /{kind}/{slug}/ on its own
77
+ * wp-app WordPress site, framable from the platform.
78
+ *
79
+ * Without --git it serves the working tree as it is. With --git it serves
80
+ * each app from its own worktree, refreshed from the remote on every page
81
+ * load: the app's work branch (--work-branch, default vibe/{slug}) when it
82
+ * exists, else the deploy branch.
83
+ */
84
+ export async function sandbox(options) {
85
+ const { readLayout, listApps, useLocalData } = await ide();
86
+ const wpApp = await loadApp();
87
+ const log = options.log ?? console.log;
88
+ const root = options.root;
89
+ const port = Number(options.port ?? 8080);
90
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new UsageError(`Invalid --port "${options.port}".`);
91
+ const publicUrl = String(options.url || `http://localhost:${port}`).replace(/\/+$/, '');
92
+ const healthPath = `/${String(options.health ?? '/').replace(/^\/+/, '')}`.replace(/(.)\/+$/, '$1');
93
+ const tokenEnv = options.tokenEnv || 'SANDBOX_TOKEN';
94
+ const token = process.env[tokenEnv] ?? '';
95
+ const frameAncestors = String(options.frameAncestors ?? '*');
96
+ const max = Math.max(1, Number(options.max ?? 3));
97
+ const useGit = Boolean(options.git);
98
+ const remote = options.remote || 'origin';
99
+ const workBranch = options.workBranch === false ? '' : String(options.workBranch || 'vibe/{slug}');
100
+
101
+ readLayout(root);
102
+ if (!process.env.WP_APP_HOME) useLocalData(root);
103
+
104
+ let branch = options.branch || '';
105
+ if (useGit) {
106
+ if (!fs.existsSync(path.join(root, '.git'))) throw new UsageError(`--git needs ${root} to be a git clone.`);
107
+ if (!tryGit(root, ['remote', 'get-url', remote])) throw new UsageError(`--git: remote "${remote}" is not set.`);
108
+ git(root, ['fetch', remote, '--prune']);
109
+ if (!branch) {
110
+ branch = tryGit(root, ['symbolic-ref', '--short', `refs/remotes/${remote}/HEAD`]).replace(`${remote}/`, '') || 'main';
111
+ }
112
+ }
113
+
114
+ const sites = new Map();
115
+ let lastFetch = 0;
116
+
117
+ function findApp(kindKey, appSlug) {
118
+ const layout = readLayout(root);
119
+ const kind = layout.kinds.find((item) => item.key === kindKey || item.folder === kindKey);
120
+ if (!kind) return null;
121
+ const appEntry = listApps(root, layout).find((item) => item.kind === kind.key && item.slug === appSlug);
122
+ return appEntry && fs.existsSync(appEntry.dir) ? { kind, app: appEntry } : null;
123
+ }
124
+
125
+ function syncWorktree(key, folderPath, navigation) {
126
+ const worktree = path.join(root, '.local', 'sandbox', 'worktrees', key.replace('/', '--'));
127
+ const now = Date.now();
128
+ if (navigation && now - lastFetch > FETCH_EVERY_MS) {
129
+ tryGit(root, ['fetch', remote, '--prune']);
130
+ lastFetch = now;
131
+ }
132
+ const appSlug = key.split('/')[1];
133
+ const kindKey = key.split('/')[0];
134
+ const work = workBranch ? workBranch.replace(/\{slug\}/g, appSlug).replace(/\{kind\}/g, kindKey) : '';
135
+ const ref = work && tryGit(root, ['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/${work}`]) ? `${remote}/${work}` : `${remote}/${branch}`;
136
+ const sha = git(root, ['rev-parse', '--verify', `${ref}^{commit}`]);
137
+ if (!fs.existsSync(path.join(worktree, '.git'))) {
138
+ fs.mkdirSync(path.dirname(worktree), { recursive: true });
139
+ tryGit(root, ['worktree', 'prune']);
140
+ git(root, ['worktree', 'add', '--force', '--detach', worktree, sha]);
141
+ } else if (tryGit(worktree, ['rev-parse', 'HEAD']) !== sha) {
142
+ git(worktree, ['checkout', '--force', '--detach', sha]);
143
+ }
144
+ return { dir: path.join(worktree, folderPath), ref, sha };
145
+ }
146
+
147
+ async function evict() {
148
+ const now = Date.now();
149
+ const busy = (site) => [...site.open].some((request) => now - request.at < BUSY_MS);
150
+ const idle = [...sites.entries()].filter(([, site]) => site.ready && !busy(site)).sort((a, b) => a[1].used - b[1].used);
151
+ while (sites.size > max && idle.length) {
152
+ const [key, site] = idle.shift();
153
+ sites.delete(key);
154
+ try {
155
+ site.wp.php.exit();
156
+ } catch {}
157
+ log(pc.dim(` stopped ${key} (keeping at most ${max} running)`));
158
+ }
159
+ }
160
+
161
+ async function getSite(kind, appEntry, navigation) {
162
+ const key = `${kind.key}/${appEntry.slug}`;
163
+ let source = { dir: appEntry.dir, ref: 'working tree', sha: '' };
164
+ if (useGit) {
165
+ const running = sites.get(key);
166
+ source = running && !navigation ? { dir: running.dir, ref: running.ref, sha: '' } : syncWorktree(key, appEntry.path, navigation);
167
+ }
168
+ if (!fs.existsSync(path.join(source.dir, 'composer.json'))) {
169
+ throw Object.assign(new Error(`${appEntry.path} has no composer.json on ${source.ref}.`), { status: 404 });
170
+ }
171
+
172
+ let site = sites.get(key);
173
+ if (site && site.dir !== source.dir) {
174
+ sites.delete(key);
175
+ site = null;
176
+ }
177
+ if (!site) {
178
+ site = { dir: source.dir, ref: source.ref, open: new Set(), used: Date.now(), ready: false, lockHash: null };
179
+ site.starting = (async () => {
180
+ const appUrl = `${publicUrl}/${encodeURIComponent(kind.key)}/${encodeURIComponent(appEntry.slug)}`;
181
+ const config = await wpApp.getWpAppConfig({
182
+ path: source.dir,
183
+ php: options.php,
184
+ wp: options.wp,
185
+ mode: 'wp-app',
186
+ port,
187
+ });
188
+ config.absoluteUrl = appUrl;
189
+ log(` starting ${key} from ${source.ref} at ${appUrl}/`);
190
+ site.wp = await wpApp.startWPApp(config);
191
+ site.ready = true;
192
+ })();
193
+ sites.set(key, site);
194
+ }
195
+ const lockHash = hashFile(path.join(source.dir, 'composer.lock'));
196
+ if (needsVendor(source.dir)) {
197
+ const missing = !fs.existsSync(path.join(source.dir, 'vendor', 'autoload.php'));
198
+ const changed = site.lockHash !== null && site.lockHash !== lockHash;
199
+ if (missing || changed) composerInstall(source.dir, log);
200
+ }
201
+ site.lockHash = lockHash;
202
+ try {
203
+ await site.starting;
204
+ } catch (error) {
205
+ sites.delete(key);
206
+ throw error;
207
+ }
208
+ site.used = Date.now();
209
+ return site;
210
+ }
211
+
212
+ const server = http.createServer(async (req, res) => {
213
+ const url = new URL(req.url ?? '/', 'http://sandbox');
214
+ const pathname = url.pathname.replace(/(.)\/+$/, '$1');
215
+ try {
216
+ if (pathname === healthPath && (req.method === 'GET' || req.method === 'HEAD')) {
217
+ if (token) {
218
+ const given = Buffer.from(String(req.headers.authorization ?? ''));
219
+ const expected = Buffer.from(`Bearer ${token}`);
220
+ if (given.length !== expected.length || !crypto.timingSafeEqual(given, expected)) {
221
+ sendJson(res, 401, { ok: false, error: 'Bearer token required.' });
222
+ return;
223
+ }
224
+ }
225
+ sendJson(res, 200, { ok: true, running: [...sites.keys()], git: useGit ? { remote, branch, work: workBranch } : false });
226
+ return;
227
+ }
228
+
229
+ const parts = url.pathname.split('/');
230
+ const kindKey = decodeURIComponent(parts[1] ?? '');
231
+ const appSlug = decodeURIComponent(parts[2] ?? '');
232
+ const found = kindKey && appSlug ? findApp(kindKey, appSlug) : null;
233
+ if (!found) {
234
+ sendJson(res, 404, { ok: false, error: 'No app here. Apps are served at /{kind}/{slug}/.' });
235
+ return;
236
+ }
237
+ if (parts.length === 3) {
238
+ res.writeHead(301, { Location: `/${parts[1]}/${parts[2]}/${url.search}` });
239
+ res.end();
240
+ return;
241
+ }
242
+
243
+ const navigation = req.method === 'GET' && NAVIGATION.test(String(req.headers.accept ?? ''));
244
+ const site = await getSite(found.kind, found.app, navigation);
245
+ // Tracked until the response closes. WordPress's own loopback
246
+ // requests (e.g. the permalink check on a fresh install) can stay
247
+ // open forever, so only requests younger than BUSY_MS keep a site busy.
248
+ const open = { at: Date.now() };
249
+ site.open.add(open);
250
+ let body = null;
251
+ res.once('close', () => {
252
+ site.open.delete(open);
253
+ body?.destroy();
254
+ evict().catch(() => {});
255
+ });
256
+ const response = await site.wp.requestHandler.requestStreamed({
257
+ url: req.url,
258
+ method: req.method,
259
+ headers: parseHeaders(req),
260
+ body: await readBody(req),
261
+ });
262
+ const [headers, status] = await Promise.all([response.headers, response.httpStatusCode]);
263
+ res.statusCode = status;
264
+ for (const name in headers) {
265
+ if (name.toLowerCase() === 'x-frame-options') continue;
266
+ res.setHeader(name, headers[name]);
267
+ }
268
+ res.setHeader('Content-Security-Policy', `frame-ancestors ${frameAncestors}`);
269
+ body = Readable.fromWeb(response.stdout);
270
+ try {
271
+ await pipeline(body, res);
272
+ } catch (error) {
273
+ if (!['ERR_STREAM_PREMATURE_CLOSE', 'ERR_STREAM_UNABLE_TO_PIPE', 'ABORT_ERR'].includes(error?.code)) throw error;
274
+ }
275
+ } catch (error) {
276
+ log(pc.red(` ${req.method} ${req.url}: ${error.message}`));
277
+ if (!res.headersSent) {
278
+ sendJson(res, error.status ?? 500, { ok: false, error: error.message });
279
+ } else {
280
+ res.destroy();
281
+ }
282
+ }
283
+ });
284
+
285
+ await new Promise((resolve, reject) => {
286
+ server.once('error', (error) => reject(error.code === 'EADDRINUSE' ? new UsageError(`Port ${port} is in use. Pass --port=<n>.`) : error));
287
+ server.listen(port, options.host ?? '0.0.0.0', resolve);
288
+ });
289
+ const actualPort = server.address().port;
290
+ log(`\n sandbox ${pc.bold(publicUrl)} ${pc.dim(`(listening on ${actualPort})`)}`);
291
+ log(` health ${healthPath}${token ? ` (Bearer token from $${tokenEnv})` : ''}`);
292
+ log(` apps ${publicUrl}/{kind}/{slug}/`);
293
+ log(` source ${useGit ? `${remote}/${branch}${workBranch ? `, or ${remote}/${workBranch} when it exists` : ''}` : 'working tree'}\n`);
294
+ return {
295
+ server,
296
+ port: actualPort,
297
+ sites,
298
+ close: async () => {
299
+ for (const site of sites.values()) {
300
+ try {
301
+ await site.starting;
302
+ site.wp.php.exit();
303
+ } catch {}
304
+ }
305
+ sites.clear();
306
+ server.closeAllConnections?.();
307
+ await new Promise((resolve) => server.close(resolve));
308
+ },
309
+ };
310
+ }
package/src/deps.js ADDED
@@ -0,0 +1,27 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { fileURLToPath, pathToFileURL } from 'url';
4
+
5
+ const here = path.dirname(fileURLToPath(import.meta.url));
6
+
7
+ /**
8
+ * Loads a sibling @wp-operations package: the installed dependency when
9
+ * present, otherwise the built copy next to this package in the monorepo.
10
+ */
11
+ async function load(name, distEntry) {
12
+ try {
13
+ return await import(`@wp-operations/${name}`);
14
+ } catch (error) {
15
+ if (error?.code !== 'ERR_MODULE_NOT_FOUND') throw error;
16
+ const local = path.resolve(here, '..', '..', name, distEntry);
17
+ if (!fs.existsSync(local)) {
18
+ throw new Error(
19
+ `@wp-operations/${name} is not installed. Run npm install (or build packages/${name}).`
20
+ );
21
+ }
22
+ return import(pathToFileURL(local).href);
23
+ }
24
+ }
25
+
26
+ export const ide = () => load('wp-ide', 'dist/index.js');
27
+ export const app = () => load('wp-app', 'dist/index.js');
package/src/index.js CHANGED
@@ -1,4 +1,6 @@
1
1
  export { startApp } from './commands/start.js';
2
2
  export { buildAll } from './commands/build.js';
3
3
  export { doctor } from './commands/doctor.js';
4
+ export { init, newApp, newPlugin, apps, plugins, composer, platformRoot } from './commands/platform.js';
5
+ export { sandbox } from './commands/sandbox.js';
4
6
  export { findRootDir, readConfig, findWpAppCli, listApps, listPackages } from './project.js';
package/src/main.js CHANGED
@@ -1,47 +1,131 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { fileURLToPath } from 'url';
4
+ import pc from 'picocolors';
5
+ import { parseArgs, UsageError } from './args.js';
4
6
  import { startApp } from './commands/start.js';
5
7
  import { buildAll } from './commands/build.js';
6
8
  import { doctor } from './commands/doctor.js';
9
+ import { apps, composer, init, newApp, newPlugin, platformRoot, plugins } from './commands/platform.js';
10
+ import { sandbox } from './commands/sandbox.js';
7
11
  import { tui } from './tui.js';
8
12
 
9
13
  const here = path.dirname(fileURLToPath(import.meta.url));
10
- const pkg = JSON.parse(
11
- fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8')
12
- );
14
+ const pkg = JSON.parse(fs.readFileSync(path.join(here, '..', 'package.json'), 'utf8'));
15
+
16
+ const HELP = `wp-ops v${pkg.version}
17
+
18
+ Usage:
19
+ wp-ops interactive menu
20
+
21
+ Platform repository:
22
+ wp-ops init [dir] [--platform=<theme dir or platform.json>]
23
+ lay out a platform repository and git init it
24
+ wp-ops apps list apps (<kind>/<slug>) and their deploy targets
25
+ wp-ops plugins list plugins and the apps that use them
26
+ wp-ops new app <kind> <slug> [--server= --app-path= --theme-slug=]
27
+ wp-ops new plugin <vendor/name> [--description=]
28
+ wp-ops composer <add|remove|update> --apps=<a,b> --packages="<x y>" [--constraint=*] [--no-lock]
29
+ edit composer.json and refresh composer.lock (what composer.yml runs)
30
+ wp-ops sandbox [--port=8080] [--url=<public url>] [--git] [--branch=] [--work-branch=vibe/{slug}]
31
+ [--health=/] [--token-env=SANDBOX_TOKEN] [--frame-ancestors="*"] [--max=3] [--php=] [--wp=]
32
+ serve every app at /{kind}/{slug}/ for the platform's previews
33
+ wp-ops edit [--port=4500] [--preview=<sandbox url>]
34
+ open the local browser editor (wp-ide)
35
+
36
+ Single app:
37
+ wp-ops start [dir] [--wp=… --php=… --port=…]
38
+ wp-ops dev [dir] start + watch
39
+ wp-ops build build all packages/ with a build script
40
+ wp-ops doctor environment and repository checks`;
13
41
 
14
42
  const [command, ...rest] = process.argv.slice(2);
43
+ const { positional, options } = parseArgs(rest);
15
44
  const flags = rest.filter((arg) => arg.startsWith('--'));
16
- const positional = rest.filter((arg) => !arg.startsWith('--'));
17
45
 
18
- function appDirFromArgs() {
19
- return path.resolve(positional[0] ?? process.cwd());
46
+ async function run() {
47
+ switch (command) {
48
+ case undefined:
49
+ await tui(pkg.version);
50
+ return;
51
+ case 'start':
52
+ case 'dev':
53
+ startApp({ appDir: path.resolve(positional[0] ?? process.cwd()), flags, dev: command === 'dev' });
54
+ return;
55
+ case 'build':
56
+ buildAll();
57
+ return;
58
+ case 'doctor':
59
+ await doctor();
60
+ return;
61
+ case 'init':
62
+ await init({ dir: positional[0] ?? process.cwd(), platform: options.platform, version: pkg.version });
63
+ return;
64
+ case 'apps':
65
+ await apps({ root: await platformRoot() });
66
+ return;
67
+ case 'plugins':
68
+ await plugins({ root: await platformRoot() });
69
+ return;
70
+ case 'new': {
71
+ const root = await platformRoot();
72
+ if (positional[0] === 'app') {
73
+ await newApp({ root, kind: positional[1], slug: positional[2], server: options.server || '', appPath: options['app-path'] || '', themeSlug: options['theme-slug'] });
74
+ } else if (positional[0] === 'plugin') {
75
+ await newPlugin({ root, name: positional[1], description: options.description || '' });
76
+ } else {
77
+ throw new UsageError('Usage: wp-ops new app <kind> <slug> | wp-ops new plugin <vendor/name>');
78
+ }
79
+ return;
80
+ }
81
+ case 'composer':
82
+ await composer({
83
+ root: await platformRoot(),
84
+ action: positional[0],
85
+ apps: options.apps || '',
86
+ packages: options.packages || positional.slice(1).join(' '),
87
+ constraint: options.constraint || '*',
88
+ lock: options.lock !== false,
89
+ });
90
+ return;
91
+ case 'sandbox':
92
+ await sandbox({
93
+ root: await platformRoot(),
94
+ port: options.port ?? 8080,
95
+ url: options.url,
96
+ git: options.git === true,
97
+ remote: options.remote,
98
+ branch: options.branch,
99
+ workBranch: options['work-branch'],
100
+ health: options.health,
101
+ tokenEnv: options['token-env'],
102
+ frameAncestors: options['frame-ancestors'],
103
+ max: options.max,
104
+ php: options.php,
105
+ wp: options.wp,
106
+ });
107
+ return;
108
+ case 'edit': {
109
+ const { ide } = await import('./deps.js');
110
+ const { startEditor } = await ide();
111
+ const editor = await startEditor({ root: process.cwd(), port: options.port ? Number(options.port) : 4500, preview: options.preview || '' });
112
+ console.log(`wp-ide editing ${editor.root}\nOpen: ${editor.url}`);
113
+ return;
114
+ }
115
+ case '--version':
116
+ case '-v':
117
+ console.log(pkg.version);
118
+ return;
119
+ default:
120
+ console.log(HELP);
121
+ process.exit(command === 'help' || command === '--help' || command === '-h' ? 0 : 1);
122
+ }
20
123
  }
21
124
 
22
- switch (command) {
23
- case undefined:
24
- await tui(pkg.version);
25
- break;
26
- case 'start':
27
- startApp({ appDir: appDirFromArgs(), flags });
28
- break;
29
- case 'dev':
30
- startApp({ appDir: appDirFromArgs(), flags, dev: true });
31
- break;
32
- case 'build':
33
- buildAll();
34
- break;
35
- case 'doctor':
36
- doctor();
37
- break;
38
- case '--version':
39
- case '-v':
40
- console.log(pkg.version);
41
- break;
42
- default:
43
- console.log(
44
- `wp-ops v${pkg.version}\n\nUsage:\n wp-ops interactive TUI\n wp-ops start [dir] [--wp=… --php=… --port=…]\n wp-ops dev [dir] start + watch\n wp-ops build build all packages\n wp-ops doctor environment checks`
45
- );
46
- process.exit(command === 'help' || command === '--help' ? 0 : 1);
125
+ try {
126
+ await run();
127
+ } catch (error) {
128
+ console.error(pc.red(`wp-ops: ${error.message}`));
129
+ if (!(error instanceof UsageError) && process.env.DEBUG) console.error(error);
130
+ process.exit(1);
47
131
  }
package/src/project.js CHANGED
@@ -1,7 +1,8 @@
1
1
  import fs from 'fs';
2
2
  import path from 'path';
3
+ import { fileURLToPath } from 'url';
3
4
 
4
- const ROOT_MARKERS = ['wp-operations.json', '.git'];
5
+ const ROOT_MARKERS = [path.join('.github', 'platform.json'), 'wp-operations.json', '.git'];
5
6
 
6
7
  export function findRootDir(startDir = process.cwd()) {
7
8
  let current = path.resolve(startDir);
@@ -37,6 +38,8 @@ export function findWpAppCli(rootDir) {
37
38
  const candidates = [
38
39
  path.join(rootDir, 'packages', 'wp-app', 'cli.js'),
39
40
  path.join(rootDir, 'node_modules', '@wp-operations', 'wp-app', 'cli.js'),
41
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..', 'wp-app', 'cli.js'),
42
+ path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'node_modules', '@wp-operations', 'wp-app', 'cli.js'),
40
43
  ];
41
44
  return candidates.find((candidate) => fs.existsSync(candidate)) ?? null;
42
45
  }
@@ -0,0 +1,140 @@
1
+ export const GITIGNORE = `vendor/
2
+ node_modules/
3
+ .local/
4
+ .env
5
+ *.log
6
+ .DS_Store
7
+ Thumbs.db
8
+ `;
9
+
10
+ export function composerWorkflow(version) {
11
+ return `name: composer
12
+
13
+ on:
14
+ workflow_dispatch:
15
+ inputs:
16
+ action:
17
+ description: add, remove or update
18
+ required: true
19
+ type: choice
20
+ options: [add, remove, update]
21
+ apps:
22
+ description: Comma-separated app folders, e.g. service-apps/shop
23
+ required: true
24
+ type: string
25
+ packages:
26
+ description: Space-separated plugin names, e.g. acme/forms acme/seo
27
+ required: true
28
+ type: string
29
+
30
+ permissions:
31
+ contents: write
32
+
33
+ concurrency:
34
+ group: composer-\${{ github.ref }}
35
+ cancel-in-progress: false
36
+
37
+ jobs:
38
+ lock:
39
+ runs-on: ubuntu-latest
40
+ steps:
41
+ - uses: actions/checkout@v4
42
+
43
+ - uses: shivammathur/setup-php@v2
44
+ with:
45
+ php-version: '8.2'
46
+ tools: composer:v2
47
+ coverage: none
48
+
49
+ - uses: actions/setup-node@v4
50
+ with:
51
+ node-version: '22'
52
+
53
+ - name: Refresh composer.lock
54
+ env:
55
+ ACTION: \${{ inputs.action }}
56
+ APPS: \${{ inputs.apps }}
57
+ PACKAGES: \${{ inputs.packages }}
58
+ run: npx --yes @wp-operations/wp-ops@^${version} composer "$ACTION" --apps="$APPS" --packages="$PACKAGES"
59
+
60
+ - name: Commit
61
+ env:
62
+ ACTION: \${{ inputs.action }}
63
+ PACKAGES: \${{ inputs.packages }}
64
+ run: |
65
+ git config user.name "github-actions[bot]"
66
+ git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
67
+ git add --all -- ':(glob)**/composer.json' ':(glob)**/composer.lock'
68
+ if git diff --cached --quiet; then
69
+ echo "composer.lock is already up to date."
70
+ exit 0
71
+ fi
72
+ git commit -m "composer: $ACTION $PACKAGES"
73
+ git push origin "HEAD:$GITHUB_REF_NAME"
74
+ `;
75
+ }
76
+
77
+ export function appStyle(slug) {
78
+ return `/*
79
+ Theme Name: ${slug}
80
+ Version: 0.1.0
81
+ Requires PHP: 8.0
82
+ */
83
+ `;
84
+ }
85
+
86
+ export const APP_INDEX = `<?php
87
+ declare(strict_types=1);
88
+
89
+ get_header();
90
+
91
+ while ( have_posts() ) :
92
+ the_post();
93
+ the_title( '<h1>', '</h1>' );
94
+ the_content();
95
+ endwhile;
96
+
97
+ get_footer();
98
+ `;
99
+
100
+ export const APP_FUNCTIONS = `<?php
101
+ declare(strict_types=1);
102
+
103
+ /*
104
+ * Loads the composer autoloader and boots every installed plugin
105
+ * (composer type "psr4-plugin") that names its class in
106
+ * extra.wp-operations.plugin-class.
107
+ */
108
+ $autoload = __DIR__ . '/vendor/autoload.php';
109
+
110
+ if ( is_readable( $autoload ) ) {
111
+ require_once $autoload;
112
+
113
+ $installed = __DIR__ . '/vendor/composer/installed.json';
114
+ $data = is_readable( $installed ) ? json_decode( (string) file_get_contents( $installed ), true ) : [];
115
+ $packages = is_array( $data ) ? ( $data['packages'] ?? $data ) : [];
116
+
117
+ foreach ( (array) $packages as $package ) {
118
+ $class = $package['extra']['wp-operations']['plugin-class'] ?? '';
119
+
120
+ if ( 'psr4-plugin' === ( $package['type'] ?? '' ) && is_string( $class ) && '' !== $class && class_exists( $class ) && method_exists( $class, 'init' ) ) {
121
+ $class::init();
122
+ }
123
+ }
124
+ }
125
+ `;
126
+
127
+ export function pluginClass(namespace) {
128
+ return `<?php
129
+ declare(strict_types=1);
130
+
131
+ namespace ${namespace};
132
+
133
+ final class Plugin
134
+ {
135
+ public static function init(): void
136
+ {
137
+ }
138
+ }
139
+ `;
140
+ }