@wp-operations/wp-ops 0.5.4 → 0.6.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 CHANGED
@@ -1,3 +1,5 @@
1
+ <p align="center"><img src="../../theme/assets/brand/icon.svg" alt="wp-operations" width="120"></p>
2
+
1
3
  # @wp-operations/wp-ops
2
4
 
3
5
  The wp-operations tool. One install gives you all four commands:
@@ -31,7 +33,7 @@ wp-ops doctor
31
33
 
32
34
  | Command | What it does |
33
35
  |---|---|
34
- | `init [dir]` | Creates the platform repository: the platform theme in `wp-operations/`, `platform.json`, `.github/platform.json`, the app manifests, `packages/`, the app folders, `.github/workflows/composer.yml` and `.gitignore`, then runs `git init`. Never overwrites a file. |
36
+ | `init [dir]` | Asks for each section of the project's `platform.json` (name, author, website, languages and default language, content types and their fields, taxonomies, modules, brand color, app categories) and writes it. Start from the default content types or from empty. Then creates the platform theme in `wp-operations/`, `.github/platform.json`, the app manifests, `packages/`, the app folders, the workflows and `.gitignore`, and runs `git init`. `--yes` takes the default `platform.json`; `--template=empty` starts with no content types. Never overwrites a file. |
35
37
  | `start` | Runs the platform (`wp-operations/`) locally. Site data stays in `.local/` (gitignored). `wp-ops start <dir>` runs one app instead. |
36
38
  | `update` | Replaces `wp-operations/` with the platform shipped in your wp-ops version. Update wp-ops first (`npm install -g @wp-operations/wp-ops`), then run it and commit. |
37
39
  | `new app <kind> <slug>` | Creates the app (composer type `wp-app`) and adds it to the kind's manifest. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wp-operations/wp-ops",
3
- "version": "0.5.4",
3
+ "version": "0.6.0",
4
4
  "description": "The wp-operations tool. One install gives the platform and wp-ops, wp-app, wp-ide and wp-code.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -4,6 +4,7 @@ import { execFileSync, spawnSync } from 'child_process';
4
4
  import { fileURLToPath } from 'url';
5
5
  import pc from 'picocolors';
6
6
  import { ide } from '../deps.js';
7
+ import { buildPlatformJson } from './setup.js';
7
8
  import { UsageError } from '../args.js';
8
9
  import {
9
10
  APP_FUNCTIONS,
@@ -48,7 +49,7 @@ export async function platformRoot(startDir = process.cwd()) {
48
49
  }
49
50
  }
50
51
 
