-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathphp-bootstrap.ts
More file actions
288 lines (252 loc) · 12.8 KB
/
Copy pathphp-bootstrap.ts
File metadata and controls
288 lines (252 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
import { readFile } from "node:fs/promises"
import { argValue, normalizePhpCode, phpBody } from "./commands.js"
import { phpCliStreamConstants, phpEnvAssignments, phpRuntimeRecipePluginPreloadFunction, phpWpConfigDefineAssignments } from "./php-snippets.js"
import { normalizeRuntimeEnvRecord, resolveCommandPath, type RuntimeCreateSpec } from "@automattic/wp-codebox-core"
interface PhpBootstrapBridge {
url: string
token: string
}
export function bootstrapAbilityPhpCode(spec: RuntimeCreateSpec, code: string): string {
return `<?php
${phpFatalDiagnosticPhp()}
define( 'REST_REQUEST', true );
$_SERVER['REQUEST_URI'] = '/wp-json/wp-codebox/ability';
${runtimeEnvPhp(spec)}
${secretEnvPhp(spec)}
${componentManifestPhp(spec)}
require_once '/wordpress/wp-load.php';
${phpBody(code)}`
}
export function bootstrapPhpCode(spec: RuntimeCreateSpec, code: string, args: string[], wpCliBridge?: PhpBootstrapBridge, failureDiagnosticFile?: string): string {
const bootstrapMode = argValue(args, "bootstrap")
if (bootstrapMode === "none") {
return code
}
const command = splitLeadingStrictTypesDeclare(code)
const bootstrapped = `<?php
${command.strictTypesDeclare ? `${command.strictTypesDeclare}\n` : ""}${phpFatalDiagnosticPhp()}
${failureDiagnosticFile ? phpFailureDiagnosticFilePhp(failureDiagnosticFile) : ""}
${phpCliStreamConstants()}
${pluginRuntimeBootstrapPhp(spec)}
${saveQueriesBootstrapPhp(args)}
${runtimeEnvPhp(spec, args)}
${secretEnvPhp(spec)}
${componentManifestPhp(spec)}
${bootstrapMode === "runtime-only" ? "" : "require_once '/wordpress/wp-load.php';"}
${failureDiagnosticFile ? phpFailureDiagnosticCompletionPhp() : ""}
${bootstrapMode === "runtime-only" ? "" : recipeActivePluginBootstrapPhp(spec, args)}
${wpCliBridge ? `putenv(${JSON.stringify(`WP_CODEBOX_TERMINAL_ACTION_URL=${wpCliBridge.url}`)});
putenv(${JSON.stringify(`WP_CODEBOX_TERMINAL_ACTION_TOKEN=${wpCliBridge.token}`)});
` : ""}
${command.body}`
return failureDiagnosticFile && bootstrapMode !== "runtime-only" ? phpFailureDiagnosticWrapperPhp(bootstrapped, failureDiagnosticFile) : bootstrapped
}
function phpFailureDiagnosticWrapperPhp(code: string, path: string): string {
return `<?php
try {
eval('?>' . base64_decode(${JSON.stringify(Buffer.from(code, "utf8").toString("base64"))}));
} catch (Throwable $wp_codebox_bootstrap_throwable) {
@file_put_contents(${JSON.stringify(path)}, 'STAGE_FAIL:bootstrap:' . get_class($wp_codebox_bootstrap_throwable) . ': ' . $wp_codebox_bootstrap_throwable->getMessage() . ' at ' . $wp_codebox_bootstrap_throwable->getFile() . ':' . $wp_codebox_bootstrap_throwable->getLine() . "\\n", FILE_APPEND);
throw $wp_codebox_bootstrap_throwable;
}`
}
function phpFailureDiagnosticFilePhp(path: string): string {
return `$wp_codebox_bootstrap_complete = false;
$wp_codebox_bootstrap_buffer_level = ob_get_level();
ob_start();
register_shutdown_function(static function () use (&$wp_codebox_bootstrap_complete, $wp_codebox_bootstrap_buffer_level): void {
if ($wp_codebox_bootstrap_complete) {
return;
}
$wp_codebox_bootstrap_output = '';
while (ob_get_level() > $wp_codebox_bootstrap_buffer_level) {
$wp_codebox_bootstrap_chunk = ob_get_clean();
if ($wp_codebox_bootstrap_chunk !== false) {
$wp_codebox_bootstrap_output = $wp_codebox_bootstrap_chunk . $wp_codebox_bootstrap_output;
}
}
$wp_codebox_failure = error_get_last();
if (is_array($wp_codebox_failure) && in_array($wp_codebox_failure['type'] ?? 0, array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR, E_RECOVERABLE_ERROR), true)) {
$wp_codebox_bootstrap_diagnostic = 'STAGE_FATAL:bootstrap:' . (string) ($wp_codebox_failure['message'] ?? '') . ' at ' . (string) ($wp_codebox_failure['file'] ?? '') . ':' . (int) ($wp_codebox_failure['line'] ?? 0);
} else {
$wp_codebox_bootstrap_detail = trim((string) preg_replace('/\\s+/', ' ', strip_tags($wp_codebox_bootstrap_output)));
if ($wp_codebox_bootstrap_detail === '') {
$wp_codebox_bootstrap_detail = 'WordPress bootstrap terminated before completion without emitting output';
}
$wp_codebox_bootstrap_diagnostic = 'STAGE_DIE:bootstrap:' . substr($wp_codebox_bootstrap_detail, 0, 16384);
}
@file_put_contents(${JSON.stringify(path)}, $wp_codebox_bootstrap_diagnostic . "\\n", FILE_APPEND);
});`
}
function phpFailureDiagnosticCompletionPhp(): string {
return `$wp_codebox_bootstrap_complete = true;
$wp_codebox_bootstrap_output = '';
while (ob_get_level() > $wp_codebox_bootstrap_buffer_level) {
$wp_codebox_bootstrap_chunk = ob_get_clean();
if ($wp_codebox_bootstrap_chunk !== false) {
$wp_codebox_bootstrap_output = $wp_codebox_bootstrap_chunk . $wp_codebox_bootstrap_output;
}
}
echo $wp_codebox_bootstrap_output;`
}
export function splitLeadingStrictTypesDeclare(code: string): { strictTypesDeclare: string; body: string } {
const normalized = normalizePhpCode(code)
const match = normalized.match(/^<\?php\s*(declare\s*\(\s*strict_types\s*=\s*1\s*\)\s*;)\s*/i)
return match
? { strictTypesDeclare: match[1], body: normalized.slice(match[0].length) }
: { strictTypesDeclare: "", body: phpBody(normalized) }
}
function saveQueriesBootstrapPhp(args: string[]): string {
const capture = argValue(args, "capture-diagnostics")
if (!capture?.split(",").map((item) => item.trim()).includes("wpdb-queries")) {
return ""
}
return `if (!defined('SAVEQUERIES')) {
define('SAVEQUERIES', true);
}
`
}
function phpFatalDiagnosticPhp(): string {
return `register_shutdown_function(static function (): void {
$contained_runtime_fatal = error_get_last();
if (!is_array($contained_runtime_fatal) || !in_array($contained_runtime_fatal['type'] ?? 0, array(E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR), true)) {
return;
}
echo "\nWP_CODEBOX_PHP_FATAL_DIAGNOSTIC:" . json_encode(array(
'schema' => 'wp-codebox/php-fatal-diagnostic/v1',
'message' => isset($contained_runtime_fatal['message']) ? (string) $contained_runtime_fatal['message'] : '',
'file' => isset($contained_runtime_fatal['file']) ? (string) $contained_runtime_fatal['file'] : '',
'line' => isset($contained_runtime_fatal['line']) ? (int) $contained_runtime_fatal['line'] : 0,
'type' => isset($contained_runtime_fatal['type']) ? (int) $contained_runtime_fatal['type'] : 0,
), JSON_UNESCAPED_SLASHES) . "\n";
});`
}
interface RecipePluginMetadata {
slug?: unknown
pluginFile?: unknown
target?: unknown
activate?: unknown
loadAs?: unknown
}
function recipeActivePluginBootstrapPhp(spec: RuntimeCreateSpec, args: string[]): string {
if (argValue(args, "recipe-active-plugins") === "none") {
return ""
}
const plugins = recipeActivePluginMetadata(spec)
if (plugins.length === 0) {
return ""
}
return `${phpRuntimeRecipePluginPreloadFunction("contained_runtime_run_php")}
$contained_runtime_run_php_active_plugins = json_decode(base64_decode('${Buffer.from(JSON.stringify(plugins), "utf8").toString("base64")}'), true);
foreach (is_array($contained_runtime_run_php_active_plugins) ? $contained_runtime_run_php_active_plugins : array() as $contained_runtime_run_php_active_plugin) {
if (is_array($contained_runtime_run_php_active_plugin)) {
contained_runtime_run_php_preload_recipe_plugin($contained_runtime_run_php_active_plugin, true, 'active-recipe-plugin', 'wordpress.run-php');
}
}
`
}
function recipeActivePluginMetadata(spec: RuntimeCreateSpec): RecipePluginMetadata[] {
const recipe = spec.metadata?.recipe && typeof spec.metadata.recipe === "object" && !Array.isArray(spec.metadata.recipe)
? spec.metadata.recipe as { inputs?: { extra_plugins?: unknown } }
: undefined
const task = spec.metadata?.task && typeof spec.metadata.task === "object" && !Array.isArray(spec.metadata.task)
? spec.metadata.task as { inputs?: { extra_plugins?: unknown } }
: undefined
const extraPlugins = Array.isArray(recipe?.inputs?.extra_plugins)
? recipe.inputs.extra_plugins
: Array.isArray(task?.inputs?.extra_plugins)
? task.inputs.extra_plugins
: []
const plugins: RecipePluginMetadata[] = extraPlugins
.filter((plugin): plugin is RecipePluginMetadata => Boolean(plugin) && typeof plugin === "object" && !Array.isArray(plugin))
.filter((plugin) => plugin.loadAs !== "mu-plugin" && plugin.activate !== false)
.map((plugin) => ({
slug: typeof plugin.slug === "string" ? plugin.slug : undefined,
pluginFile: typeof plugin.pluginFile === "string" && /^[^/][^:]*\.php$/.test(plugin.pluginFile) && !plugin.pluginFile.includes("..") ? plugin.pluginFile : undefined,
target: typeof plugin.target === "string" ? plugin.target : undefined,
activate: plugin.activate,
loadAs: plugin.loadAs,
}))
return plugins.filter((plugin) => typeof plugin.pluginFile === "string")
}
export async function phpCodeFromArgs(args: string[], command = "wordpress.run-php", normalize = true): Promise<string> {
const inlineCode = argValue(args, "code")
if (inlineCode) {
return normalize ? normalizePhpCode(inlineCode) : inlineCode
}
const codeFile = argValue(args, "code-file")
if (codeFile) {
const code = await readFile(resolveCommandPath(codeFile), "utf8")
return normalize ? normalizePhpCode(code) : code
}
throw new Error(`${command} requires code=<php> or code-file=<path>`)
}
function pluginRuntimeBootstrapPhp(spec: RuntimeCreateSpec): string {
const pluginRuntime = spec.metadata?.recipe && typeof spec.metadata.recipe === "object" && !Array.isArray(spec.metadata.recipe)
? (spec.metadata.recipe as { inputs?: { pluginRuntime?: unknown } }).inputs?.pluginRuntime
: undefined
if (!pluginRuntime || typeof pluginRuntime !== "object" || Array.isArray(pluginRuntime)) {
return ""
}
const runtime = pluginRuntime as { php?: { memoryLimit?: unknown; maxExecutionTime?: unknown }; wpConfigDefines?: Record<string, unknown> }
const lines: string[] = []
const memoryLimit = typeof runtime.php?.memoryLimit === "string" ? runtime.php.memoryLimit : undefined
if (memoryLimit && /^[0-9]+[KMG]?$/.test(memoryLimit)) {
lines.push(`@ini_set('memory_limit', ${JSON.stringify(memoryLimit)});`)
}
const maxExecutionTime = runtime.php?.maxExecutionTime
if (Number.isInteger(maxExecutionTime) && typeof maxExecutionTime === "number" && maxExecutionTime >= 0 && maxExecutionTime <= 3600) {
lines.push(`@set_time_limit(${maxExecutionTime});`)
}
const wpConfigDefines = phpWpConfigDefineAssignments(runtime.wpConfigDefines ?? {}).trim()
if (wpConfigDefines) {
lines.push(wpConfigDefines)
}
return lines.length > 0 ? `${lines.join("\n")}\n` : ""
}
function componentManifestPhp(spec: RuntimeCreateSpec): string {
const manifest = componentManifest(spec)
if (!manifest) {
return ""
}
const encoded = Buffer.from(JSON.stringify(manifest), "utf8").toString("base64")
return `$contained_runtime_component_manifest = json_decode(base64_decode('${encoded}'), true);
if (is_array($contained_runtime_component_manifest)) {
$GLOBALS['contained_runtime_component_manifest'] = $contained_runtime_component_manifest;
if (!defined('CONTAINED_RUNTIME_COMPONENT_MANIFEST_JSON')) {
define('CONTAINED_RUNTIME_COMPONENT_MANIFEST_JSON', json_encode($contained_runtime_component_manifest, JSON_UNESCAPED_SLASHES));
}
}
`
}
function componentManifest(spec: RuntimeCreateSpec): unknown {
const recipeManifest = metadataInputs(spec.metadata?.recipe)?.component_manifest
if (recipeManifest && typeof recipeManifest === "object" && !Array.isArray(recipeManifest)) {
return recipeManifest
}
const taskManifest = metadataInputs(spec.metadata?.task)?.component_manifest
if (taskManifest && typeof taskManifest === "object" && !Array.isArray(taskManifest)) {
return taskManifest
}
return undefined
}
function metadataInputs(value: unknown): Record<string, unknown> | undefined {
if (!value || typeof value !== "object" || Array.isArray(value)) {
return undefined
}
const inputs = (value as { inputs?: unknown }).inputs
return inputs && typeof inputs === "object" && !Array.isArray(inputs) ? inputs as Record<string, unknown> : undefined
}
function secretEnvPhp(spec: RuntimeCreateSpec): string {
return phpEnvAssignments(normalizeRuntimeEnvRecord(spec.secretEnv ?? {}, { field: "secretEnv" }))
}
function runtimeEnvPhp(spec: RuntimeCreateSpec, args: string[] = []): string {
const override = argValue(args, "runtime-env-json")
let executionEnvironment: Record<string, unknown> = {}
if (override) {
const parsed = JSON.parse(override) as unknown
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("runtime-env-json must be a JSON object")
executionEnvironment = parsed as Record<string, unknown>
}
return phpEnvAssignments(normalizeRuntimeEnvRecord({ ...(spec.runtimeEnv ?? {}), ...executionEnvironment }, { field: "runtimeEnv" }))
}