51
- export async function init({ dir = process.cwd(), platform, version, log = console.log }) {
52
+ export async function init({ dir = process.cwd(), platform, version, answers = null, log = console.log }) {
52
53
  const { DEFAULT_KINDS, LAYOUT_FILE, encodeJson, layoutJson } = await ide();
53
54
  const root = path.resolve(dir);
54
55
  fs.mkdirSync(root, { recursive: true });
@@ -85,8 +86,9 @@ export async function init({ dir = process.cwd(), platform, version, log = conso
85
86
  if (!fs.existsSync(file)) {
86
87
  throw new UsageError(`--platform: ${file} does not exist.`);
87
88
  }
88
- JSON.parse(fs.readFileSync(file, 'utf8').replace(/^/, ''));
89
- writeNew(path.join(root, 'platform.json'), fs.readFileSync(file), created);
89
+ const base = JSON.parse(fs.readFileSync(file, 'utf8').replace(/^/, ''));
90
+ const config = answers ? encodeJson(buildPlatformJson(base, answers)) : fs.readFileSync(file);
91
+ if (writeNew(path.join(root, 'platform.json'), config, created)) syncPlatformJson(root);
90
92
  }
91
93
 
92
94
  let gitInit = false;
@@ -119,6 +121,18 @@ export function bundledPlatform() {
119
121
 
120
122
  export const PLATFORM_DIR = 'wp-operations';
121
123
 
124
+ /**
125
+ * The repository's platform.json is the one the platform runs with: it is
126
+ * copied into wp-operations/ (deploy-platform.yml does the same on deploy).
127
+ */
128
+ function syncPlatformJson(root) {
129
+ const source = path.join(root, 'platform.json');
130
+ const theme = path.join(root, PLATFORM_DIR);
131
+ if (fs.existsSync(source) && fs.existsSync(path.join(theme, 'style.css'))) {
132
+ fs.copyFileSync(source, path.join(theme, 'platform.json'));
133
+ }
134
+ }
135
+
122
136
  function writeWorkflows(root, version, created) {
123
137
  const dir = path.join(root, '.github', 'workflows');
124
138
  writeNew(path.join(dir, 'composer.yml'), composerWorkflow(version), created);
@@ -161,6 +175,7 @@ export async function update({ root, version, log = console.log }) {
161
175
  }
162
176
  fs.rmSync(target, { recursive: true, force: true });
163
177
  copyTheme(source, target);
178
+ syncPlatformJson(root);
164
179
  log(` ${pc.green('✓')} Platform ${from || '(none)'} → ${to}. Review with git diff, then commit.`);
165
180
  return { from, to, changed: true };
166
181
  }
@@ -0,0 +1,163 @@
1
+ import * as p from '@clack/prompts';
2
+
3
+ export const LANGUAGES = [
4
+ ['en', 'English'], ['fr', 'French'], ['ar', 'Arabic'], ['de', 'German'], ['es', 'Spanish'], ['it', 'Italian'],
5
+ ['pt', 'Portuguese'], ['nl', 'Dutch'], ['ru', 'Russian'], ['tr', 'Turkish'], ['hi', 'Hindi'], ['ml', 'Malayalam'],
6
+ ['ta', 'Tamil'], ['ur', 'Urdu'], ['zh', 'Chinese'], ['ja', 'Japanese'],
7
+ ];
8
+
9
+ export const FIELD_TYPES = ['text', 'textarea', 'html', 'number', 'checkbox', 'url', 'email', 'select', 'image', 'files', 'video', 'audio', 'lines'];
10
+ const KINDS = { media: 'All Contents', interactive: 'Questionnaires', document: 'Doc Templates' };
11
+ const MENU_FOR_KIND = { media: 'contents', interactive: 'questionnaires', document: 'templates' };
12
+
13
+ const clone = (value) => JSON.parse(JSON.stringify(value));
14
+ const key = (value) => String(value).toLowerCase().trim().replace(/[^a-z0-9_-]+/g, '_').replace(/^_+|_+$/g, '');
15
+
16
+ class Cancelled extends Error {}
17
+ function check(value) {
18
+ if (p.isCancel(value)) throw new Cancelled('Cancelled.');
19
+ return value;
20
+ }
21
+
22
+ /**
23
+ * "title, level:select(beginner|advanced), cover:image" → field definitions.
24
+ */
25
+ export function parseFields(text) {
26
+ return String(text || '')
27
+ .split(',')
28
+ .map((part) => part.trim())
29
+ .filter(Boolean)
30
+ .map((part) => {
31
+ const match = part.match(/^([^:]+?)(?::\s*([a-z]+)(?:\(([^)]*)\))?)?$/i);
32
+ const label = (match?.[1] || part).trim();
33
+ const type = FIELD_TYPES.includes(String(match?.[2] || '').toLowerCase()) ? match[2].toLowerCase() : 'text';
34
+ const field = { key: key(label), type, label: label.charAt(0).toUpperCase() + label.slice(1) };
35
+ if (type === 'select') {
36
+ const options = String(match?.[3] || '').split('|').map((o) => o.trim()).filter(Boolean);
37
+ field.options = Object.fromEntries(options.map((o) => [key(o), o]));
38
+ }
39
+ return field;
40
+ });
41
+ }
42
+
43
+ export function contentType({ label, singular, kind = 'media', fields = [] }) {
44
+ const slug = key(label);
45
+ return {
46
+ key: slug,
47
+ label,
48
+ singular: singular || label,
49
+ kind,
50
+ icon: 'dashicons-admin-post',
51
+ supports: ['title', 'editor', 'excerpt', 'thumbnail'],
52
+ translate: true,
53
+ folder: slug,
54
+ fields,
55
+ };
56
+ }
57
+
58
+ /**
59
+ * Builds a project's platform.json from the platform's default one and the
60
+ * answers. Sections that are not answered keep the default values.
61
+ */
62
+ export function buildPlatformJson(base, answers = {}) {
63
+ const config = clone(base);
64
+ const a = answers;
65
+
66
+ config.platform = { ...config.platform, name: a.name ?? config.platform?.name ?? '', author: a.author ?? config.platform?.author ?? '', url: a.url ?? config.platform?.url ?? '' };
67
+
68
+ if (Array.isArray(a.languages) && a.languages.length) {
69
+ config.languages = a.languages.map((code) => ({ code, name: (LANGUAGES.find(([c]) => c === code) || [code, code])[1] }));
70
+ config.default_language = a.languages.includes(a.defaultLanguage) ? a.defaultLanguage : a.languages[0];
71
+ }
72
+
73
+ if (a.template === 'empty') {
74
+ config.content = { ...config.content, placeholders: [], types: [], taxonomies: [] };
75
+ }
76
+ if (Array.isArray(a.types)) config.content.types.push(...a.types);
77
+ if (Array.isArray(a.taxonomies)) config.content.taxonomies.push(...a.taxonomies);
78
+
79
+ const kinds = new Set(config.content.types.map((type) => type.kind));
80
+ if (config.app?.cms?.menu) {
81
+ config.app.cms.menu = config.app.cms.menu.filter((item) => !item.kinds || item.kinds.some((kind) => kinds.has(kind)));
82
+ }
83
+
84
+ if (Array.isArray(a.modules)) {
85
+ config.modules = Object.fromEntries(Object.entries(config.modules || {}).filter(([name]) => a.modules.includes(name)));
86
+ }
87
+
88
+ if (config.app) {
89
+ if (a.name) config.app.name = a.name;
90
+ if (a.brandColor) config.app.theme = { ...config.app.theme, colors: { ...config.app.theme?.colors, brand: a.brandColor, ring: a.brandColor } };
91
+ if (Array.isArray(a.categories) && a.categories.length) config.app.apps = { ...config.app.apps, categories: a.categories };
92
+ }
93
+
94
+ return config;
95
+ }
96
+
97
+ /**
98
+ * Asks for each section of platform.json, in order. Enter keeps the default.
99
+ */
100
+ export async function askPlatform(base, { name: suggested = '' } = {}) {
101
+ try {
102
+ const answers = {};
103
+ p.log.step('platform');
104
+ answers.name = check(await p.text({ message: 'Platform name', initialValue: suggested, placeholder: suggested }));
105
+ answers.author = check(await p.text({ message: 'Author (optional)', defaultValue: '', placeholder: '' }));
106
+ answers.url = check(await p.text({ message: 'Website (optional)', defaultValue: '', placeholder: 'https://' }));
107
+
108
+ p.log.step('languages');
109
+ const defaults = (base.languages || []).map((l) => l.code);
110
+ answers.languages = check(await p.multiselect({
111
+ message: 'Languages',
112
+ options: LANGUAGES.map(([code, label]) => ({ value: code, label: `${label} (${code})` })),
113
+ initialValues: defaults.filter((code) => LANGUAGES.some(([c]) => c === code)),
114
+ required: true,
115
+ }));
116
+ answers.defaultLanguage = answers.languages.length > 1
117
+ ? check(await p.select({ message: 'Default language', options: answers.languages.map((code) => ({ value: code, label: code })), initialValue: answers.languages.includes(base.default_language) ? base.default_language : answers.languages[0] }))
118
+ : answers.languages[0];
119
+
120
+ p.log.step('content');
121
+ answers.template = check(await p.select({
122
+ message: 'Content types',
123
+ options: [
124
+ { value: 'default', label: 'Start from the default set', hint: (base.content?.types || []).map((t) => t.label).join(', ') },
125
+ { value: 'empty', label: 'Start empty' },
126
+ ],
127
+ }));
128
+ answers.types = [];
129
+ while (check(await p.confirm({ message: answers.types.length ? 'Add another content type?' : 'Add a content type?', initialValue: answers.template === 'empty' && !answers.types.length }))) {
130
+ const label = check(await p.text({ message: 'Name (plural)', placeholder: 'Products', validate: (v) => (key(v) ? undefined : 'Enter a name') }));
131
+ const singular = check(await p.text({ message: 'Singular', initialValue: label.replace(/s$/i, '') }));
132
+ const kind = check(await p.select({ message: 'Shown in the CMS under', options: Object.entries(KINDS).map(([value, label]) => ({ value, label })) }));
133
+ const fields = check(await p.text({ message: `Fields (name:type, comma separated). Types: ${FIELD_TYPES.join(', ')}`, placeholder: 'price:number, color:select(red|blue), gallery:files', defaultValue: '' }));
134
+ answers.types.push(contentType({ label, singular, kind, fields: parseFields(fields) }));
135
+ }
136
+ answers.taxonomies = [];
137
+ const typeKeys = [...(answers.template === 'empty' ? [] : (base.content?.types || []).map((t) => t.key)), ...answers.types.map((t) => t.key)];
138
+ while (typeKeys.length && check(await p.confirm({ message: answers.taxonomies.length ? 'Add another taxonomy?' : 'Add a taxonomy (categories, tags)?', initialValue: false }))) {
139
+ const label = check(await p.text({ message: 'Name (plural)', placeholder: 'Categories', validate: (v) => (key(v) ? undefined : 'Enter a name') }));
140
+ const hierarchical = check(await p.confirm({ message: 'Nested (like categories)?', initialValue: true }));
141
+ const types = check(await p.multiselect({ message: 'For which content types?', options: typeKeys.map((value) => ({ value, label: value })), required: true }));
142
+ answers.taxonomies.push({ key: key(label), label, singular: label.replace(/ies$/i, 'y').replace(/s$/i, ''), hierarchical, types, translate: true });
143
+ }
144
+
145
+ p.log.step('modules');
146
+ answers.modules = check(await p.multiselect({
147
+ message: 'Modules',
148
+ options: Object.entries(base.modules || {}).map(([value, module]) => ({ value, label: module.label || value })),
149
+ initialValues: Object.keys(base.modules || {}),
150
+ required: false,
151
+ }));
152
+
153
+ p.log.step('app');
154
+ answers.brandColor = check(await p.text({ message: 'Brand color', initialValue: base.app?.theme?.colors?.brand || '#8b7cf6', validate: (v) => (/^#[0-9a-f]{3,8}$/i.test(v) ? undefined : 'Use a hex color, e.g. #8b7cf6') }));
155
+ const categories = check(await p.text({ message: 'App categories (comma separated)', initialValue: (base.app?.apps?.categories || []).join(', ') }));
156
+ answers.categories = categories.split(',').map((c) => c.trim()).filter(Boolean);
157
+
158
+ return answers;
159
+ } catch (error) {
160
+ if (error instanceof Cancelled) return null;
161
+ throw error;
162
+ }
163
+ }
package/src/main.js CHANGED
@@ -6,7 +6,9 @@ import { parseArgs, UsageError } from './args.js';
6
6
  import { startApp } from './commands/start.js';
7
7
  import { buildAll } from './commands/build.js';
8
8
  import { doctor } from './commands/doctor.js';
9
- import { PLATFORM_DIR, apps, composer, init, newApp, newPlugin, platformRoot, plugins, update } from './commands/platform.js';
9
+ import * as p from '@clack/prompts';
10
+ import { PLATFORM_DIR, apps, bundledPlatform, composer, init, newApp, newPlugin, platformRoot, plugins, update } from './commands/platform.js';
11
+ import { askPlatform } from './commands/setup.js';
10
12
  import { sandbox } from './commands/sandbox.js';
11
13
  import { tui } from './tui.js';
12
14
 
@@ -19,7 +21,10 @@ Usage:
19
21
  wp-ops interactive menu
20
22
 
21
23
  Platform repository:
22
- wp-ops init [dir] create a platform repository: the platform (wp-operations/), layout, workflows, git
24
+ wp-ops init [dir] create a platform repository: asks for each section of platform.json
25
+ (name, languages, content types, taxonomies, modules, app), then
26
+ writes the platform (wp-operations/), layout, workflows and git
27
+ [--yes: default platform.json] [--template=empty]
23
28
  wp-ops start [--port=] run the platform locally (admin / password)
24
29
  wp-ops update update wp-operations/ to the platform shipped with this wp-ops
25
30
  wp-ops apps list apps (<kind>/<slug>) and their deploy targets
@@ -70,7 +75,22 @@ async function run() {
70
75
  await doctor();
71
76
  return;
72
77
  case 'init':
73
- await init({ dir: positional[0] ?? process.cwd(), platform: options.platform, version: pkg.version });
78
+ {
79
+ const dir = path.resolve(positional[0] ?? process.cwd());
80
+ const source = options.platform ? path.resolve(options.platform) : bundledPlatform();
81
+ const baseFile = source && fs.existsSync(source) && fs.statSync(source).isDirectory() ? path.join(source, 'platform.json') : source;
82
+ let answers = options.template === 'empty' ? { template: 'empty', name: path.basename(dir) } : null;
83
+ if (!answers && options.yes !== true && process.stdin.isTTY && baseFile && fs.existsSync(baseFile) && !fs.existsSync(path.join(dir, 'platform.json'))) {
84
+ p.intro(`wp-ops init ${path.basename(dir)}`);
85
+ answers = await askPlatform(JSON.parse(fs.readFileSync(baseFile, 'utf8')), { name: path.basename(dir) });
86
+ if (!answers) {
87
+ p.cancel('Nothing created.');
88
+ return;
89
+ }
90
+ p.outro('Creating the platform repository');
91
+ }
92
+ await init({ dir, platform: options.platform, version: pkg.version, answers });
93
+ }
74
94
  return;
75
95
  case 'apps':
76
96
  await apps({ root: await platformRoot() });
@@ -1,5 +1,10 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.2
4
+
5
+ - changed logo size from mine to my father's (tried to fool boss)
6
+ - Theme updates work while the repository is private: set `PLATFORM_UPDATES_TOKEN` in wp-config.php.
7
+
3
8
  ## 0.1.1
4
9
 
5
10
  - Sign-in screen shows the platform logo again (your Site Logo when set) and no longer scrolls.
@@ -14,6 +14,7 @@ define( 'PLATFORM_OPENAI_KEY', 'sk-…' ); // one constant per AI mod
14
14
  define( 'PLATFORM_SANDBOX_TOKEN', '…' ); // optional, per sandbox (same value as SANDBOX_TOKEN for wp-ops sandbox)
15
15
  define( 'PLATFORM_STORAGE_BUCKET', '…' ); // optional S3/R2 storage: PLATFORM_STORAGE_ENDPOINT, _BUCKET, _ACCESS_KEY, _SECRET_KEY, _PUBLIC_URL
16
16
  define( 'PLATFORM_CONFIG', '/path/to/platform.json' ); // optional: use another platform.json than the theme's
17
+ define( 'PLATFORM_UPDATES_TOKEN', 'github_pat_…' ); // needed for theme updates while the wp-operations repository is private (read access to its releases)
17
18
  ```
18
19
 
19
20
  ## Settings
@@ -9,7 +9,7 @@ body.platform-gate,body.login{margin:0;background:var(--bg);color:var(--text);fo
9
9
  .gate{box-sizing:border-box;min-height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;padding:48px 20px;position:relative;overflow:hidden}
10
10
  .gate__glow{position:absolute;inset:-40% -20% auto;height:90%;background:radial-gradient(50% 50% at 50% 40%,rgba(255,255,255,.07),transparent 70%);pointer-events:none}
11
11
  .gate__card{position:relative;width:100%;max-width:380px;background:linear-gradient(180deg,rgba(255,255,255,.035),rgba(255,255,255,.01));border:1px solid var(--line);border-radius:20px;padding:36px 32px 28px;box-shadow:0 30px 80px -20px rgba(0,0,0,.7)}
12
- .gate__mark{display:block;width:56px;height:56px;object-fit:contain;margin:0 auto 20px}
12
+ .gate__mark{display:block;width:80px;height:80px;object-fit:contain;margin:0 auto 20px}
13
13
  .gate h1{font-size:20px;font-weight:600;letter-spacing:-.01em;text-align:center;margin:0 0 24px}
14
14
  .gate__lead{color:var(--muted);text-align:center;margin:0 0 24px}
15
15
  .gate__foot{position:relative;margin-top:28px;color:var(--faint);font-size:12px}
@@ -15,13 +15,42 @@ final class Updates {
15
15
  const TAG = 'theme-v';
16
16
  const ASSET = 'wp-operations.zip';
17
17
  const CACHE = 'platform_theme_release';
18
+ const TOKEN = 'PLATFORM_UPDATES_TOKEN';
18
19
 
19
20
  public static function register(): void {
20
21
  add_filter( 'pre_set_site_transient_update_themes', [ __CLASS__, 'check' ] );
22
+ add_filter( 'http_request_args', [ __CLASS__, 'authorize' ], 10, 2 );
21
23
  add_action( 'upgrader_process_complete', [ __CLASS__, 'forget' ], 10, 0 );
22
24
  add_action( 'wp_ajax_platform_theme_changelog', [ __CLASS__, 'changelog' ] );
23
25
  }
24
26
 
27
+ private static function token(): string {
28
+ return defined( self::TOKEN ) ? trim( (string) constant( self::TOKEN ) ) : '';
29
+ }
30
+
31
+ /**
32
+ * With PLATFORM_UPDATES_TOKEN set (needed while the repository is private),
33
+ * GitHub API requests to this repository carry the token, and the release
34
+ * asset is downloaded through the API.
35
+ */
36
+ public static function authorize( array $args, string $url ): array {
37
+ $token = self::token();
38
+
39
+ if ( '' === $token || 0 !== strpos( $url, 'https://api.github.com/repos/' . self::REPOSITORY . '/' ) ) {
40
+ return $args;
41
+ }
42
+
43
+ $args['headers'] = (array) ( $args['headers'] ?? [] );
44
+ $args['headers']['Authorization'] = 'Bearer ' . $token;
45
+ $args['headers']['User-Agent'] = 'wp-operations';
46
+
47
+ if ( false !== strpos( $url, '/releases/assets/' ) ) {
48
+ $args['headers']['Accept'] = 'application/octet-stream';
49
+ }
50
+
51
+ return $args;
52
+ }
53
+
25
54
  public static function changelog(): void {
26
55
  if ( ! current_user_can( 'update_themes' ) ) {
27
56
  wp_die( esc_html__( 'Sorry, you are not allowed to update themes.', 'wp-operations' ), 403 );
@@ -131,7 +160,7 @@ final class Updates {
131
160
  $release = [
132
161
  'version' => substr( $tag, strlen( self::TAG ) ),
133
162
  'url' => esc_url_raw( (string) ( $item['html_url'] ?? '' ) ),
134
- 'package' => esc_url_raw( (string) ( $asset['browser_download_url'] ?? '' ) ),
163
+ 'package' => esc_url_raw( (string) ( '' !== self::token() ? ( $asset['url'] ?? '' ) : ( $asset['browser_download_url'] ?? '' ) ) ),
135
164
  'notes' => (string) ( $item['body'] ?? '' ),
136
165
  ];
137
166
  break 2;
@@ -2,8 +2,8 @@
2
2
  Theme Name: wp-operations
3
3
  Theme URI: https://github.com/wordpress-operations/wordpress-operations
4
4
  Author: wp-operations
5
- Description: The wp-operations platform: content engine (platform.json), CMS, app builder and operations for one platform repository.
6
- Version: 0.1.1
5
+ Description: wp-operations: AI-powered content engine with platform builder, CMS and operations for one repository.
6
+ Version: 0.1.2
7
7
  Requires at least: 6.4
8
8
  Requires PHP: 8.0
9
9
  License: GPL-2.0-or-later