@php-wasm/compile-extension 3.1.26 → 3.1.28

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
@@ -46,13 +46,14 @@ creates them before PHP starts.
46
46
 
47
47
  The supported `--php-versions` are `7.4` and `8.0` through `8.5`.
48
48
 
49
- Docker is required. The build reuses the `packages/php-wasm/compile` base image
50
- and its PHP patch set, then runs `phpize`, `emconfigure`, and `emmake` inside
51
- the container.
49
+ Docker is required. The CLI lazily fetches the small PHP.wasm Docker asset set
50
+ needed to prepare the Emscripten base image and all `compile/php/php*.patch`
51
+ files, then runs `phpize`, `emconfigure`, and `emmake` inside the container.
52
52
 
53
53
  ## Running in CI
54
54
 
55
- The package only needs Docker and Node. A typical GitHub Actions job:
55
+ The package only needs Docker and Node. It does not require a checkout of
56
+ `WordPress/wordpress-playground`. A typical GitHub Actions job:
56
57
 
57
58
  ```yaml
58
59
  - uses: actions/checkout@v4
@@ -73,6 +74,34 @@ In a matrix workflow, set `strategy.max-parallel: 1` on the WASM job —
73
74
  parallel Docker builds on hosted runners often hit apt-mirror flakes during
74
75
  the base image build.
75
76
 
77
+ On first use, a published `@php-wasm/compile-extension` package fetches Docker
78
+ assets from the matching `WordPress/wordpress-playground` tag, such as
79
+ `v3.1.27` for package version `3.1.27`. When running from a Playground
80
+ workspace, it uses local workspace assets when available and otherwise fetches
81
+ from `trunk`. Fetched assets are cached under
82
+ `~/.cache/php-wasm/compile-extension/docker-assets`, or under
83
+ `PHP_WASM_COMPILE_EXTENSION_CACHE_DIR` when that environment variable is set.
84
+
85
+ ## Preparing the build image
86
+
87
+ Advanced workflows may need to run another build step inside the same
88
+ Emscripten/PHP image before compiling the final phpize extension. For example,
89
+ a Rust extension can build a `wasm32-unknown-emscripten` `staticlib` first and
90
+ then pass that archive through `--extra-ldflags`.
91
+
92
+ Use `--prepare-image` to build the package-owned Docker image and exit without
93
+ compiling an extension source directory:
94
+
95
+ ```bash
96
+ npx @php-wasm/compile-extension \
97
+ --prepare-image \
98
+ --php-versions 8.4 \
99
+ --jobs 1
100
+ ```
101
+
102
+ For PHP `8.4`, the prepared image tag is
103
+ `playground-php-wasm:compile-extension-php8-4-jspi`.
104
+
76
105
  ## Loading the result
77
106
 
78
107
  Host the entire output directory somewhere static and pass the manifest URL to
@@ -146,21 +175,11 @@ The helper can only link WebAssembly objects built with the same Emscripten
146
175
  toolchain and JSPI ABI as the PHP runtime. Native host libraries from
147
176
  `/usr/lib`, Homebrew, apt, or npm packages cannot be linked into the `.so`.
148
177
 
149
- For dependencies already built by Playground, build the matching target and pass
150
- the mounted path under `/php-wasm-compile`:
151
-
152
- ```bash
153
- make -C packages/php-wasm/compile libz_jspi
154
-
155
- npx @php-wasm/compile-extension \
156
- --source ./zlib-probe \
157
- --name zlib_probe \
158
- --php-versions 8.4 \
159
- --extra-cflags "-I/php-wasm-compile/libz/jspi/dist/root/lib/include" \
160
- --extra-ldflags "/php-wasm-compile/libz/jspi/dist/root/lib/lib/libz.a"
161
- ```
178
+ The lazy-fetched asset set includes only the Docker files required for the PHP
179
+ extension build itself. It does not include prebuilt Playground dependency
180
+ archives such as `libz`, `libxml2`, or `libpng`.
162
181
 
163
- For dependencies that are not in `packages/php-wasm/compile`, either:
182
+ For dependencies:
164
183
 
165
184
  - Vendor the dependency source under your extension and build it from
166
185
  `config.m4`, using paths under `/build` after the helper copies `/src`.
@@ -286,6 +305,11 @@ patch the extension's build recipe to use the WebAssembly archive directly.
286
305
  Static `.a` archives passed via `--extra-ldflags` are force-linked with
287
306
  `--whole-archive` so the side module contains the dependency code it needs.
288
307
 
308
+ When developing inside the WordPress Playground monorepo, the CLI still prefers
309
+ the workspace Docker assets. In that monorepo-only workflow, dependency archives
310
+ built under `packages/php-wasm/compile` are mounted at `/php-wasm-compile`.
311
+ Package consumers should not need that path in CI.
312
+
289
313
  ## Troubleshooting
290
314
 
291
315
  `Could not detect the extension name`
@@ -296,9 +320,10 @@ Pass `--name` explicitly, or make sure `config.m4` contains `PHP_ARG_ENABLE`,
296
320
  `configure: error: ... not found`
297
321
 
298
322
  The dependency headers or libraries are not visible inside the container. Use
299
- paths under `/build` for files copied from `--source`, or
300
- `/php-wasm-compile/<dependency>/<mode>/dist/root/lib` for Playground-built
301
- dependencies.
323
+ paths under `/build` for files copied from `--source`. The
324
+ `/php-wasm-compile/<dependency>/<mode>/dist/root/lib` paths are only available
325
+ when running inside a WordPress Playground monorepo checkout with those
326
+ dependency archives already built.
302
327
 
303
328
  `undefined symbol` when loading the extension
304
329
 
@@ -0,0 +1,10 @@
1
+ import{createHash as v}from"node:crypto";import d from"node:fs";import{readFile as x,rm as S,mkdir as m,writeFile as y}from"node:fs/promises";import u from"node:path";import{init as P,readObject as k,listServerRefs as j,indexPack as B}from"isomorphic-git";import R from"isomorphic-git/http/node";async function M({repoUrl:t,ref:e,paths:n,outDir:a,workDir:r}){if(n.length===0)return[];await S(r,{recursive:!0,force:!0}),await m(r,{recursive:!0}),await P({fs:d,dir:r,defaultBranch:"trunk"});const o=await F(t,e);await b({repoUrl:t,dir:r,packfileName:"trees.pack",body:G(o)});const i=await w(r,o,"commit"),l=await w(r,i.tree,"tree"),s=new Map;for(const c of n)for(const[h,p]of await A(r,l,c))s.set(h,p);return await b({repoUrl:t,dir:r,packfileName:"blobs.pack",body:O(Array.from(s.values(),c=>c.oid))}),await Promise.all(Array.from(s,async([c,h])=>{const p=await k({fs:d,dir:r,oid:h.oid,format:"content"});if(p.type!=="blob")throw new Error(`Expected ${c} to resolve to a Git blob, got ${p.type}.`);const g=u.join(a,c);await m(u.dirname(g),{recursive:!0}),await y(g,p.object)})),Array.from(s.keys()).sort()}async function F(t,e){const n=e.startsWith("refs/")?e:T(e),r=(await j({http:R,url:t,prefix:n,peelTags:!0,protocolVersion:2})).find(o=>o.ref===n);if(!r)throw new Error(`Could not resolve ${n} from ${t}.`);return r.peeled??r.oid}function T(t){return t==="trunk"?"refs/heads/trunk":/^v?\d+\.\d+\.\d+/.test(t)?`refs/tags/${t.startsWith("v")?t:`v${t}`}`:`refs/heads/${t}`}async function b({repoUrl:t,dir:e,packfileName:n,body:a}){const r=await fetch(`${t}/git-upload-pack`,{method:"POST",headers:{accept:"application/x-git-upload-pack-result","content-type":"application/x-git-upload-pack-request","content-length":String(a.length)},body:a});if(!r.ok)throw new Error(`Git upload-pack request failed with ${r.status} ${r.statusText}.`);const o=q(Buffer.from(await r.arrayBuffer()));if(o.length===0)throw new Error("Git upload-pack response did not contain a packfile.");const i=u.join(e,".git/objects/pack",n);await m(u.dirname(i),{recursive:!0}),await y(i,o),await B({fs:d,dir:e,filepath:u.relative(e,i).split(u.sep).join("/")})}async function w(t,e,n){const a=await k({fs:d,dir:t,oid:e,format:"parsed"});if(a.type!==n)throw new Error(`Expected ${e} to be a ${n}, got ${a.type}.`);return a.object}async function A(t,e,n){const a=await $(t,e,n.split("/"),[]);if(a.length===0)throw new Error(`Path not found in the repo: ${n}`);return a}async function $(t,e,n,a){const[r,...o]=n,i=e.filter(s=>N(s.path,r));if(i.length===0)return[];const l=[];for(const s of i){const c=[...a,s.path];if(o.length===0){if(s.type!=="blob")throw new Error(`Expected ${c.join("/")} to resolve to a file.`);l.push([c.join("/"),s]);continue}s.type==="tree"&&l.push(...await $(t,await w(t,s.oid,"tree"),o,c))}return l}function N(t,e){return e.includes("*")?new RegExp(`^${e.split("*").map(C).join(".*")}$`).test(t):t===e}function C(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function G(t){return Buffer.concat([f(`want ${t} multi_ack_detailed no-done side-band-64k thin-pack ofs-delta agent=git/2.37.3 filter
2
+ `),f(`filter blob:none
3
+ `),f(`shallow ${t}
4
+ `),f(`deepen 1
5
+ `),E(),f(`done
6
+ `)])}function O(t){return Buffer.concat([...t.map(e=>f(`want ${e} multi_ack_detailed no-done side-band-64k thin-pack ofs-delta agent=git/2.37.3
7
+ `)),E(),f(`done
8
+ `)])}function q(t){const e=[];let n=0;for(;n+4<=t.length;){const a=Number.parseInt(t.subarray(n,n+4).toString("ascii"),16);if(n+=4,!Number.isFinite(a))throw new Error("Invalid Git pkt-line response.");if(a===0||a===1)continue;if(a===2)break;if(a<4)throw new Error("Invalid Git pkt-line response.");const r=a-4,o=t.subarray(n,n+r);if(n+=r,o.length===0||o.toString("utf8")===`NAK
9
+ `)continue;const i=o[0];if(i===1)e.push(o.subarray(1));else{if(i===2)continue;if(i===3)throw new Error(o.subarray(1).toString("utf8"));o.subarray(0,4).toString("ascii")==="PACK"&&e.push(o)}}return Buffer.concat(e)}function f(t){const e=Buffer.isBuffer(t)?t:Buffer.from(t),n=Buffer.from((e.length+4).toString(16).padStart(4,"0"));return Buffer.concat([n,e])}function E(){return Buffer.from("0000")}function W(t){return v("sha256").update(t).digest("hex").slice(0,16)}async function V(t){return JSON.parse(await x(t,"utf8"))}export{G as createTreeFetchRequest,q as parseUploadPackResponse,N as pathSegmentMatchesPattern,V as readJsonFile,M as sparseCheckoutFiles,W as stableHash};
10
+ //# sourceMappingURL=git-sparse-checkout-ClUpBgMv.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"git-sparse-checkout-ClUpBgMv.js","sources":["../../../../../packages/php-wasm/compile-extension/src/git-sparse-checkout.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport fs from 'node:fs';\nimport { mkdir, readFile, rm, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {\n\tindexPack,\n\tinit,\n\tlistServerRefs,\n\treadObject,\n\ttype CommitObject,\n\ttype TreeEntry,\n\ttype TreeObject,\n} from 'isomorphic-git';\nimport http from 'isomorphic-git/http/node';\n\n/**\n * Sparse-fetches blobs from a Git repository using the same protocol shape as\n * https://github.com/adamziel/git-sparse-checkout-in-js, with isomorphic-git\n * handling ref discovery, pack indexing, and object reads.\n */\nexport async function sparseCheckoutFiles({\n\trepoUrl,\n\tref,\n\tpaths,\n\toutDir,\n\tworkDir,\n}: {\n\trepoUrl: string;\n\tref: string;\n\tpaths: string[];\n\toutDir: string;\n\tworkDir: string;\n}): Promise<string[]> {\n\tif (paths.length === 0) {\n\t\treturn [];\n\t}\n\n\tawait rm(workDir, { recursive: true, force: true });\n\tawait mkdir(workDir, { recursive: true });\n\tawait init({ fs, dir: workDir, defaultBranch: 'trunk' });\n\n\tconst commitHash = await resolveRemoteCommit(repoUrl, ref);\n\tawait fetchAndIndexPack({\n\t\trepoUrl,\n\t\tdir: workDir,\n\t\tpackfileName: 'trees.pack',\n\t\tbody: createTreeFetchRequest(commitHash),\n\t});\n\n\tconst commit = await readParsedObject<CommitObject>(\n\t\tworkDir,\n\t\tcommitHash,\n\t\t'commit'\n\t);\n\tconst rootTree = await readParsedObject<TreeObject>(\n\t\tworkDir,\n\t\tcommit.tree,\n\t\t'tree'\n\t);\n\tconst entries = new Map<string, TreeEntry>();\n\tfor (const filepath of paths) {\n\t\tfor (const [matchedPath, entry] of await resolveTreeEntries(\n\t\t\tworkDir,\n\t\t\trootTree,\n\t\t\tfilepath\n\t\t)) {\n\t\t\tentries.set(matchedPath, entry);\n\t\t}\n\t}\n\n\tawait fetchAndIndexPack({\n\t\trepoUrl,\n\t\tdir: workDir,\n\t\tpackfileName: 'blobs.pack',\n\t\tbody: createObjectFetchRequest(\n\t\t\tArray.from(entries.values(), (entry) => entry.oid)\n\t\t),\n\t});\n\n\tawait Promise.all(\n\t\tArray.from(entries, async ([filepath, entry]) => {\n\t\t\tconst blob = await readObject({\n\t\t\t\tfs,\n\t\t\t\tdir: workDir,\n\t\t\t\toid: entry.oid,\n\t\t\t\tformat: 'content',\n\t\t\t});\n\t\t\tif (blob.type !== 'blob') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Expected ${filepath} to resolve to a Git blob, got ${blob.type}.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst outputPath = path.join(outDir, filepath);\n\t\t\tawait mkdir(path.dirname(outputPath), { recursive: true });\n\t\t\tawait writeFile(outputPath, blob.object);\n\t\t})\n\t);\n\n\treturn Array.from(entries.keys()).sort();\n}\n\nasync function resolveRemoteCommit(\n\trepoUrl: string,\n\tref: string\n): Promise<string> {\n\tconst fullRef = ref.startsWith('refs/') ? ref : refToFullRef(ref);\n\tconst refs = await listServerRefs({\n\t\thttp,\n\t\turl: repoUrl,\n\t\tprefix: fullRef,\n\t\tpeelTags: true,\n\t\tprotocolVersion: 2,\n\t});\n\tconst exactRef = refs.find((entry) => entry.ref === fullRef);\n\tif (!exactRef) {\n\t\tthrow new Error(`Could not resolve ${fullRef} from ${repoUrl}.`);\n\t}\n\treturn exactRef.peeled ?? exactRef.oid;\n}\n\nfunction refToFullRef(ref: string): string {\n\tif (ref === 'trunk') {\n\t\treturn 'refs/heads/trunk';\n\t}\n\tif (/^v?\\d+\\.\\d+\\.\\d+/.test(ref)) {\n\t\treturn `refs/tags/${ref.startsWith('v') ? ref : `v${ref}`}`;\n\t}\n\treturn `refs/heads/${ref}`;\n}\n\nasync function fetchAndIndexPack({\n\trepoUrl,\n\tdir,\n\tpackfileName,\n\tbody,\n}: {\n\trepoUrl: string;\n\tdir: string;\n\tpackfileName: string;\n\tbody: Buffer;\n}) {\n\tconst response = await fetch(`${repoUrl}/git-upload-pack`, {\n\t\tmethod: 'POST',\n\t\theaders: {\n\t\t\taccept: 'application/x-git-upload-pack-result',\n\t\t\t'content-type': 'application/x-git-upload-pack-request',\n\t\t\t'content-length': String(body.length),\n\t\t},\n\t\tbody,\n\t});\n\n\tif (!response.ok) {\n\t\tthrow new Error(\n\t\t\t`Git upload-pack request failed with ${response.status} ${response.statusText}.`\n\t\t);\n\t}\n\n\tconst packfile = parseUploadPackResponse(\n\t\tBuffer.from(await response.arrayBuffer())\n\t);\n\tif (packfile.length === 0) {\n\t\tthrow new Error('Git upload-pack response did not contain a packfile.');\n\t}\n\n\tconst packPath = path.join(dir, '.git/objects/pack', packfileName);\n\tawait mkdir(path.dirname(packPath), { recursive: true });\n\tawait writeFile(packPath, packfile);\n\tawait indexPack({\n\t\tfs,\n\t\tdir,\n\t\tfilepath: path.relative(dir, packPath).split(path.sep).join('/'),\n\t});\n}\n\nasync function readParsedObject<T>(\n\tdir: string,\n\toid: string,\n\texpectedType: 'commit' | 'tree'\n): Promise<T> {\n\tconst result = await readObject({\n\t\tfs,\n\t\tdir,\n\t\toid,\n\t\tformat: 'parsed',\n\t});\n\tif (result.type !== expectedType) {\n\t\tthrow new Error(`Expected ${oid} to be a ${expectedType}, got ${result.type}.`);\n\t}\n\treturn result.object as T;\n}\n\nasync function resolveTreeEntries(\n\tdir: string,\n\trootTree: TreeObject,\n\tfilepath: string\n): Promise<Array<[string, TreeEntry]>> {\n\tconst entries = await resolveTreeEntriesFromSegments(\n\t\tdir,\n\t\trootTree,\n\t\tfilepath.split('/'),\n\t\t[]\n\t);\n\tif (entries.length === 0) {\n\t\tthrow new Error(`Path not found in the repo: ${filepath}`);\n\t}\n\treturn entries;\n}\n\nasync function resolveTreeEntriesFromSegments(\n\tdir: string,\n\ttree: TreeObject,\n\tsegments: string[],\n\tresolvedSegments: string[]\n): Promise<Array<[string, TreeEntry]>> {\n\tconst [segment, ...remainingSegments] = segments;\n\tconst matchedEntries = tree.filter((entry) =>\n\t\tpathSegmentMatchesPattern(entry.path, segment)\n\t);\n\n\tif (matchedEntries.length === 0) {\n\t\treturn [];\n\t}\n\n\tconst matches: Array<[string, TreeEntry]> = [];\n\tfor (const entry of matchedEntries) {\n\t\tconst nextResolvedSegments = [...resolvedSegments, entry.path];\n\t\tif (remainingSegments.length === 0) {\n\t\t\tif (entry.type !== 'blob') {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Expected ${nextResolvedSegments.join('/')} to resolve to a file.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tmatches.push([nextResolvedSegments.join('/'), entry]);\n\t\t\tcontinue;\n\t\t}\n\t\tif (entry.type !== 'tree') {\n\t\t\tcontinue;\n\t\t}\n\t\tmatches.push(\n\t\t\t...(await resolveTreeEntriesFromSegments(\n\t\t\t\tdir,\n\t\t\t\tawait readParsedObject<TreeObject>(dir, entry.oid, 'tree'),\n\t\t\t\tremainingSegments,\n\t\t\t\tnextResolvedSegments\n\t\t\t))\n\t\t);\n\t}\n\n\treturn matches;\n}\n\nexport function pathSegmentMatchesPattern(\n\tsegment: string,\n\tpattern: string\n): boolean {\n\tif (!pattern.includes('*')) {\n\t\treturn segment === pattern;\n\t}\n\treturn new RegExp(\n\t\t`^${pattern\n\t\t\t.split('*')\n\t\t\t.map(escapeRegExp)\n\t\t\t.join('.*')}$`\n\t).test(segment);\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nexport function createTreeFetchRequest(commitHash: string): Buffer {\n\treturn Buffer.concat([\n\t\tpktLine(\n\t\t\t`want ${commitHash} multi_ack_detailed no-done side-band-64k thin-pack ofs-delta agent=git/2.37.3 filter \\n`\n\t\t),\n\t\tpktLine('filter blob:none\\n'),\n\t\tpktLine(`shallow ${commitHash}\\n`),\n\t\tpktLine('deepen 1\\n'),\n\t\tflushPkt(),\n\t\tpktLine('done\\n'),\n\t]);\n}\n\nfunction createObjectFetchRequest(objectHashes: string[]): Buffer {\n\treturn Buffer.concat([\n\t\t...objectHashes.map((objectHash) =>\n\t\t\tpktLine(\n\t\t\t\t`want ${objectHash} multi_ack_detailed no-done side-band-64k thin-pack ofs-delta agent=git/2.37.3 \\n`\n\t\t\t)\n\t\t),\n\t\tflushPkt(),\n\t\tpktLine('done\\n'),\n\t]);\n}\n\nexport function parseUploadPackResponse(response: Buffer): Buffer {\n\tconst packChunks: Buffer[] = [];\n\tlet offset = 0;\n\n\twhile (offset + 4 <= response.length) {\n\t\tconst lineLength = Number.parseInt(\n\t\t\tresponse.subarray(offset, offset + 4).toString('ascii'),\n\t\t\t16\n\t\t);\n\t\toffset += 4;\n\t\tif (!Number.isFinite(lineLength)) {\n\t\t\tthrow new Error('Invalid Git pkt-line response.');\n\t\t}\n\t\tif (lineLength === 0) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (lineLength === 1) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (lineLength === 2) {\n\t\t\tbreak;\n\t\t}\n\t\tif (lineLength < 4) {\n\t\t\tthrow new Error('Invalid Git pkt-line response.');\n\t\t}\n\t\tconst payloadLength = lineLength - 4;\n\t\tconst payload = response.subarray(offset, offset + payloadLength);\n\t\toffset += payloadLength;\n\n\t\tif (payload.length === 0 || payload.toString('utf8') === 'NAK\\n') {\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst sideband = payload[0];\n\t\tif (sideband === 1) {\n\t\t\tpackChunks.push(payload.subarray(1));\n\t\t} else if (sideband === 2) {\n\t\t\tcontinue;\n\t\t} else if (sideband === 3) {\n\t\t\tthrow new Error(payload.subarray(1).toString('utf8'));\n\t\t} else if (payload.subarray(0, 4).toString('ascii') === 'PACK') {\n\t\t\tpackChunks.push(payload);\n\t\t}\n\t}\n\n\treturn Buffer.concat(packChunks);\n}\n\nfunction pktLine(value: string | Buffer): Buffer {\n\tconst payload = Buffer.isBuffer(value) ? value : Buffer.from(value);\n\tconst header = Buffer.from((payload.length + 4).toString(16).padStart(4, '0'));\n\treturn Buffer.concat([header, payload]);\n}\n\nfunction flushPkt(): Buffer {\n\treturn Buffer.from('0000');\n}\n\nexport function stableHash(value: string): string {\n\treturn createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\nexport async function readJsonFile<T>(filename: string): Promise<T> {\n\treturn JSON.parse(await readFile(filename, 'utf8')) as T;\n}\n"],"names":["sparseCheckoutFiles","repoUrl","ref","paths","outDir","workDir","rm","mkdir","init","fs","commitHash","resolveRemoteCommit","fetchAndIndexPack","createTreeFetchRequest","commit","readParsedObject","rootTree","entries","filepath","matchedPath","entry","resolveTreeEntries","createObjectFetchRequest","blob","readObject","outputPath","path","writeFile","fullRef","refToFullRef","exactRef","listServerRefs","http","dir","packfileName","body","response","packfile","parseUploadPackResponse","packPath","indexPack","oid","expectedType","result","resolveTreeEntriesFromSegments","tree","segments","resolvedSegments","segment","remainingSegments","matchedEntries","pathSegmentMatchesPattern","matches","nextResolvedSegments","pattern","escapeRegExp","value","pktLine","flushPkt","objectHashes","objectHash","packChunks","offset","lineLength","payloadLength","payload","sideband","header","stableHash","createHash","readJsonFile","filename","readFile"],"mappings":"wSAqBA,eAAsBA,EAAoB,CACzC,QAAAC,EACA,IAAAC,EACA,MAAAC,EACA,OAAAC,EACA,QAAAC,CACD,EAMsB,CACrB,GAAIF,EAAM,SAAW,EACpB,MAAO,CAAA,EAGR,MAAMG,EAAGD,EAAS,CAAE,UAAW,GAAM,MAAO,GAAM,EAClD,MAAME,EAAMF,EAAS,CAAE,UAAW,GAAM,EACxC,MAAMG,EAAK,CAAE,GAAAC,EAAI,IAAKJ,EAAS,cAAe,QAAS,EAEvD,MAAMK,EAAa,MAAMC,EAAoBV,EAASC,CAAG,EACzD,MAAMU,EAAkB,CACvB,QAAAX,EACA,IAAKI,EACL,aAAc,aACd,KAAMQ,EAAuBH,CAAU,CAAA,CACvC,EAED,MAAMI,EAAS,MAAMC,EACpBV,EACAK,EACA,QAAA,EAEKM,EAAW,MAAMD,EACtBV,EACAS,EAAO,KACP,MAAA,EAEKG,MAAc,IACpB,UAAWC,KAAYf,EACtB,SAAW,CAACgB,EAAaC,CAAK,IAAK,MAAMC,EACxChB,EACAW,EACAE,CAAA,EAEAD,EAAQ,IAAIE,EAAaC,CAAK,EAIhC,aAAMR,EAAkB,CACvB,QAAAX,EACA,IAAKI,EACL,aAAc,aACd,KAAMiB,EACL,MAAM,KAAKL,EAAQ,OAAA,EAAWG,GAAUA,EAAM,GAAG,CAAA,CAClD,CACA,EAED,MAAM,QAAQ,IACb,MAAM,KAAKH,EAAS,MAAO,CAACC,EAAUE,CAAK,IAAM,CAChD,MAAMG,EAAO,MAAMC,EAAW,CAC7B,GAAAf,EACA,IAAKJ,EACL,IAAKe,EAAM,IACX,OAAQ,SAAA,CACR,EACD,GAAIG,EAAK,OAAS,OACjB,MAAM,IAAI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/usr/bin/env node
2
2
  export declare function main(args?: string[]): Promise<void>;
3
+ export declare function parseCliArgs(args: string[]): Promise<{
4
+ [x: string]: unknown;
5
+ source: string | undefined;
6
+ "prepare-image": boolean | undefined;
7
+ prepareImage: boolean | undefined;
8
+ name: string | undefined;
9
+ "php-versions": string;
10
+ phpVersions: string;
11
+ out: string;
12
+ "extra-cflags": string | undefined;
13
+ extraCflags: string | undefined;
14
+ "extra-ldflags": string | undefined;
15
+ extraLdflags: string | undefined;
16
+ "config-args": string;
17
+ configArgs: string;
18
+ optimize: string;
19
+ jobs: number | undefined;
20
+ "extra-files": string[];
21
+ extraFiles: string[];
22
+ _: (string | number)[];
23
+ $0: string;
24
+ } | {
25
+ [x: string]: unknown;
26
+ source: string | undefined;
27
+ "prepare-image": boolean | undefined;
28
+ prepareImage: boolean | undefined;
29
+ name: string | undefined;
30
+ "php-versions": string;
31
+ phpVersions: string;
32
+ out: string;
33
+ "extra-cflags": string | undefined;
34
+ extraCflags: string | undefined;
35
+ "extra-ldflags": string | undefined;
36
+ extraLdflags: string | undefined;
37
+ "config-args": string;
38
+ configArgs: string;
39
+ optimize: string;
40
+ jobs: number | undefined;
41
+ "extra-files": string[];
42
+ extraFiles: string[];
43
+ _: (string | number)[];
44
+ $0: string;
45
+ }>;
3
46
  export declare function normalizeDashPrefixedOptionValues(args: string[]): string[];
47
+ export declare function validateCliMode(argv: {
48
+ source?: unknown;
49
+ 'prepare-image'?: unknown;
50
+ prepareImage?: unknown;
51
+ help?: unknown;
52
+ }): true;
4
53
  export declare function splitShellWords(value: string): string[];
package/cli.js CHANGED
@@ -1,4 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{realpathSync as w,existsSync as v}from"node:fs";import i from"node:path";import{fileURLToPath as x}from"node:url";import A from"yargs";import{hideBin as D}from"yargs/helpers";import{mkdir as g,writeFile as N,readFile as E,cp as F,readdir as P,stat as b}from"node:fs/promises";import y from"node:os";import{spawn as O}from"node:child_process";function _(e){const t=i.join(e,"packages/php-wasm");return{workspaceRoot:e,phpWasmRoot:t,compileRoot:i.join(t,"compile")}}async function I(){try{await p("docker",["--version"],{stdio:"ignore"})}catch(e){throw new Error("Docker is required to compile PHP.wasm extensions, but the docker command was not found.",{cause:e})}}async function k(e){await p("make",["base-image"],{cwd:e.compileRoot})}async function j(e){const t=$(e);return await p("docker",["build","-f","compile-extension/docker/Dockerfile.ext",".",`--tag=${t}`,"--progress=plain","--build-arg",`PHP_VERSION=${e.phpRelease}`,"--build-arg","JSPI=yes"],{cwd:e.phpWasmRoot}),t}async function C(e){const t=$(e),r=["run","--rm","-v",`${e.sourceDir}:/src:ro`,"-v",`${e.outDir}:/out`,"-v",`${e.compileRoot}:/php-wasm-compile:ro`,"--env",`EXTENSION_NAME=${e.name}`,"--env",`PHP_VERSION_SHORT=${e.phpVersion}`,"--env",`ASYNC_MODE=${e.asyncMode}`,"--env",`ARTIFACT_FILENAME=${e.artifactFile}`,"--env",`OPTIMIZE=${e.optimize}`,"--env",`CONFIG_ARGS_COUNT=${e.configArgs.length}`];e.extraCflags&&r.push("--env",`EXTRA_CFLAGS=${e.extraCflags}`),e.extraLdflags&&r.push("--env",`EXTRA_LDFLAGS=${e.extraLdflags}`),e.configArgs.forEach((n,a)=>{r.push("--env",`CONFIG_ARG_${a}=${n}`)}),r.push(t),await p("docker",r,{cwd:e.workspaceRoot})}function $(e){return`playground-php-wasm:compile-extension-php${e.phpVersion.replaceAll(".","-")}-${e.asyncMode}`}async function p(e,t,r={}){console.log(`Running ${e} ${t.join(" ")}`),await new Promise((n,a)=>{const s=O(e,t,{cwd:r.cwd,stdio:r.stdio??"inherit",env:process.env});s.on("error",a),s.on("close",c=>{if(c===0){n();return}a(new Error(`${e} exited with code ${c}`))})})}const T="jspi";async function L(e){const t={name:e.name,version:e.version,artifacts:e.artifacts.map(r=>({phpVersion:r.phpVersion,sourcePath:r.sourcePath}))};return e.extraFiles&&(t.extraFiles=e.extraFiles),t}async function M(e){await g(e.outDir,{recursive:!0});const t=i.join(e.outDir,"manifest.json");return await N(t,`${JSON.stringify(e.manifest,null,2)}
3
- `),t}const z=["8.5","8.4","8.3","8.2","8.1","8.0","7.4"],H={"8.5":"8.5.5","8.4":"8.4.20","8.3":"8.3.30","8.2":"8.2.30","8.1":"8.1.34","8.0":"8.0.30","7.4":"7.4.33"};async function V(e){const t=i.resolve(e.workspaceRoot,e.outDir),r=i.resolve(e.workspaceRoot,e.sourceDir),n=_(e.workspaceRoot),a=await G(r),s=e.phpVersions.map(l=>({phpVersion:l,asyncMode:T}));await g(t,{recursive:!0}),await I(),await k(n);const c=await J(s,B(e.jobs,s.length),async({phpVersion:l,asyncMode:o})=>{const h=W(l),m=`${e.name}-php${l}-${o}.so`;return await j({...n,phpVersion:l,phpRelease:h,asyncMode:o}),await C({...n,sourceDir:r,outDir:t,name:e.name,phpVersion:l,asyncMode:o,artifactFile:m,optimize:e.optimize,extraCflags:e.extraCflags,extraLdflags:e.extraLdflags,configArgs:e.configArgs}),{phpVersion:l,sourcePath:m,path:i.join(t,m)}}),f=await L({name:e.name,version:a,artifacts:c,extraFiles:e.extraFiles});return{manifestPath:await M({outDir:t,manifest:f}),artifacts:c,manifest:f}}function W(e){return H[e]??e}async function G(e){try{const t=JSON.parse(await E(i.join(e,"package.json"),"utf8"));if(typeof t.version=="string")return t.version}catch{}return"0.0.0"}async function J(e,t,r){const n=new Array(e.length);let a=0;const s=Array.from({length:Math.min(t,e.length)},async()=>{for(;a<e.length;){const c=a++;n[c]=await r(e[c])}});return await Promise.all(s),n}function B(e,t){return t===0?1:e&&e>0?Math.min(e,t):Math.min(y.availableParallelism?.()??y.cpus().length,t)}const X=[/\bPHP_ARG_ENABLE\(\s*\[?([A-Za-z0-9_]+)\]?/m,/\bPHP_ARG_WITH\(\s*\[?([A-Za-z0-9_]+)\]?/m,/\bPHP_NEW_EXTENSION\(\s*\[?([A-Za-z0-9_]+)\]?/m];async function U(e){const t=i.join(e,"config.m4");let r;try{r=await E(t,"utf8")}catch(a){throw new Error(`Could not read ${t}. Pass --name or provide a config.m4 file.`,{cause:a})}const n=Z(r);if(!n)throw new Error(`Could not detect the extension name from ${t}. Pass --name explicitly.`);return n}function Z(e){for(const t of X){const r=t.exec(e);if(r?.[1])return r[1]}return null}function q(e){const t=e.lastIndexOf(":");if(t<0)throw new Error(`Invalid --extra-files value ${JSON.stringify(e)}. Expected "<hostDir>:<vfsRoot>".`);const r=e.slice(0,t),n=e.slice(t+1);if(!r||!n)throw new Error(`Invalid --extra-files value ${JSON.stringify(e)}. Expected "<hostDir>:<vfsRoot>".`);if(!n.startsWith("/"))throw new Error(`--extra-files vfsRoot must be an absolute VFS path. Received ${JSON.stringify(n)}.`);return{hostDir:r,vfsRoot:n}}async function Y(e,t,r){if(!e.length)return;const n=e[0].vfsRoot;for(const f of e)if(f.vfsRoot!==n)throw new Error("All --extra-files entries must share the same vfsRoot. Received "+JSON.stringify(e.map(u=>u.vfsRoot)));const a=[],s=new Set,c=new Set;for(const f of e){const u=i.resolve(r,f.hostDir),l=i.basename(u),o=i.join(t,l);if(c.has(o))throw new Error(`--extra-files destination collides on disk: ${o}. Two host directories share the same basename, so one would overwrite the other.`);c.add(o),await g(i.dirname(o),{recursive:!0}),await F(u,o,{recursive:!0}),await R(o,async(h,m)=>{const d=i.relative(o,h).split(i.sep).join("/");if(!d)return;const S=`${l}/${d}`;if(m){if(!((await P(h)).length===0))return;if(s.has(d))throw new Error(`--extra-files vfsPath collides across specs: ${d}.`);s.add(d),a.push({vfsPath:d,type:"directory"});return}if(s.has(d))throw new Error(`--extra-files vfsPath collides across specs: ${d}.`);s.add(d),a.push({vfsPath:d,sourcePath:S})})}return a.sort((f,u)=>f.vfsPath<u.vfsPath?-1:f.vfsPath>u.vfsPath?1:0),{vfsRoot:n,nodes:a}}async function R(e,t){for(const r of await P(e)){const n=i.join(e,r),a=await b(n);await t(n,a.isDirectory()),a.isDirectory()&&await R(n,t)}}const K=new Set(["--config-args","--extra-cflags","--extra-ldflags"]);async function Q(e=D(process.argv)){const t=await A(ee(e)).scriptName("@php-wasm/compile-extension").usage("Usage: $0 --source <dir> [options]").options({source:{type:"string",demandOption:!0,description:"Extension source directory containing config.m4"},name:{type:"string",description:"Extension name. Defaults to parsing config.m4."},"php-versions":{type:"string",default:z.join(","),description:"Comma-separated PHP major.minor versions."},out:{type:"string",default:"./dist",description:"Output directory."},"extra-cflags":{type:"string",description:"Extra CFLAGS appended to the side-module build."},"extra-ldflags":{type:"string",description:"Extra LDFLAGS appended to the side-module build."},"config-args":{type:"string",default:"",description:"Extra ./configure arguments, parsed as shell words."},optimize:{type:"string",default:"2",description:"Optimization level passed as -O<level>."},jobs:{type:"number",description:"Maximum concurrent docker builds."},"extra-files":{type:"string",array:!0,default:[],description:"Stage a host directory under an absolute VFS root. Format: <hostDir>:<vfsRoot>. Files are copied next to the manifest and recorded in extraFiles."}}).strict().help().parse(),r=ne(process.cwd()),n=i.resolve(r,t.source),a=t.name??await U(n),s=te(t["php-versions"],"php-versions"),c=re(t["config-args"]||""),f=t["extra-files"].map(q),u=i.resolve(r,t.out),l=await Y(f,u,r),o=await V({workspaceRoot:r,sourceDir:n,outDir:t.out,name:a,phpVersions:s,extraCflags:t["extra-cflags"],extraLdflags:t["extra-ldflags"],configArgs:c,optimize:t.optimize,jobs:t.jobs,extraFiles:l});console.log(`Wrote ${o.artifacts.length} artifacts.`),console.log(`Wrote ${o.manifestPath}.`)}ae(import.meta.url)&&Q().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1)});function ee(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];if(K.has(n)&&r+1<e.length&&!e[r+1].startsWith(`${n}=`)){t.push(`${n}=${e[r+1]}`),r++;continue}t.push(n)}return t}function te(e,t){const r=e.split(",").map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error(`--${t} must contain at least one value.`);return r}function re(e){const t=[];let r="",n=null,a=!1;for(const s of e){if(a){r+=s,a=!1;continue}if(s==="\\"){a=!0;continue}if(n){s===n?n=null:r+=s;continue}if(s==='"'||s==="'"){n=s;continue}if(/\s/.test(s)){r.length>0&&(t.push(r),r="");continue}r+=s}if(a&&(r+="\\"),n)throw new Error("Unterminated quote in --config-args.");return r.length>0&&t.push(r),t}function ne(e){let t=i.resolve(e);for(;t!==i.dirname(t);){if(v(i.join(t,"packages/php-wasm/compile"))&&v(i.join(t,"nx.json")))return t;t=i.dirname(t)}return process.cwd()}function ae(e){const t=process.argv[1];if(!t)return!1;try{return w(t)===w(x(e))}catch{return i.resolve(t)===x(e)}}
2
+ import{existsSync as h,readdirSync as z,readFileSync as V,realpathSync as k}from"node:fs";import s from"node:path";import{fileURLToPath as y}from"node:url";import G from"yargs";import{hideBin as B}from"yargs/helpers";import{rm as w,mkdir as g,rename as R,writeFile as j,readFile as A,cp as U,readdir as S,stat as X}from"node:fs/promises";import v from"node:os";import{spawn as q}from"node:child_process";import{createHash as Z}from"node:crypto";const Y="modulepreload",K=function(e){return"/"+e},$={},Q=function(t,r,n){let o=Promise.resolve();if(r&&r.length>0){document.getElementsByTagName("link");const a=document.querySelector("meta[property=csp-nonce]"),c=a?.nonce||a?.getAttribute("nonce");o=Promise.allSettled(r.map(u=>{if(u=K(u),u in $)return;$[u]=!0;const l=u.endsWith(".css"),p=l?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${p}`))return;const f=document.createElement("link");if(f.rel=l?"stylesheet":Y,l||(f.as="script"),f.crossOrigin="",f.href=u,c&&f.setAttribute("nonce",c),document.head.appendChild(f),l)return new Promise((d,m)=>{f.addEventListener("load",d),f.addEventListener("error",()=>m(new Error(`Unable to preload CSS for ${u}`)))})}))}function i(a){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=a,window.dispatchEvent(c),!c.defaultPrevented)throw a}return o.then(a=>{for(const c of a||[])c.status==="rejected"&&i(c.reason);return t().catch(i)})},D="https://github.com/WordPress/wordpress-playground.git",b=["compile/base-image/Dockerfile","compile/base-image/emcc-for-php-wasm.sh","compile/base-image/replace.sh","compile/base-image/replace-across-lines.sh","compile/php/php*.patch","compile-extension/docker/Dockerfile.ext","compile-extension/scripts/build-in-docker.sh"],ee=b.map(e=>`packages/php-wasm/${e}`);async function te({workspaceRoot:e,packageRoot:t,cacheRoot:r=ie(),fetchDockerAssets:n}){const o=oe({workspaceRoot:e,packageRoot:t}),i=s.join(r,_(o),"php-wasm");if(x(i))return i;console.log(`Fetching PHP.wasm Docker assets from WordPress/wordpress-playground ${o}.`);const a=await(n??re)({ref:o,cacheRoot:r});if(!x(a))throw new Error(`Fetched PHP.wasm Docker assets from ${o}, but the cache is incomplete.`);return a}async function re({ref:e,cacheRoot:t}){const r=s.join(t,_(e)),n=s.join(r,"php-wasm"),o=`${r}-${process.pid}-${Date.now()}.tmp`,i=s.join(o,"php-wasm");await w(o,{recursive:!0,force:!0}),await g(i,{recursive:!0});try{const{sparseCheckoutFiles:a}=await Q(async()=>{const{sparseCheckoutFiles:u}=await import("./assets/git-sparse-checkout-ClUpBgMv.js");return{sparseCheckoutFiles:u}},[]),c=await a({repoUrl:D,ref:e,paths:ee,outDir:o,workDir:s.join(o,".git-work")});for(const u of c){const l=ce(u),p=s.join(o,"packages/php-wasm",l),f=s.join(i,l);await g(s.dirname(f),{recursive:!0}),await R(p,f)}await j(s.join(i,"source.json"),`${JSON.stringify({repository:D,ref:e},null,2)}
3
+ `),await w(s.join(o,".git-work"),{recursive:!0,force:!0}),await w(s.join(o,"packages"),{recursive:!0,force:!0}),await ne({tempDir:o,cacheDir:r,phpWasmRoot:n})}catch(a){throw await w(o,{recursive:!0,force:!0}),a}return n}function x(e){return b.every(t=>t.includes("*")?ue(e,t).length>0:h(s.join(e,t)))}async function ne({tempDir:e,cacheDir:t,phpWasmRoot:r}){await g(s.dirname(t),{recursive:!0});try{await R(e,t)}catch(n){if(pe(n)&&x(r)){await w(e,{recursive:!0,force:!0});return}throw n}}function oe({workspaceRoot:e,packageRoot:t}){if(se(e))return"trunk";const n=ae(t).version;if(!n)throw new Error(`Could not resolve @php-wasm/compile-extension version from ${t}.`);return`v${n}`}function se(e){return h(s.join(e,"nx.json"))&&h(s.join(e,"packages/php-wasm/compile-extension/package.json"))}function ie(){const e=process.env.PHP_WASM_COMPILE_EXTENSION_CACHE_DIR;if(e)return e;const t=process.env.XDG_CACHE_HOME;if(t)return s.join(t,"php-wasm/compile-extension/docker-assets");const r=v.homedir();return r?s.join(r,".cache/php-wasm/compile-extension/docker-assets"):s.join(v.tmpdir(),"php-wasm/compile-extension/docker-assets")}function ae(e){const t=s.join(e,"package.json");return h(t)?JSON.parse(V(t,"utf8")):{}}function _(e){return Z("sha256").update(e).digest("hex").slice(0,16)}function ce(e){const t="packages/php-wasm/";if(!e.startsWith(t))throw new Error(`Unexpected fetched Docker asset path: ${e}`);return e.slice(t.length)}function ue(e,t){const r=s.join(e,s.dirname(t)),n=s.basename(t);return h(r)?z(r,{withFileTypes:!0}).filter(o=>o.isFile()&&le(o.name,n)).map(o=>s.join(s.dirname(t),o.name).split(s.sep).join("/")).sort():[]}function le(e,t){return t.includes("*")?new RegExp(`^${t.split("*").map(fe).join(".*")}$`).test(e):e===t}function fe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function pe(e){return typeof e=="object"&&e!==null&&"code"in e&&["EEXIST","ENOTEMPTY","EPERM"].includes(String(e.code))}async function C(e,t={}){const r=s.join(e,"packages/php-wasm");if(x(r))return P(e,r);const n=t.packageRoot??me(),o=s.join(n,"php-wasm");if(x(o))return P(e,o);const i=await te({workspaceRoot:e,packageRoot:n,cacheRoot:t.cacheRoot,fetchDockerAssets:t.fetchDockerAssets});return P(e,i)}function P(e,t){return{workspaceRoot:e,phpWasmRoot:t,compileRoot:s.join(t,"compile"),compileExtensionRoot:s.join(t,"compile-extension")}}function me(){let e=s.dirname(y(import.meta.url));for(;e!==s.dirname(e);){if(h(s.join(e,"package.json")))return e;e=s.dirname(e)}return s.dirname(y(import.meta.url))}async function F(){try{await E("docker",["--version"],{stdio:"ignore"})}catch(e){throw new Error("Docker is required to compile PHP.wasm extensions, but the docker command was not found.",{cause:e})}}async function N(e){await E("docker",["build","-f","./Dockerfile",".","--tag=playground-php-wasm:base","--progress=plain"],{cwd:s.join(e.compileRoot,"base-image")})}async function O(e){const t=I(e);return await E("docker",["build","-f","compile-extension/docker/Dockerfile.ext",".",`--tag=${t}`,"--progress=plain","--build-arg",`PHP_VERSION=${e.phpRelease}`,"--build-arg","JSPI=yes"],{cwd:e.phpWasmRoot}),t}async function de(e){const t=I(e),r=["run","--rm","-v",`${e.sourceDir}:/src:ro`,"-v",`${e.outDir}:/out`,"-v",`${e.compileRoot}:/php-wasm-compile:ro`,"--env",`EXTENSION_NAME=${e.name}`,"--env",`PHP_VERSION_SHORT=${e.phpVersion}`,"--env",`ASYNC_MODE=${e.asyncMode}`,"--env",`ARTIFACT_FILENAME=${e.artifactFile}`,"--env",`OPTIMIZE=${e.optimize}`,"--env",`CONFIG_ARGS_COUNT=${e.configArgs.length}`];e.extraCflags&&r.push("--env",`EXTRA_CFLAGS=${e.extraCflags}`),e.extraLdflags&&r.push("--env",`EXTRA_LDFLAGS=${e.extraLdflags}`),e.configArgs.forEach((n,o)=>{r.push("--env",`CONFIG_ARG_${o}=${n}`)}),r.push(t),await E("docker",r,{cwd:e.workspaceRoot})}function I(e){return`playground-php-wasm:compile-extension-php${e.phpVersion.replaceAll(".","-")}-${e.asyncMode}`}async function E(e,t,r={}){console.log(`Running ${e} ${t.join(" ")}`),await new Promise((n,o)=>{const i=q(e,t,{cwd:r.cwd,stdio:r.stdio??"inherit",env:process.env});i.on("error",o),i.on("close",a=>{if(a===0){n();return}o(new Error(`${e} exited with code ${a}`))})})}const T="jspi";async function he(e){const t={name:e.name,version:e.version,artifacts:e.artifacts.map(r=>({phpVersion:r.phpVersion,sourcePath:r.sourcePath}))};return e.extraFiles&&(t.extraFiles=e.extraFiles),t}async function ge(e){await g(e.outDir,{recursive:!0});const t=s.join(e.outDir,"manifest.json");return await j(t,`${JSON.stringify(e.manifest,null,2)}
4
+ `),t}const we=["8.5","8.4","8.3","8.2","8.1","8.0","7.4"],xe={"8.5":"8.5.5","8.4":"8.4.20","8.3":"8.3.30","8.2":"8.2.30","8.1":"8.1.34","8.0":"8.0.30","7.4":"7.4.33"};async function ye(e){await F();const t=await C(e.workspaceRoot),r=e.phpVersions.map(o=>({phpVersion:o,asyncMode:T}));return await N(t),{images:await H(r,L(e.jobs,r.length),async({phpVersion:o,asyncMode:i})=>{const a=await O({...t,phpVersion:o,phpRelease:M(o),asyncMode:i});return{phpVersion:o,asyncMode:i,imageTag:a}})}}async function ve(e){const t=s.resolve(e.workspaceRoot,e.outDir),r=s.resolve(e.workspaceRoot,e.sourceDir);await F();const n=await C(e.workspaceRoot),o=await Ee(r),i=e.phpVersions.map(l=>({phpVersion:l,asyncMode:T}));await g(t,{recursive:!0}),await N(n);const a=await H(i,L(e.jobs,i.length),async({phpVersion:l,asyncMode:p})=>{const f=M(l),d=`${e.name}-php${l}-${p}.so`;return await O({...n,phpVersion:l,phpRelease:f,asyncMode:p}),await de({...n,sourceDir:r,outDir:t,name:e.name,phpVersion:l,asyncMode:p,artifactFile:d,optimize:e.optimize,extraCflags:e.extraCflags,extraLdflags:e.extraLdflags,configArgs:e.configArgs}),{phpVersion:l,sourcePath:d,path:s.join(t,d)}}),c=await he({name:e.name,version:o,artifacts:a,extraFiles:e.extraFiles});return{manifestPath:await ge({outDir:t,manifest:c}),artifacts:a,manifest:c}}function M(e){return xe[e]??e}async function Ee(e){try{const t=JSON.parse(await A(s.join(e,"package.json"),"utf8"));if(typeof t.version=="string")return t.version}catch{}return"0.0.0"}async function H(e,t,r){const n=new Array(e.length);let o=0;const i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){const a=o++;n[a]=await r(e[a])}});return await Promise.all(i),n}function L(e,t){return t===0?1:e&&e>0?Math.min(e,t):Math.min(v.availableParallelism?.()??v.cpus().length,t)}const Pe=[/\bPHP_ARG_ENABLE\(\s*\[?([A-Za-z0-9_]+)\]?/m,/\bPHP_ARG_WITH\(\s*\[?([A-Za-z0-9_]+)\]?/m,/\bPHP_NEW_EXTENSION\(\s*\[?([A-Za-z0-9_]+)\]?/m];async function ke(e){const t=s.join(e,"config.m4");let r;try{r=await A(t,"utf8")}catch(o){throw new Error(`Could not read ${t}. Pass --name or provide a config.m4 file.`,{cause:o})}const n=$e(r);if(!n)throw new Error(`Could not detect the extension name from ${t}. Pass --name explicitly.`);return n}function $e(e){for(const t of Pe){const r=t.exec(e);if(r?.[1])return r[1]}return null}function De(e){const t=e.lastIndexOf(":");if(t<0)throw new Error(`Invalid --extra-files value ${JSON.stringify(e)}. Expected "<hostDir>:<vfsRoot>".`);const r=e.slice(0,t),n=e.slice(t+1);if(!r||!n)throw new Error(`Invalid --extra-files value ${JSON.stringify(e)}. Expected "<hostDir>:<vfsRoot>".`);if(!n.startsWith("/"))throw new Error(`--extra-files vfsRoot must be an absolute VFS path. Received ${JSON.stringify(n)}.`);return{hostDir:r,vfsRoot:n}}async function Re(e,t,r){if(!e.length)return;const n=e[0].vfsRoot;for(const c of e)if(c.vfsRoot!==n)throw new Error("All --extra-files entries must share the same vfsRoot. Received "+JSON.stringify(e.map(u=>u.vfsRoot)));const o=[],i=new Set,a=new Set;for(const c of e){const u=s.resolve(r,c.hostDir),l=s.basename(u),p=s.join(t,l);if(a.has(p))throw new Error(`--extra-files destination collides on disk: ${p}. Two host directories share the same basename, so one would overwrite the other.`);a.add(p),await g(s.dirname(p),{recursive:!0}),await U(u,p,{recursive:!0}),await W(p,async(f,d)=>{const m=s.relative(p,f).split(s.sep).join("/");if(!m)return;const J=`${l}/${m}`;if(d){if(!((await S(f)).length===0))return;if(i.has(m))throw new Error(`--extra-files vfsPath collides across specs: ${m}.`);i.add(m),o.push({vfsPath:m,type:"directory"});return}if(i.has(m))throw new Error(`--extra-files vfsPath collides across specs: ${m}.`);i.add(m),o.push({vfsPath:m,sourcePath:J})})}return o.sort((c,u)=>c.vfsPath<u.vfsPath?-1:c.vfsPath>u.vfsPath?1:0),{vfsRoot:n,nodes:o}}async function W(e,t){for(const r of await S(e)){const n=s.join(e,r),o=await X(n);await t(n,o.isDirectory()),o.isDirectory()&&await W(n,t)}}const je=new Set(["--config-args","--extra-cflags","--extra-ldflags"]);async function Ae(e=B(process.argv)){const t=await Se(e),r=Ne(process.cwd()),n=Ce(t["php-versions"],"php-versions");if(t["prepare-image"]){const d=await ye({workspaceRoot:r,phpVersions:n,jobs:t.jobs});console.log(`Prepared ${d.images.length} PHP.wasm extension build images.`);for(const m of d.images)console.log(m.imageTag);return}const o=t.source,i=s.resolve(r,o),a=t.name??await ke(i),c=Fe(t["config-args"]||""),u=t["extra-files"].map(De),l=s.resolve(r,t.out),p=await Re(u,l,r),f=await ve({workspaceRoot:r,sourceDir:i,outDir:t.out,name:a,phpVersions:n,extraCflags:t["extra-cflags"],extraLdflags:t["extra-ldflags"],configArgs:c,optimize:t.optimize,jobs:t.jobs,extraFiles:p});console.log(`Wrote ${f.artifacts.length} artifacts.`),console.log(`Wrote ${f.manifestPath}.`)}async function Se(e){return await G(be(e)).scriptName("@php-wasm/compile-extension").usage("Usage: $0 [--source <dir> | --prepare-image] [options]").options({source:{type:"string",description:"Extension source directory containing config.m4"},"prepare-image":{type:"boolean",description:"Build the Docker images for the requested PHP versions and exit without compiling an extension source directory."},name:{type:"string",description:"Extension name. Defaults to parsing config.m4."},"php-versions":{type:"string",default:we.join(","),description:"Comma-separated PHP major.minor versions."},out:{type:"string",default:"./dist",description:"Output directory."},"extra-cflags":{type:"string",description:"Extra CFLAGS appended to the side-module build."},"extra-ldflags":{type:"string",description:"Extra LDFLAGS appended to the side-module build."},"config-args":{type:"string",default:"",description:"Extra ./configure arguments, parsed as shell words."},optimize:{type:"string",default:"2",description:"Optimization level passed as -O<level>."},jobs:{type:"number",description:"Maximum concurrent docker builds."},"extra-files":{type:"string",array:!0,default:[],description:"Stage a host directory under an absolute VFS root. Format: <hostDir>:<vfsRoot>. Files are copied next to the manifest and recorded in extraFiles."}}).conflicts("source","prepare-image").check(_e).exitProcess(!1).strict().help().parse()}Oe(import.meta.url)&&Ae().catch(e=>{console.error(e instanceof Error?e.message:e),process.exit(1)});function be(e){const t=[];for(let r=0;r<e.length;r++){const n=e[r];if(je.has(n)&&r+1<e.length&&!e[r+1].startsWith(`${n}=`)){t.push(`${n}=${e[r+1]}`),r++;continue}t.push(n)}return t}function _e(e){if(e.help)return!0;const t=typeof e.source=="string"&&e.source.length>0,r=!!(e["prepare-image"]??e.prepareImage);if(t&&r)throw new Error("--source and --prepare-image cannot be used together.");if(!t&&!r)throw new Error("--source is required unless --prepare-image is set.");return!0}function Ce(e,t){const r=e.split(",").map(n=>n.trim()).filter(Boolean);if(r.length===0)throw new Error(`--${t} must contain at least one value.`);return r}function Fe(e){const t=[];let r="",n=null,o=!1;for(const i of e){if(o){r+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(n){i===n?n=null:r+=i;continue}if(i==='"'||i==="'"){n=i;continue}if(/\s/.test(i)){r.length>0&&(t.push(r),r="");continue}r+=i}if(o&&(r+="\\"),n)throw new Error("Unterminated quote in --config-args.");return r.length>0&&t.push(r),t}function Ne(e){let t=s.resolve(e);for(;t!==s.dirname(t);){if(h(s.join(t,"packages/php-wasm/compile-extension/package.json"))&&h(s.join(t,"nx.json")))return t;t=s.dirname(t)}return process.cwd()}function Oe(e){const t=process.argv[1];if(!t)return!1;try{return k(t)===k(y(e))}catch{return s.resolve(t)===y(e)}}
4
5
  //# sourceMappingURL=cli.js.map
package/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","sources":["../../../../packages/php-wasm/compile-extension/src/docker.ts","../../../../packages/php-wasm/compile-extension/src/manifest.ts","../../../../packages/php-wasm/compile-extension/src/compile.ts","../../../../packages/php-wasm/compile-extension/src/detect.ts","../../../../packages/php-wasm/compile-extension/src/extra-files.ts","../../../../packages/php-wasm/compile-extension/src/cli.ts"],"sourcesContent":["import { spawn } from 'node:child_process';\nimport path from 'node:path';\n\nimport type { AsyncMode } from './manifest';\n\nexport interface DockerBuildContext {\n\tworkspaceRoot: string;\n\tphpWasmRoot: string;\n\tcompileRoot: string;\n}\n\nexport interface DockerImageOptions extends DockerBuildContext {\n\tphpVersion: string;\n\tphpRelease: string;\n\tasyncMode: AsyncMode;\n}\n\nexport interface DockerRunOptions extends DockerImageOptions {\n\tsourceDir: string;\n\toutDir: string;\n\tname: string;\n\tartifactFile: string;\n\toptimize: string;\n\textraCflags?: string;\n\textraLdflags?: string;\n\tconfigArgs: string[];\n}\n\nexport function createDockerContext(workspaceRoot: string): DockerBuildContext {\n\tconst phpWasmRoot = path.join(workspaceRoot, 'packages/php-wasm');\n\treturn {\n\t\tworkspaceRoot,\n\t\tphpWasmRoot,\n\t\tcompileRoot: path.join(phpWasmRoot, 'compile'),\n\t};\n}\n\nexport async function assertDockerIsAvailable(): Promise<void> {\n\ttry {\n\t\tawait runCommand('docker', ['--version'], {\n\t\t\tstdio: 'ignore',\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t'Docker is required to compile PHP.wasm extensions, but the docker command was not found.',\n\t\t\t{ cause: error }\n\t\t);\n\t}\n}\n\nexport async function buildBaseImage(context: DockerBuildContext) {\n\tawait runCommand('make', ['base-image'], {\n\t\tcwd: context.compileRoot,\n\t});\n}\n\nexport async function buildExtensionImage(\n\toptions: DockerImageOptions\n): Promise<string> {\n\tconst imageTag = getExtensionImageTag(options);\n\tawait runCommand(\n\t\t'docker',\n\t\t[\n\t\t\t'build',\n\t\t\t'-f',\n\t\t\t'compile-extension/docker/Dockerfile.ext',\n\t\t\t'.',\n\t\t\t`--tag=${imageTag}`,\n\t\t\t'--progress=plain',\n\t\t\t'--build-arg',\n\t\t\t`PHP_VERSION=${options.phpRelease}`,\n\t\t\t'--build-arg',\n\t\t\t'JSPI=yes',\n\t\t],\n\t\t{\n\t\t\tcwd: options.phpWasmRoot,\n\t\t}\n\t);\n\treturn imageTag;\n}\n\nexport async function runExtensionBuild(options: DockerRunOptions) {\n\tconst imageTag = getExtensionImageTag(options);\n\tconst runArgs = [\n\t\t'run',\n\t\t'--rm',\n\t\t'-v',\n\t\t`${options.sourceDir}:/src:ro`,\n\t\t'-v',\n\t\t`${options.outDir}:/out`,\n\t\t'-v',\n\t\t`${options.compileRoot}:/php-wasm-compile:ro`,\n\t\t'--env',\n\t\t`EXTENSION_NAME=${options.name}`,\n\t\t'--env',\n\t\t`PHP_VERSION_SHORT=${options.phpVersion}`,\n\t\t'--env',\n\t\t`ASYNC_MODE=${options.asyncMode}`,\n\t\t'--env',\n\t\t`ARTIFACT_FILENAME=${options.artifactFile}`,\n\t\t'--env',\n\t\t`OPTIMIZE=${options.optimize}`,\n\t\t'--env',\n\t\t`CONFIG_ARGS_COUNT=${options.configArgs.length}`,\n\t];\n\n\tif (options.extraCflags) {\n\t\trunArgs.push('--env', `EXTRA_CFLAGS=${options.extraCflags}`);\n\t}\n\tif (options.extraLdflags) {\n\t\trunArgs.push('--env', `EXTRA_LDFLAGS=${options.extraLdflags}`);\n\t}\n\n\toptions.configArgs.forEach((arg, index) => {\n\t\trunArgs.push('--env', `CONFIG_ARG_${index}=${arg}`);\n\t});\n\n\trunArgs.push(imageTag);\n\n\tawait runCommand('docker', runArgs, {\n\t\tcwd: options.workspaceRoot,\n\t});\n}\n\nfunction getExtensionImageTag(\n\toptions: Pick<DockerImageOptions, 'phpVersion' | 'asyncMode'>\n) {\n\tconst phpVersion = options.phpVersion.replaceAll('.', '-');\n\treturn `playground-php-wasm:compile-extension-php${phpVersion}-${options.asyncMode}`;\n}\n\ninterface RunCommandOptions {\n\tcwd?: string;\n\tstdio?: 'inherit' | 'ignore';\n}\n\nasync function runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions: RunCommandOptions = {}\n): Promise<void> {\n\tconsole.log(`Running ${command} ${args.join(' ')}`);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tstdio: options.stdio ?? 'inherit',\n\t\t\tenv: process.env,\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treject(new Error(`${command} exited with code ${code}`));\n\t\t});\n\t});\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport const ExtensionAsyncMode = 'jspi';\nexport type AsyncMode = typeof ExtensionAsyncMode;\n\n/**\n * One sidecar file or empty directory staged alongside an artifact.\n *\n * Mirrors `PHPExtensionManifestExtraFile` in `@php-wasm/universal`.\n */\nexport interface ExtensionManifestExtraFile {\n\t/** Joined with the group's `vfsRoot` to form the final VFS path. */\n\tvfsPath: string;\n\t/** Defaults to \"file\". Only file nodes need a `sourcePath`. */\n\ttype?: 'file' | 'directory';\n\t/** Relative to the manifest URL/base URL, or an absolute URL. */\n\tsourcePath?: string;\n}\n\nexport interface ExtensionManifestExtraFiles {\n\t/** Absolute VFS prefix joined with each node's `vfsPath`. */\n\tvfsRoot?: string;\n\tnodes?: ExtensionManifestExtraFile[];\n}\n\nexport interface ExtensionArtifact {\n\tphpVersion: string;\n\t/** Path to the `.so` file, relative to the manifest URL or absolute. */\n\tsourcePath: string;\n\t/** URL-backed files needed only by this artifact. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport interface ExtensionManifest {\n\tname: string;\n\tversion: string;\n\tartifacts: ExtensionArtifact[];\n\t/** URL-backed files shared by every artifact in this manifest. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport interface BuiltArtifact {\n\tphpVersion: string;\n\t/** Path to the `.so` file, relative to the manifest URL. */\n\tsourcePath: string;\n\t/** Absolute path on disk where the `.so` was written. */\n\tpath: string;\n}\n\nexport async function createManifest(options: {\n\tname: string;\n\tversion: string;\n\tartifacts: BuiltArtifact[];\n\textraFiles?: ExtensionManifestExtraFiles;\n}): Promise<ExtensionManifest> {\n\tconst manifest: ExtensionManifest = {\n\t\tname: options.name,\n\t\tversion: options.version,\n\t\tartifacts: options.artifacts.map((artifact) => ({\n\t\t\tphpVersion: artifact.phpVersion,\n\t\t\tsourcePath: artifact.sourcePath,\n\t\t})),\n\t};\n\tif (options.extraFiles) {\n\t\tmanifest.extraFiles = options.extraFiles;\n\t}\n\treturn manifest;\n}\n\nexport async function writeManifest(options: {\n\toutDir: string;\n\tmanifest: ExtensionManifest;\n}): Promise<string> {\n\tawait mkdir(options.outDir, { recursive: true });\n\tconst manifestPath = path.join(options.outDir, 'manifest.json');\n\tawait writeFile(\n\t\tmanifestPath,\n\t\t`${JSON.stringify(options.manifest, null, 2)}\\n`\n\t);\n\treturn manifestPath;\n}\n\nexport function findExtensionArtifact(\n\tmanifest: ExtensionManifest,\n\tphpVersion: string\n): ExtensionArtifact | undefined {\n\treturn manifest.artifacts.find(\n\t\t(artifact) => artifact.phpVersion === phpVersion\n\t);\n}\n","import { mkdir, readFile } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport {\n\tassertDockerIsAvailable,\n\tbuildBaseImage,\n\tbuildExtensionImage,\n\tcreateDockerContext,\n\trunExtensionBuild,\n} from './docker';\nimport type {\n\tAsyncMode,\n\tBuiltArtifact,\n\tExtensionManifestExtraFiles,\n} from './manifest';\nimport { createManifest, ExtensionAsyncMode, writeManifest } from './manifest';\n\nexport const SupportedExtensionPHPVersions = [\n\t'8.5',\n\t'8.4',\n\t'8.3',\n\t'8.2',\n\t'8.1',\n\t'8.0',\n\t'7.4',\n] as const;\n\nconst PHP_RELEASE_BY_MINOR: Record<string, string> = {\n\t'8.5': '8.5.5',\n\t'8.4': '8.4.20',\n\t'8.3': '8.3.30',\n\t'8.2': '8.2.30',\n\t'8.1': '8.1.34',\n\t'8.0': '8.0.30',\n\t'7.4': '7.4.33',\n};\n\nexport interface CompileExtensionOptions {\n\tworkspaceRoot: string;\n\tsourceDir: string;\n\toutDir: string;\n\tname: string;\n\tphpVersions: string[];\n\textraCflags?: string;\n\textraLdflags?: string;\n\tconfigArgs: string[];\n\toptimize: string;\n\tjobs?: number;\n\t/** Sidecar files to record at the manifest level. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport async function compileExtensionMatrix(options: CompileExtensionOptions) {\n\tconst outDir = path.resolve(options.workspaceRoot, options.outDir);\n\tconst sourceDir = path.resolve(options.workspaceRoot, options.sourceDir);\n\tconst context = createDockerContext(options.workspaceRoot);\n\tconst version = await detectManifestVersion(sourceDir);\n\tconst matrix: Array<{ phpVersion: string; asyncMode: AsyncMode }> =\n\t\toptions.phpVersions.map((phpVersion) => ({\n\t\t\tphpVersion,\n\t\t\tasyncMode: ExtensionAsyncMode,\n\t\t}));\n\n\tawait mkdir(outDir, { recursive: true });\n\tawait assertDockerIsAvailable();\n\tawait buildBaseImage(context);\n\n\tconst artifacts = await mapLimit(\n\t\tmatrix,\n\t\tnormalizeJobCount(options.jobs, matrix.length),\n\t\tasync ({ phpVersion, asyncMode }) => {\n\t\t\tconst phpRelease = resolvePHPRelease(phpVersion);\n\t\t\tconst artifactFile = `${options.name}-php${phpVersion}-${asyncMode}.so`;\n\t\t\tawait buildExtensionImage({\n\t\t\t\t...context,\n\t\t\t\tphpVersion,\n\t\t\t\tphpRelease,\n\t\t\t\tasyncMode,\n\t\t\t});\n\t\t\tawait runExtensionBuild({\n\t\t\t\t...context,\n\t\t\t\tsourceDir,\n\t\t\t\toutDir,\n\t\t\t\tname: options.name,\n\t\t\t\tphpVersion,\n\t\t\t\tphpRelease,\n\t\t\t\tasyncMode,\n\t\t\t\tartifactFile,\n\t\t\t\toptimize: options.optimize,\n\t\t\t\textraCflags: options.extraCflags,\n\t\t\t\textraLdflags: options.extraLdflags,\n\t\t\t\tconfigArgs: options.configArgs,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tphpVersion,\n\t\t\t\tsourcePath: artifactFile,\n\t\t\t\tpath: path.join(outDir, artifactFile),\n\t\t\t} satisfies BuiltArtifact;\n\t\t}\n\t);\n\n\tconst manifest = await createManifest({\n\t\tname: options.name,\n\t\tversion,\n\t\tartifacts,\n\t\textraFiles: options.extraFiles,\n\t});\n\tconst manifestPath = await writeManifest({ outDir, manifest });\n\treturn { manifestPath, artifacts, manifest };\n}\n\nexport function resolvePHPRelease(phpVersion: string): string {\n\treturn PHP_RELEASE_BY_MINOR[phpVersion] ?? phpVersion;\n}\n\nasync function detectManifestVersion(sourceDir: string): Promise<string> {\n\ttry {\n\t\tconst packageJson = JSON.parse(\n\t\t\tawait readFile(path.join(sourceDir, 'package.json'), 'utf8')\n\t\t) as { version?: unknown };\n\t\tif (typeof packageJson.version === 'string') {\n\t\t\treturn packageJson.version;\n\t\t}\n\t} catch {\n\t\t// Native PHP extension sources usually do not contain package.json.\n\t}\n\treturn '0.0.0';\n}\n\nasync function mapLimit<T, R>(\n\titems: T[],\n\tlimit: number,\n\tworker: (item: T) => Promise<R>\n): Promise<R[]> {\n\tconst results: R[] = new Array(items.length) as R[];\n\tlet nextIndex = 0;\n\tconst workers = Array.from(\n\t\t{ length: Math.min(limit, items.length) },\n\t\tasync () => {\n\t\t\twhile (nextIndex < items.length) {\n\t\t\t\tconst index = nextIndex++;\n\t\t\t\tresults[index] = await worker(items[index]);\n\t\t\t}\n\t\t}\n\t);\n\tawait Promise.all(workers);\n\treturn results;\n}\n\nfunction normalizeJobCount(\n\tjobs: number | undefined,\n\ttaskCount: number\n): number {\n\tif (taskCount === 0) {\n\t\treturn 1;\n\t}\n\tif (jobs && jobs > 0) {\n\t\treturn Math.min(jobs, taskCount);\n\t}\n\treturn Math.min(os.availableParallelism?.() ?? os.cpus().length, taskCount);\n}\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nconst EXTENSION_NAME_PATTERNS = [\n\t/\\bPHP_ARG_ENABLE\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n\t/\\bPHP_ARG_WITH\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n\t/\\bPHP_NEW_EXTENSION\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n];\n\nexport async function detectExtensionName(sourceDir: string): Promise<string> {\n\tconst configPath = path.join(sourceDir, 'config.m4');\n\tlet config: string;\n\ttry {\n\t\tconfig = await readFile(configPath, 'utf8');\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Could not read ${configPath}. Pass --name or provide a config.m4 file.`,\n\t\t\t{ cause: error }\n\t\t);\n\t}\n\n\tconst detected = detectExtensionNameFromConfig(config);\n\tif (!detected) {\n\t\tthrow new Error(\n\t\t\t`Could not detect the extension name from ${configPath}. Pass --name explicitly.`\n\t\t);\n\t}\n\treturn detected;\n}\n\nexport function detectExtensionNameFromConfig(config: string): string | null {\n\tfor (const pattern of EXTENSION_NAME_PATTERNS) {\n\t\tconst match = pattern.exec(config);\n\t\tif (match?.[1]) {\n\t\t\treturn match[1];\n\t\t}\n\t}\n\treturn null;\n}\n","import { cp, mkdir, readdir, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type {\n\tExtensionManifestExtraFile,\n\tExtensionManifestExtraFiles,\n} from './manifest';\n\n/**\n * Parses a `--extra-files` CLI argument of the form `<hostDir>:<vfsRoot>`.\n *\n * `vfsRoot` must be an absolute VFS path so the loader can stage files\n * without making up a default root. Splitting on the *last* colon lets\n * Windows host paths like `C:\\dir:/internal/root` round-trip cleanly.\n */\nexport function parseExtraFilesSpec(spec: string): {\n\thostDir: string;\n\tvfsRoot: string;\n} {\n\tconst separator = spec.lastIndexOf(':');\n\tif (separator < 0) {\n\t\tthrow new Error(\n\t\t\t`Invalid --extra-files value ${JSON.stringify(\n\t\t\t\tspec\n\t\t\t)}. Expected \"<hostDir>:<vfsRoot>\".`\n\t\t);\n\t}\n\tconst hostDir = spec.slice(0, separator);\n\tconst vfsRoot = spec.slice(separator + 1);\n\tif (!hostDir || !vfsRoot) {\n\t\tthrow new Error(\n\t\t\t`Invalid --extra-files value ${JSON.stringify(\n\t\t\t\tspec\n\t\t\t)}. Expected \"<hostDir>:<vfsRoot>\".`\n\t\t);\n\t}\n\tif (!vfsRoot.startsWith('/')) {\n\t\tthrow new Error(\n\t\t\t`--extra-files vfsRoot must be an absolute VFS path. Received ${JSON.stringify(\n\t\t\t\tvfsRoot\n\t\t\t)}.`\n\t\t);\n\t}\n\treturn { hostDir, vfsRoot };\n}\n\n/**\n * Copies one or more host directories into `outDir` and returns a manifest\n * `extraFiles` group whose `sourcePath` entries are relative to `outDir`.\n *\n * Each spec is `<hostDir>:<vfsRoot>`. All specs must agree on `vfsRoot`\n * because the manifest format only stores a single `vfsRoot` per group.\n *\n * Files keep their relative path under `vfsRoot`. Empty directories are\n * recorded as `type: 'directory'` nodes so the loader creates them.\n */\nexport async function stageExtraFilesIntoOutDir(\n\tspecs: Array<{ hostDir: string; vfsRoot: string }>,\n\toutDir: string,\n\tworkspaceRoot: string\n): Promise<ExtensionManifestExtraFiles | undefined> {\n\tif (!specs.length) {\n\t\treturn undefined;\n\t}\n\tconst vfsRoot = specs[0].vfsRoot;\n\tfor (const spec of specs) {\n\t\tif (spec.vfsRoot !== vfsRoot) {\n\t\t\tthrow new Error(\n\t\t\t\t'All --extra-files entries must share the same vfsRoot. Received ' +\n\t\t\t\t\tJSON.stringify(specs.map((entry) => entry.vfsRoot))\n\t\t\t);\n\t\t}\n\t}\n\n\tconst nodes: ExtensionManifestExtraFile[] = [];\n\tconst claimedVfsPaths = new Set<string>();\n\tconst claimedDestinations = new Set<string>();\n\tfor (const spec of specs) {\n\t\tconst absoluteHostDir = path.resolve(workspaceRoot, spec.hostDir);\n\t\tconst targetSubdir = path.basename(absoluteHostDir);\n\t\tconst destinationDir = path.join(outDir, targetSubdir);\n\t\tif (claimedDestinations.has(destinationDir)) {\n\t\t\tthrow new Error(\n\t\t\t\t`--extra-files destination collides on disk: ${destinationDir}. ` +\n\t\t\t\t\t`Two host directories share the same basename, so one would overwrite the other.`\n\t\t\t);\n\t\t}\n\t\tclaimedDestinations.add(destinationDir);\n\t\tawait mkdir(path.dirname(destinationDir), { recursive: true });\n\t\tawait cp(absoluteHostDir, destinationDir, { recursive: true });\n\n\t\tawait walk(destinationDir, async (entryPath, isDirectory) => {\n\t\t\tconst relativeUnderRoot = path\n\t\t\t\t.relative(destinationDir, entryPath)\n\t\t\t\t.split(path.sep)\n\t\t\t\t.join('/');\n\t\t\tif (!relativeUnderRoot) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sourcePath = `${targetSubdir}/${relativeUnderRoot}`;\n\t\t\tif (isDirectory) {\n\t\t\t\tconst empty = (await readdir(entryPath)).length === 0;\n\t\t\t\tif (!empty) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (claimedVfsPaths.has(relativeUnderRoot)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`--extra-files vfsPath collides across specs: ${relativeUnderRoot}.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tclaimedVfsPaths.add(relativeUnderRoot);\n\t\t\t\tnodes.push({\n\t\t\t\t\tvfsPath: relativeUnderRoot,\n\t\t\t\t\ttype: 'directory',\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (claimedVfsPaths.has(relativeUnderRoot)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`--extra-files vfsPath collides across specs: ${relativeUnderRoot}.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tclaimedVfsPaths.add(relativeUnderRoot);\n\t\t\tnodes.push({\n\t\t\t\tvfsPath: relativeUnderRoot,\n\t\t\t\tsourcePath,\n\t\t\t});\n\t\t});\n\t}\n\t// Sort with a locale-independent comparator so the manifest is byte-stable\n\t// across machines (`localeCompare` honors the host locale).\n\tnodes.sort((a, b) =>\n\t\ta.vfsPath < b.vfsPath ? -1 : a.vfsPath > b.vfsPath ? 1 : 0\n\t);\n\n\treturn {\n\t\tvfsRoot,\n\t\tnodes,\n\t};\n}\n\nasync function walk(\n\tdir: string,\n\tvisitor: (entryPath: string, isDirectory: boolean) => Promise<void>\n): Promise<void> {\n\tfor (const entry of await readdir(dir)) {\n\t\tconst entryPath = path.join(dir, entry);\n\t\tconst entryStat = await stat(entryPath);\n\t\tawait visitor(entryPath, entryStat.isDirectory());\n\t\tif (entryStat.isDirectory()) {\n\t\t\tawait walk(entryPath, visitor);\n\t\t}\n\t}\n}\n","#!/usr/bin/env node\nimport { existsSync, realpathSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\nimport {\n\tcompileExtensionMatrix,\n\tSupportedExtensionPHPVersions,\n} from './compile';\nimport { detectExtensionName } from './detect';\nimport { parseExtraFilesSpec, stageExtraFilesIntoOutDir } from './extra-files';\n\nconst OptionsWithDashPrefixedValues = new Set([\n\t'--config-args',\n\t'--extra-cflags',\n\t'--extra-ldflags',\n]);\n\nexport async function main(args = hideBin(process.argv)) {\n\tconst argv = await yargs(normalizeDashPrefixedOptionValues(args))\n\t\t.scriptName('@php-wasm/compile-extension')\n\t\t.usage('Usage: $0 --source <dir> [options]')\n\t\t.options({\n\t\t\tsource: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdemandOption: true,\n\t\t\t\tdescription: 'Extension source directory containing config.m4',\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extension name. Defaults to parsing config.m4.',\n\t\t\t},\n\t\t\t'php-versions': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: SupportedExtensionPHPVersions.join(','),\n\t\t\t\tdescription: 'Comma-separated PHP major.minor versions.',\n\t\t\t},\n\t\t\tout: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: './dist',\n\t\t\t\tdescription: 'Output directory.',\n\t\t\t},\n\t\t\t'extra-cflags': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extra CFLAGS appended to the side-module build.',\n\t\t\t},\n\t\t\t'extra-ldflags': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extra LDFLAGS appended to the side-module build.',\n\t\t\t},\n\t\t\t'config-args': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: '',\n\t\t\t\tdescription:\n\t\t\t\t\t'Extra ./configure arguments, parsed as shell words.',\n\t\t\t},\n\t\t\toptimize: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: '2',\n\t\t\t\tdescription: 'Optimization level passed as -O<level>.',\n\t\t\t},\n\t\t\tjobs: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Maximum concurrent docker builds.',\n\t\t\t},\n\t\t\t'extra-files': {\n\t\t\t\ttype: 'string',\n\t\t\t\tarray: true,\n\t\t\t\tdefault: [] as string[],\n\t\t\t\tdescription:\n\t\t\t\t\t'Stage a host directory under an absolute VFS root. Format: <hostDir>:<vfsRoot>. Files are copied next to the manifest and recorded in extraFiles.',\n\t\t\t},\n\t\t})\n\t\t.strict()\n\t\t.help()\n\t\t.parse();\n\n\tconst workspaceRoot = findWorkspaceRoot(process.cwd());\n\tconst sourceDir = path.resolve(workspaceRoot, argv['source'] as string);\n\tconst name =\n\t\t(argv['name'] as string | undefined) ??\n\t\t(await detectExtensionName(sourceDir));\n\tconst phpVersions = parseCsv(\n\t\targv['php-versions'] as string,\n\t\t'php-versions'\n\t);\n\tconst configArgs = splitShellWords((argv['config-args'] as string) || '');\n\tconst extraFilesSpecs = (argv['extra-files'] as string[]).map(\n\t\tparseExtraFilesSpec\n\t);\n\tconst outDir = path.resolve(workspaceRoot, argv['out'] as string);\n\tconst extraFiles = await stageExtraFilesIntoOutDir(\n\t\textraFilesSpecs,\n\t\toutDir,\n\t\tworkspaceRoot\n\t);\n\n\tconst result = await compileExtensionMatrix({\n\t\tworkspaceRoot,\n\t\tsourceDir,\n\t\toutDir: argv['out'] as string,\n\t\tname,\n\t\tphpVersions,\n\t\textraCflags: argv['extra-cflags'] as string | undefined,\n\t\textraLdflags: argv['extra-ldflags'] as string | undefined,\n\t\tconfigArgs,\n\t\toptimize: argv['optimize'] as string,\n\t\tjobs: argv['jobs'] as number | undefined,\n\t\textraFiles,\n\t});\n\n\tconsole.log(`Wrote ${result.artifacts.length} artifacts.`);\n\tconsole.log(`Wrote ${result.manifestPath}.`);\n}\n\nif (isCliEntrypoint(import.meta.url)) {\n\tmain().catch((error) => {\n\t\tconsole.error(error instanceof Error ? error.message : error);\n\t\tprocess.exit(1);\n\t});\n}\n\nexport function normalizeDashPrefixedOptionValues(args: string[]): string[] {\n\tconst normalized: string[] = [];\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (\n\t\t\tOptionsWithDashPrefixedValues.has(arg) &&\n\t\t\ti + 1 < args.length &&\n\t\t\t!args[i + 1].startsWith(`${arg}=`)\n\t\t) {\n\t\t\tnormalized.push(`${arg}=${args[i + 1]}`);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tnormalized.push(arg);\n\t}\n\treturn normalized;\n}\n\nfunction parseCsv(value: string, name: string): string[] {\n\tconst values = value\n\t\t.split(',')\n\t\t.map((entry) => entry.trim())\n\t\t.filter(Boolean);\n\tif (values.length === 0) {\n\t\tthrow new Error(`--${name} must contain at least one value.`);\n\t}\n\treturn values;\n}\n\nexport function splitShellWords(value: string): string[] {\n\tconst words: string[] = [];\n\tlet current = '';\n\tlet quote: '\"' | \"'\" | null = null;\n\tlet escaping = false;\n\n\tfor (const character of value) {\n\t\tif (escaping) {\n\t\t\tcurrent += character;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\\\\') {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) {\n\t\t\t\tquote = null;\n\t\t\t} else {\n\t\t\t\tcurrent += character;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"' || character === \"'\") {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(character)) {\n\t\t\tif (current.length > 0) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = '';\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (escaping) {\n\t\tcurrent += '\\\\';\n\t}\n\tif (quote) {\n\t\tthrow new Error('Unterminated quote in --config-args.');\n\t}\n\tif (current.length > 0) {\n\t\twords.push(current);\n\t}\n\treturn words;\n}\n\nfunction findWorkspaceRoot(startDirectory: string): string {\n\tlet directory = path.resolve(startDirectory);\n\twhile (directory !== path.dirname(directory)) {\n\t\tif (\n\t\t\texistsSync(path.join(directory, 'packages/php-wasm/compile')) &&\n\t\t\texistsSync(path.join(directory, 'nx.json'))\n\t\t) {\n\t\t\treturn directory;\n\t\t}\n\t\tdirectory = path.dirname(directory);\n\t}\n\treturn process.cwd();\n}\n\nfunction isCliEntrypoint(metaUrl: string): boolean {\n\tconst entrypoint = process.argv[1];\n\tif (!entrypoint) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn (\n\t\t\trealpathSync(entrypoint) === realpathSync(fileURLToPath(metaUrl))\n\t\t);\n\t} catch {\n\t\treturn path.resolve(entrypoint) === fileURLToPath(metaUrl);\n\t}\n}\n"],"names":["createDockerContext","workspaceRoot","phpWasmRoot","path","assertDockerIsAvailable","runCommand","error","buildBaseImage","context","buildExtensionImage","options","imageTag","getExtensionImageTag","runExtensionBuild","runArgs","arg","index","command","args","resolve","reject","child","spawn","code","ExtensionAsyncMode","createManifest","manifest","artifact","writeManifest","mkdir","manifestPath","writeFile","SupportedExtensionPHPVersions","PHP_RELEASE_BY_MINOR","compileExtensionMatrix","outDir","sourceDir","version","detectManifestVersion","matrix","phpVersion","artifacts","mapLimit","normalizeJobCount","asyncMode","phpRelease","resolvePHPRelease","artifactFile","packageJson","readFile","items","limit","worker","results","nextIndex","workers","jobs","taskCount","os","EXTENSION_NAME_PATTERNS","detectExtensionName","configPath","config","detected","detectExtensionNameFromConfig","pattern","match","parseExtraFilesSpec","spec","separator","hostDir","vfsRoot","stageExtraFilesIntoOutDir","specs","entry","nodes","claimedVfsPaths","claimedDestinations","absoluteHostDir","targetSubdir","destinationDir","cp","walk","entryPath","isDirectory","relativeUnderRoot","sourcePath","readdir","a","b","dir","visitor","entryStat","stat","OptionsWithDashPrefixedValues","main","hideBin","argv","yargs","normalizeDashPrefixedOptionValues","findWorkspaceRoot","name","phpVersions","parseCsv","configArgs","splitShellWords","extraFilesSpecs","extraFiles","result","isCliEntrypoint","normalized","i","value","values","words","current","quote","escaping","character","startDirectory","directory","existsSync","metaUrl","entrypoint","realpathSync","fileURLToPath"],"mappings":";6VA4BO,SAASA,EAAoBC,EAA2C,CAC9E,MAAMC,EAAcC,EAAK,KAAKF,EAAe,mBAAmB,EAChE,MAAO,CACN,cAAAA,EACA,YAAAC,EACA,YAAaC,EAAK,KAAKD,EAAa,SAAS,CAAA,CAE/C,CAEA,eAAsBE,GAAyC,CAC9D,GAAI,CACH,MAAMC,EAAW,SAAU,CAAC,WAAW,EAAG,CACzC,MAAO,QAAA,CACP,CACF,OAASC,EAAO,CACf,MAAM,IAAI,MACT,2FACA,CAAE,MAAOA,CAAA,CAAM,CAEjB,CACD,CAEA,eAAsBC,EAAeC,EAA6B,CACjE,MAAMH,EAAW,OAAQ,CAAC,YAAY,EAAG,CACxC,IAAKG,EAAQ,WAAA,CACb,CACF,CAEA,eAAsBC,EACrBC,EACkB,CAClB,MAAMC,EAAWC,EAAqBF,CAAO,EAC7C,aAAML,EACL,SACA,CACC,QACA,KACA,0CACA,IACA,SAASM,CAAQ,GACjB,mBACA,cACA,eAAeD,EAAQ,UAAU,GACjC,cACA,UAAA,EAED,CACC,IAAKA,EAAQ,WAAA,CACd,EAEMC,CACR,CAEA,eAAsBE,EAAkBH,EAA2B,CAClE,MAAMC,EAAWC,EAAqBF,CAAO,EACvCI,EAAU,CACf,MACA,OACA,KACA,GAAGJ,EAAQ,SAAS,WACpB,KACA,GAAGA,EAAQ,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,CAAS,GAAG,CAC7C,GACChB,EACCtB,EAAK,KACJsC,EACA,mDACD,GAEDhB,EAAWtB,EAAK,KAAKsC,EAAW,SAAS,CAAC,EAE1C,OAAOA,EAERA,EAAYtC,EAAK,QAAQsC,CAAS,CACnC,CACA,OAAO,QAAQ,KAChB,CAEA,SAASoH,GAAgBY,EAA0B,CAClD,MAAMC,EAAa,QAAQ,KAAK,CAAC,EACjC,GAAI,CAACA,EACJ,MAAO,GAER,GAAI,CACH,OACCC,EAAaD,CAAU,IAAMC,EAAapH,EAAckH,CAAO,CAAC,CAElE,MAAQ,CACP,OAAOtK,EAAK,QAAQuK,CAAU,IAAMnH,EAAckH,CAAO,CAC1D,CACD","names":["PlaygroundRepositoryUrl","DockerAssetPaths","PlaygroundDockerAssetPaths","relativePath","ensureDockerAssets","workspaceRoot","packageRoot","cacheRoot","getDockerAssetsCacheRoot","fetchDockerAssetsOption","ref","resolveDockerAssetsRef","phpWasmRoot","path","stableHash","isPhpWasmDockerContext","fetchedPhpWasmRoot","fetchDockerAssets","cacheDir","tempDir","tempPhpWasmRoot","rm","mkdir","sparseCheckoutFiles","__vitePreload","fetchedPaths","fetchedPath","stripPhpWasmPathPrefix","source","destination","rename","writeFile","publishFetchedDockerAssets","error","findMatchingLocalFiles","existsSync","isExistingPathError","isPlaygroundWorkspace","version","readPackageJson","configuredCacheDir","xdgCacheHome","home","os","packageJsonPath","readFileSync","value","createHash","prefix","root","relativePathPattern","directory","basenamePattern","readdirSync","entry","pathSegmentMatchesPattern","segment","pattern","escapeRegExp","createDockerContext","options","workspacePhpWasmRoot","createContext","findPackageRoot","packagePhpWasmRoot","fileURLToPath","assertDockerIsAvailable","runCommand","buildBaseImage","context","buildExtensionImage","imageTag","getExtensionImageTag","runExtensionBuild","runArgs","arg","index","command","args","resolve","reject","child","spawn","code","ExtensionAsyncMode","createManifest","manifest","artifact","writeManifest","manifestPath","SupportedExtensionPHPVersions","PHP_RELEASE_BY_MINOR","prepareExtensionBuildImages","matrix","phpVersion","mapLimit","normalizeJobCount","asyncMode","resolvePHPRelease","compileExtensionMatrix","outDir","sourceDir","detectManifestVersion","artifacts","phpRelease","artifactFile","packageJson","readFile","items","limit","worker","results","nextIndex","workers","jobs","taskCount","EXTENSION_NAME_PATTERNS","detectExtensionName","configPath","config","detected","detectExtensionNameFromConfig","match","parseExtraFilesSpec","spec","separator","hostDir","vfsRoot","stageExtraFilesIntoOutDir","specs","nodes","claimedVfsPaths","claimedDestinations","absoluteHostDir","targetSubdir","destinationDir","cp","walk","entryPath","isDirectory","relativeUnderRoot","sourcePath","readdir","a","b","dir","visitor","entryStat","stat","OptionsWithDashPrefixedValues","main","hideBin","argv","parseCliArgs","findWorkspaceRoot","phpVersions","parseCsv","result","image","name","configArgs","splitShellWords","extraFilesSpecs","extraFiles","yargs","normalizeDashPrefixedOptionValues","validateCliMode","isCliEntrypoint","normalized","i","hasSource","prepareImage","values","words","current","quote","escaping","character","startDirectory","metaUrl","entrypoint","realpathSync"],"ignoreList":[],"sources":["../../../../packages/php-wasm/compile-extension/src/docker-assets.ts","../../../../packages/php-wasm/compile-extension/src/docker.ts","../../../../packages/php-wasm/compile-extension/src/manifest.ts","../../../../packages/php-wasm/compile-extension/src/compile.ts","../../../../packages/php-wasm/compile-extension/src/detect.ts","../../../../packages/php-wasm/compile-extension/src/extra-files.ts","../../../../packages/php-wasm/compile-extension/src/cli.ts"],"sourcesContent":["import { createHash } from 'node:crypto';\nimport { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\n\nexport const PlaygroundRepositoryUrl =\n\t'https://github.com/WordPress/wordpress-playground.git';\n\nexport const DockerAssetPaths = [\n\t'compile/base-image/Dockerfile',\n\t'compile/base-image/emcc-for-php-wasm.sh',\n\t'compile/base-image/replace.sh',\n\t'compile/base-image/replace-across-lines.sh',\n\t'compile/php/php*.patch',\n\t'compile-extension/docker/Dockerfile.ext',\n\t'compile-extension/scripts/build-in-docker.sh',\n];\n\nconst PlaygroundDockerAssetPaths = DockerAssetPaths.map(\n\t(relativePath) => `packages/php-wasm/${relativePath}`\n);\n\nexport interface EnsureDockerAssetsOptions {\n\tworkspaceRoot: string;\n\tpackageRoot: string;\n\tcacheRoot?: string;\n\tfetchDockerAssets?: typeof fetchDockerAssets;\n}\n\nexport interface FetchDockerAssetsOptions {\n\tref: string;\n\tcacheRoot: string;\n}\n\nexport async function ensureDockerAssets({\n\tworkspaceRoot,\n\tpackageRoot,\n\tcacheRoot = getDockerAssetsCacheRoot(),\n\tfetchDockerAssets: fetchDockerAssetsOption,\n}: EnsureDockerAssetsOptions): Promise<string> {\n\tconst ref = resolveDockerAssetsRef({ workspaceRoot, packageRoot });\n\tconst phpWasmRoot = path.join(cacheRoot, stableHash(ref), 'php-wasm');\n\n\tif (isPhpWasmDockerContext(phpWasmRoot)) {\n\t\treturn phpWasmRoot;\n\t}\n\n\tconsole.log(\n\t\t`Fetching PHP.wasm Docker assets from WordPress/wordpress-playground ${ref}.`\n\t);\n\tconst fetchedPhpWasmRoot = await (\n\t\tfetchDockerAssetsOption ?? fetchDockerAssets\n\t)({ ref, cacheRoot });\n\tif (!isPhpWasmDockerContext(fetchedPhpWasmRoot)) {\n\t\tthrow new Error(\n\t\t\t`Fetched PHP.wasm Docker assets from ${ref}, but the cache is incomplete.`\n\t\t);\n\t}\n\treturn fetchedPhpWasmRoot;\n}\n\nexport async function fetchDockerAssets({\n\tref,\n\tcacheRoot,\n}: FetchDockerAssetsOptions): Promise<string> {\n\tconst cacheDir = path.join(cacheRoot, stableHash(ref));\n\tconst phpWasmRoot = path.join(cacheDir, 'php-wasm');\n\tconst tempDir = `${cacheDir}-${process.pid}-${Date.now()}.tmp`;\n\tconst tempPhpWasmRoot = path.join(tempDir, 'php-wasm');\n\n\tawait rm(tempDir, { recursive: true, force: true });\n\tawait mkdir(tempPhpWasmRoot, { recursive: true });\n\n\ttry {\n\t\tconst { sparseCheckoutFiles } = await import('./git-sparse-checkout');\n\t\tconst fetchedPaths = await sparseCheckoutFiles({\n\t\t\trepoUrl: PlaygroundRepositoryUrl,\n\t\t\tref,\n\t\t\tpaths: PlaygroundDockerAssetPaths,\n\t\t\toutDir: tempDir,\n\t\t\tworkDir: path.join(tempDir, '.git-work'),\n\t\t});\n\n\t\tfor (const fetchedPath of fetchedPaths) {\n\t\t\tconst relativePath = stripPhpWasmPathPrefix(fetchedPath);\n\t\t\tconst source = path.join(\n\t\t\t\ttempDir,\n\t\t\t\t'packages/php-wasm',\n\t\t\t\trelativePath\n\t\t\t);\n\t\t\tconst destination = path.join(tempPhpWasmRoot, relativePath);\n\t\t\tawait mkdir(path.dirname(destination), { recursive: true });\n\t\t\tawait rename(source, destination);\n\t\t}\n\n\t\tawait writeFile(\n\t\t\tpath.join(tempPhpWasmRoot, 'source.json'),\n\t\t\t`${JSON.stringify({ repository: PlaygroundRepositoryUrl, ref }, null, 2)}\\n`\n\t\t);\n\t\tawait rm(path.join(tempDir, '.git-work'), {\n\t\t\trecursive: true,\n\t\t\tforce: true,\n\t\t});\n\t\tawait rm(path.join(tempDir, 'packages'), {\n\t\t\trecursive: true,\n\t\t\tforce: true,\n\t\t});\n\n\t\tawait publishFetchedDockerAssets({\n\t\t\ttempDir,\n\t\t\tcacheDir,\n\t\t\tphpWasmRoot,\n\t\t});\n\t} catch (error) {\n\t\tawait rm(tempDir, { recursive: true, force: true });\n\t\tthrow error;\n\t}\n\n\treturn phpWasmRoot;\n}\n\nexport function isPhpWasmDockerContext(phpWasmRoot: string): boolean {\n\treturn DockerAssetPaths.every((relativePath) => {\n\t\tif (!relativePath.includes('*')) {\n\t\t\treturn existsSync(path.join(phpWasmRoot, relativePath));\n\t\t}\n\t\treturn findMatchingLocalFiles(phpWasmRoot, relativePath).length > 0;\n\t});\n}\n\nexport async function publishFetchedDockerAssets({\n\ttempDir,\n\tcacheDir,\n\tphpWasmRoot,\n}: {\n\ttempDir: string;\n\tcacheDir: string;\n\tphpWasmRoot: string;\n}): Promise<void> {\n\tawait mkdir(path.dirname(cacheDir), { recursive: true });\n\ttry {\n\t\tawait rename(tempDir, cacheDir);\n\t} catch (error) {\n\t\tif (isExistingPathError(error) && isPhpWasmDockerContext(phpWasmRoot)) {\n\t\t\tawait rm(tempDir, { recursive: true, force: true });\n\t\t\treturn;\n\t\t}\n\t\tthrow error;\n\t}\n}\n\nexport function resolveDockerAssetsRef({\n\tworkspaceRoot,\n\tpackageRoot,\n}: {\n\tworkspaceRoot: string;\n\tpackageRoot: string;\n}): string {\n\tif (isPlaygroundWorkspace(workspaceRoot)) {\n\t\treturn 'trunk';\n\t}\n\tconst packageJson = readPackageJson(packageRoot);\n\tconst version = packageJson.version;\n\tif (!version) {\n\t\tthrow new Error(\n\t\t\t`Could not resolve @php-wasm/compile-extension version from ${packageRoot}.`\n\t\t);\n\t}\n\treturn `v${version}`;\n}\n\nexport function isPlaygroundWorkspace(workspaceRoot: string): boolean {\n\treturn (\n\t\texistsSync(path.join(workspaceRoot, 'nx.json')) &&\n\t\texistsSync(\n\t\t\tpath.join(\n\t\t\t\tworkspaceRoot,\n\t\t\t\t'packages/php-wasm/compile-extension/package.json'\n\t\t\t)\n\t\t)\n\t);\n}\n\nexport function getDockerAssetsCacheRoot(): string {\n\tconst configuredCacheDir =\n\t\tprocess.env['PHP_WASM_COMPILE_EXTENSION_CACHE_DIR'];\n\tif (configuredCacheDir) {\n\t\treturn configuredCacheDir;\n\t}\n\tconst xdgCacheHome = process.env['XDG_CACHE_HOME'];\n\tif (xdgCacheHome) {\n\t\treturn path.join(\n\t\t\txdgCacheHome,\n\t\t\t'php-wasm/compile-extension/docker-assets'\n\t\t);\n\t}\n\tconst home = os.homedir();\n\tif (home) {\n\t\treturn path.join(home, '.cache/php-wasm/compile-extension/docker-assets');\n\t}\n\treturn path.join(os.tmpdir(), 'php-wasm/compile-extension/docker-assets');\n}\n\nfunction readPackageJson(packageRoot: string): { version?: string } {\n\tconst packageJsonPath = path.join(packageRoot, 'package.json');\n\tif (!existsSync(packageJsonPath)) {\n\t\treturn {};\n\t}\n\treturn JSON.parse(\n\t\t// This file is tiny and read synchronously while resolving CLI startup\n\t\t// paths; keeping the API sync avoids threading async through ref helpers.\n\t\treadFileSync(packageJsonPath, 'utf8')\n\t) as { version?: string };\n}\n\nexport async function readDockerAssetSource(\n\tphpWasmRoot: string\n): Promise<{ repository: string; ref: string } | undefined> {\n\tconst sourceFile = path.join(phpWasmRoot, 'source.json');\n\tif (!existsSync(sourceFile)) {\n\t\treturn undefined;\n\t}\n\treturn readJsonFile(sourceFile);\n}\n\nfunction stableHash(value: string): string {\n\treturn createHash('sha256').update(value).digest('hex').slice(0, 16);\n}\n\nfunction stripPhpWasmPathPrefix(fetchedPath: string): string {\n\tconst prefix = 'packages/php-wasm/';\n\tif (!fetchedPath.startsWith(prefix)) {\n\t\tthrow new Error(`Unexpected fetched Docker asset path: ${fetchedPath}`);\n\t}\n\treturn fetchedPath.slice(prefix.length);\n}\n\nfunction findMatchingLocalFiles(\n\troot: string,\n\trelativePathPattern: string\n): string[] {\n\tconst directory = path.join(root, path.dirname(relativePathPattern));\n\tconst basenamePattern = path.basename(relativePathPattern);\n\tif (!existsSync(directory)) {\n\t\treturn [];\n\t}\n\treturn readdirSync(directory, { withFileTypes: true })\n\t\t.filter(\n\t\t\t(entry) =>\n\t\t\t\tentry.isFile() &&\n\t\t\t\tpathSegmentMatchesPattern(entry.name, basenamePattern)\n\t\t)\n\t\t.map((entry) =>\n\t\t\tpath\n\t\t\t\t.join(path.dirname(relativePathPattern), entry.name)\n\t\t\t\t.split(path.sep)\n\t\t\t\t.join('/')\n\t\t)\n\t\t.sort();\n}\n\nfunction pathSegmentMatchesPattern(segment: string, pattern: string): boolean {\n\tif (!pattern.includes('*')) {\n\t\treturn segment === pattern;\n\t}\n\treturn new RegExp(\n\t\t`^${pattern\n\t\t\t.split('*')\n\t\t\t.map(escapeRegExp)\n\t\t\t.join('.*')}$`\n\t).test(segment);\n}\n\nfunction escapeRegExp(value: string): string {\n\treturn value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n\nasync function readJsonFile<T>(filename: string): Promise<T> {\n\treturn JSON.parse(await readFile(filename, 'utf8')) as T;\n}\n\nfunction isExistingPathError(error: unknown): boolean {\n\treturn (\n\t\ttypeof error === 'object' &&\n\t\terror !== null &&\n\t\t'code' in error &&\n\t\t['EEXIST', 'ENOTEMPTY', 'EPERM'].includes(String(error.code))\n\t);\n}\n","import { spawn } from 'node:child_process';\nimport { existsSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport {\n\tensureDockerAssets,\n\tisPhpWasmDockerContext,\n\ttype EnsureDockerAssetsOptions,\n} from './docker-assets';\nimport type { AsyncMode } from './manifest';\n\nexport interface DockerBuildContext {\n\tworkspaceRoot: string;\n\tphpWasmRoot: string;\n\tcompileRoot: string;\n\tcompileExtensionRoot: string;\n}\n\nexport interface DockerImageOptions extends DockerBuildContext {\n\tphpVersion: string;\n\tphpRelease: string;\n\tasyncMode: AsyncMode;\n}\n\nexport interface DockerRunOptions extends DockerImageOptions {\n\tsourceDir: string;\n\toutDir: string;\n\tname: string;\n\tartifactFile: string;\n\toptimize: string;\n\textraCflags?: string;\n\textraLdflags?: string;\n\tconfigArgs: string[];\n}\n\nexport interface CreateDockerContextOptions {\n\tpackageRoot?: string;\n\tcacheRoot?: string;\n\tfetchDockerAssets?: EnsureDockerAssetsOptions['fetchDockerAssets'];\n}\n\nexport async function createDockerContext(\n\tworkspaceRoot: string,\n\toptions: CreateDockerContextOptions = {}\n): Promise<DockerBuildContext> {\n\tconst workspacePhpWasmRoot = path.join(workspaceRoot, 'packages/php-wasm');\n\tif (isPhpWasmDockerContext(workspacePhpWasmRoot)) {\n\t\treturn createContext(workspaceRoot, workspacePhpWasmRoot);\n\t}\n\n\tconst packageRoot = options.packageRoot ?? findPackageRoot();\n\tconst packagePhpWasmRoot = path.join(packageRoot, 'php-wasm');\n\tif (isPhpWasmDockerContext(packagePhpWasmRoot)) {\n\t\treturn createContext(workspaceRoot, packagePhpWasmRoot);\n\t}\n\n\tconst fetchedPhpWasmRoot = await ensureDockerAssets({\n\t\tworkspaceRoot,\n\t\tpackageRoot,\n\t\tcacheRoot: options.cacheRoot,\n\t\tfetchDockerAssets: options.fetchDockerAssets,\n\t});\n\treturn createContext(workspaceRoot, fetchedPhpWasmRoot);\n}\n\nfunction createContext(\n\tworkspaceRoot: string,\n\tphpWasmRoot: string\n): DockerBuildContext {\n\treturn {\n\t\tworkspaceRoot,\n\t\tphpWasmRoot,\n\t\tcompileRoot: path.join(phpWasmRoot, 'compile'),\n\t\tcompileExtensionRoot: path.join(phpWasmRoot, 'compile-extension'),\n\t};\n}\n\nfunction findPackageRoot(): string {\n\tlet directory = path.dirname(fileURLToPath(import.meta.url));\n\twhile (directory !== path.dirname(directory)) {\n\t\tif (existsSync(path.join(directory, 'package.json'))) {\n\t\t\treturn directory;\n\t\t}\n\t\tdirectory = path.dirname(directory);\n\t}\n\treturn path.dirname(fileURLToPath(import.meta.url));\n}\n\nexport async function assertDockerIsAvailable(): Promise<void> {\n\ttry {\n\t\tawait runCommand('docker', ['--version'], {\n\t\t\tstdio: 'ignore',\n\t\t});\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t'Docker is required to compile PHP.wasm extensions, but the docker command was not found.',\n\t\t\t{ cause: error }\n\t\t);\n\t}\n}\n\nexport async function buildBaseImage(context: DockerBuildContext) {\n\tawait runCommand(\n\t\t'docker',\n\t\t[\n\t\t\t'build',\n\t\t\t'-f',\n\t\t\t'./Dockerfile',\n\t\t\t'.',\n\t\t\t'--tag=playground-php-wasm:base',\n\t\t\t'--progress=plain',\n\t\t],\n\t\t{\n\t\t\tcwd: path.join(context.compileRoot, 'base-image'),\n\t\t}\n\t);\n}\n\nexport async function buildExtensionImage(\n\toptions: DockerImageOptions\n): Promise<string> {\n\tconst imageTag = getExtensionImageTag(options);\n\tawait runCommand(\n\t\t'docker',\n\t\t[\n\t\t\t'build',\n\t\t\t'-f',\n\t\t\t'compile-extension/docker/Dockerfile.ext',\n\t\t\t'.',\n\t\t\t`--tag=${imageTag}`,\n\t\t\t'--progress=plain',\n\t\t\t'--build-arg',\n\t\t\t`PHP_VERSION=${options.phpRelease}`,\n\t\t\t'--build-arg',\n\t\t\t'JSPI=yes',\n\t\t],\n\t\t{\n\t\t\tcwd: options.phpWasmRoot,\n\t\t}\n\t);\n\treturn imageTag;\n}\n\nexport async function runExtensionBuild(options: DockerRunOptions) {\n\tconst imageTag = getExtensionImageTag(options);\n\tconst runArgs = [\n\t\t'run',\n\t\t'--rm',\n\t\t'-v',\n\t\t`${options.sourceDir}:/src:ro`,\n\t\t'-v',\n\t\t`${options.outDir}:/out`,\n\t\t'-v',\n\t\t`${options.compileRoot}:/php-wasm-compile:ro`,\n\t\t'--env',\n\t\t`EXTENSION_NAME=${options.name}`,\n\t\t'--env',\n\t\t`PHP_VERSION_SHORT=${options.phpVersion}`,\n\t\t'--env',\n\t\t`ASYNC_MODE=${options.asyncMode}`,\n\t\t'--env',\n\t\t`ARTIFACT_FILENAME=${options.artifactFile}`,\n\t\t'--env',\n\t\t`OPTIMIZE=${options.optimize}`,\n\t\t'--env',\n\t\t`CONFIG_ARGS_COUNT=${options.configArgs.length}`,\n\t];\n\n\tif (options.extraCflags) {\n\t\trunArgs.push('--env', `EXTRA_CFLAGS=${options.extraCflags}`);\n\t}\n\tif (options.extraLdflags) {\n\t\trunArgs.push('--env', `EXTRA_LDFLAGS=${options.extraLdflags}`);\n\t}\n\n\toptions.configArgs.forEach((arg, index) => {\n\t\trunArgs.push('--env', `CONFIG_ARG_${index}=${arg}`);\n\t});\n\n\trunArgs.push(imageTag);\n\n\tawait runCommand('docker', runArgs, {\n\t\tcwd: options.workspaceRoot,\n\t});\n}\n\nfunction getExtensionImageTag(\n\toptions: Pick<DockerImageOptions, 'phpVersion' | 'asyncMode'>\n) {\n\tconst phpVersion = options.phpVersion.replaceAll('.', '-');\n\treturn `playground-php-wasm:compile-extension-php${phpVersion}-${options.asyncMode}`;\n}\n\ninterface RunCommandOptions {\n\tcwd?: string;\n\tstdio?: 'inherit' | 'ignore';\n}\n\nasync function runCommand(\n\tcommand: string,\n\targs: string[],\n\toptions: RunCommandOptions = {}\n): Promise<void> {\n\tconsole.log(`Running ${command} ${args.join(' ')}`);\n\tawait new Promise<void>((resolve, reject) => {\n\t\tconst child = spawn(command, args, {\n\t\t\tcwd: options.cwd,\n\t\t\tstdio: options.stdio ?? 'inherit',\n\t\t\tenv: process.env,\n\t\t});\n\t\tchild.on('error', reject);\n\t\tchild.on('close', (code) => {\n\t\t\tif (code === 0) {\n\t\t\t\tresolve();\n\t\t\t\treturn;\n\t\t\t}\n\t\t\treject(new Error(`${command} exited with code ${code}`));\n\t\t});\n\t});\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nexport const ExtensionAsyncMode = 'jspi';\nexport type AsyncMode = typeof ExtensionAsyncMode;\n\n/**\n * One sidecar file or empty directory staged alongside an artifact.\n *\n * Mirrors `PHPExtensionManifestExtraFile` in `@php-wasm/universal`.\n */\nexport interface ExtensionManifestExtraFile {\n\t/** Joined with the group's `vfsRoot` to form the final VFS path. */\n\tvfsPath: string;\n\t/** Defaults to \"file\". Only file nodes need a `sourcePath`. */\n\ttype?: 'file' | 'directory';\n\t/** Relative to the manifest URL/base URL, or an absolute URL. */\n\tsourcePath?: string;\n}\n\nexport interface ExtensionManifestExtraFiles {\n\t/** Absolute VFS prefix joined with each node's `vfsPath`. */\n\tvfsRoot?: string;\n\tnodes?: ExtensionManifestExtraFile[];\n}\n\nexport interface ExtensionArtifact {\n\tphpVersion: string;\n\t/** Path to the `.so` file, relative to the manifest URL or absolute. */\n\tsourcePath: string;\n\t/** URL-backed files needed only by this artifact. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport interface ExtensionManifest {\n\tname: string;\n\tversion: string;\n\tartifacts: ExtensionArtifact[];\n\t/** URL-backed files shared by every artifact in this manifest. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport interface BuiltArtifact {\n\tphpVersion: string;\n\t/** Path to the `.so` file, relative to the manifest URL. */\n\tsourcePath: string;\n\t/** Absolute path on disk where the `.so` was written. */\n\tpath: string;\n}\n\nexport async function createManifest(options: {\n\tname: string;\n\tversion: string;\n\tartifacts: BuiltArtifact[];\n\textraFiles?: ExtensionManifestExtraFiles;\n}): Promise<ExtensionManifest> {\n\tconst manifest: ExtensionManifest = {\n\t\tname: options.name,\n\t\tversion: options.version,\n\t\tartifacts: options.artifacts.map((artifact) => ({\n\t\t\tphpVersion: artifact.phpVersion,\n\t\t\tsourcePath: artifact.sourcePath,\n\t\t})),\n\t};\n\tif (options.extraFiles) {\n\t\tmanifest.extraFiles = options.extraFiles;\n\t}\n\treturn manifest;\n}\n\nexport async function writeManifest(options: {\n\toutDir: string;\n\tmanifest: ExtensionManifest;\n}): Promise<string> {\n\tawait mkdir(options.outDir, { recursive: true });\n\tconst manifestPath = path.join(options.outDir, 'manifest.json');\n\tawait writeFile(\n\t\tmanifestPath,\n\t\t`${JSON.stringify(options.manifest, null, 2)}\\n`\n\t);\n\treturn manifestPath;\n}\n\nexport function findExtensionArtifact(\n\tmanifest: ExtensionManifest,\n\tphpVersion: string\n): ExtensionArtifact | undefined {\n\treturn manifest.artifacts.find(\n\t\t(artifact) => artifact.phpVersion === phpVersion\n\t);\n}\n","import { mkdir, readFile } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\n\nimport {\n\tassertDockerIsAvailable,\n\tbuildBaseImage,\n\tbuildExtensionImage,\n\tcreateDockerContext,\n\trunExtensionBuild,\n} from './docker';\nimport type {\n\tAsyncMode,\n\tBuiltArtifact,\n\tExtensionManifestExtraFiles,\n} from './manifest';\nimport { createManifest, ExtensionAsyncMode, writeManifest } from './manifest';\n\nexport const SupportedExtensionPHPVersions = [\n\t'8.5',\n\t'8.4',\n\t'8.3',\n\t'8.2',\n\t'8.1',\n\t'8.0',\n\t'7.4',\n] as const;\n\nconst PHP_RELEASE_BY_MINOR: Record<string, string> = {\n\t'8.5': '8.5.5',\n\t'8.4': '8.4.20',\n\t'8.3': '8.3.30',\n\t'8.2': '8.2.30',\n\t'8.1': '8.1.34',\n\t'8.0': '8.0.30',\n\t'7.4': '7.4.33',\n};\n\nexport interface CompileExtensionOptions {\n\tworkspaceRoot: string;\n\tsourceDir: string;\n\toutDir: string;\n\tname: string;\n\tphpVersions: string[];\n\textraCflags?: string;\n\textraLdflags?: string;\n\tconfigArgs: string[];\n\toptimize: string;\n\tjobs?: number;\n\t/** Sidecar files to record at the manifest level. */\n\textraFiles?: ExtensionManifestExtraFiles;\n}\n\nexport interface PrepareExtensionBuildImagesOptions {\n\tworkspaceRoot: string;\n\tphpVersions: string[];\n\tjobs?: number;\n}\n\nexport async function prepareExtensionBuildImages(\n\toptions: PrepareExtensionBuildImagesOptions\n) {\n\tawait assertDockerIsAvailable();\n\n\tconst context = await createDockerContext(options.workspaceRoot);\n\tconst matrix: Array<{ phpVersion: string; asyncMode: AsyncMode }> =\n\t\toptions.phpVersions.map((phpVersion) => ({\n\t\t\tphpVersion,\n\t\t\tasyncMode: ExtensionAsyncMode,\n\t\t}));\n\n\tawait buildBaseImage(context);\n\n\tconst images = await mapLimit(\n\t\tmatrix,\n\t\tnormalizeJobCount(options.jobs, matrix.length),\n\t\tasync ({ phpVersion, asyncMode }) => {\n\t\t\tconst imageTag = await buildExtensionImage({\n\t\t\t\t...context,\n\t\t\t\tphpVersion,\n\t\t\t\tphpRelease: resolvePHPRelease(phpVersion),\n\t\t\t\tasyncMode,\n\t\t\t});\n\t\t\treturn { phpVersion, asyncMode, imageTag };\n\t\t}\n\t);\n\n\treturn { images };\n}\n\nexport async function compileExtensionMatrix(options: CompileExtensionOptions) {\n\tconst outDir = path.resolve(options.workspaceRoot, options.outDir);\n\tconst sourceDir = path.resolve(options.workspaceRoot, options.sourceDir);\n\tawait assertDockerIsAvailable();\n\n\tconst context = await createDockerContext(options.workspaceRoot);\n\tconst version = await detectManifestVersion(sourceDir);\n\tconst matrix: Array<{ phpVersion: string; asyncMode: AsyncMode }> =\n\t\toptions.phpVersions.map((phpVersion) => ({\n\t\t\tphpVersion,\n\t\t\tasyncMode: ExtensionAsyncMode,\n\t}));\n\n\tawait mkdir(outDir, { recursive: true });\n\tawait buildBaseImage(context);\n\n\tconst artifacts = await mapLimit(\n\t\tmatrix,\n\t\tnormalizeJobCount(options.jobs, matrix.length),\n\t\tasync ({ phpVersion, asyncMode }) => {\n\t\t\tconst phpRelease = resolvePHPRelease(phpVersion);\n\t\t\tconst artifactFile = `${options.name}-php${phpVersion}-${asyncMode}.so`;\n\t\t\tawait buildExtensionImage({\n\t\t\t\t...context,\n\t\t\t\tphpVersion,\n\t\t\t\tphpRelease,\n\t\t\t\tasyncMode,\n\t\t\t});\n\t\t\tawait runExtensionBuild({\n\t\t\t\t...context,\n\t\t\t\tsourceDir,\n\t\t\t\toutDir,\n\t\t\t\tname: options.name,\n\t\t\t\tphpVersion,\n\t\t\t\tphpRelease,\n\t\t\t\tasyncMode,\n\t\t\t\tartifactFile,\n\t\t\t\toptimize: options.optimize,\n\t\t\t\textraCflags: options.extraCflags,\n\t\t\t\textraLdflags: options.extraLdflags,\n\t\t\t\tconfigArgs: options.configArgs,\n\t\t\t});\n\t\t\treturn {\n\t\t\t\tphpVersion,\n\t\t\t\tsourcePath: artifactFile,\n\t\t\t\tpath: path.join(outDir, artifactFile),\n\t\t\t} satisfies BuiltArtifact;\n\t\t}\n\t);\n\n\tconst manifest = await createManifest({\n\t\tname: options.name,\n\t\tversion,\n\t\tartifacts,\n\t\textraFiles: options.extraFiles,\n\t});\n\tconst manifestPath = await writeManifest({ outDir, manifest });\n\treturn { manifestPath, artifacts, manifest };\n}\n\nexport function resolvePHPRelease(phpVersion: string): string {\n\treturn PHP_RELEASE_BY_MINOR[phpVersion] ?? phpVersion;\n}\n\nasync function detectManifestVersion(sourceDir: string): Promise<string> {\n\ttry {\n\t\tconst packageJson = JSON.parse(\n\t\t\tawait readFile(path.join(sourceDir, 'package.json'), 'utf8')\n\t\t) as { version?: unknown };\n\t\tif (typeof packageJson.version === 'string') {\n\t\t\treturn packageJson.version;\n\t\t}\n\t} catch {\n\t\t// Native PHP extension sources usually do not contain package.json.\n\t}\n\treturn '0.0.0';\n}\n\nasync function mapLimit<T, R>(\n\titems: T[],\n\tlimit: number,\n\tworker: (item: T) => Promise<R>\n): Promise<R[]> {\n\tconst results: R[] = new Array(items.length) as R[];\n\tlet nextIndex = 0;\n\tconst workers = Array.from(\n\t\t{ length: Math.min(limit, items.length) },\n\t\tasync () => {\n\t\t\twhile (nextIndex < items.length) {\n\t\t\t\tconst index = nextIndex++;\n\t\t\t\tresults[index] = await worker(items[index]);\n\t\t\t}\n\t\t}\n\t);\n\tawait Promise.all(workers);\n\treturn results;\n}\n\nfunction normalizeJobCount(\n\tjobs: number | undefined,\n\ttaskCount: number\n): number {\n\tif (taskCount === 0) {\n\t\treturn 1;\n\t}\n\tif (jobs && jobs > 0) {\n\t\treturn Math.min(jobs, taskCount);\n\t}\n\treturn Math.min(os.availableParallelism?.() ?? os.cpus().length, taskCount);\n}\n","import { readFile } from 'node:fs/promises';\nimport path from 'node:path';\n\nconst EXTENSION_NAME_PATTERNS = [\n\t/\\bPHP_ARG_ENABLE\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n\t/\\bPHP_ARG_WITH\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n\t/\\bPHP_NEW_EXTENSION\\(\\s*\\[?([A-Za-z0-9_]+)\\]?/m,\n];\n\nexport async function detectExtensionName(sourceDir: string): Promise<string> {\n\tconst configPath = path.join(sourceDir, 'config.m4');\n\tlet config: string;\n\ttry {\n\t\tconfig = await readFile(configPath, 'utf8');\n\t} catch (error) {\n\t\tthrow new Error(\n\t\t\t`Could not read ${configPath}. Pass --name or provide a config.m4 file.`,\n\t\t\t{ cause: error }\n\t\t);\n\t}\n\n\tconst detected = detectExtensionNameFromConfig(config);\n\tif (!detected) {\n\t\tthrow new Error(\n\t\t\t`Could not detect the extension name from ${configPath}. Pass --name explicitly.`\n\t\t);\n\t}\n\treturn detected;\n}\n\nexport function detectExtensionNameFromConfig(config: string): string | null {\n\tfor (const pattern of EXTENSION_NAME_PATTERNS) {\n\t\tconst match = pattern.exec(config);\n\t\tif (match?.[1]) {\n\t\t\treturn match[1];\n\t\t}\n\t}\n\treturn null;\n}\n","import { cp, mkdir, readdir, stat } from 'node:fs/promises';\nimport path from 'node:path';\n\nimport type {\n\tExtensionManifestExtraFile,\n\tExtensionManifestExtraFiles,\n} from './manifest';\n\n/**\n * Parses a `--extra-files` CLI argument of the form `<hostDir>:<vfsRoot>`.\n *\n * `vfsRoot` must be an absolute VFS path so the loader can stage files\n * without making up a default root. Splitting on the *last* colon lets\n * Windows host paths like `C:\\dir:/internal/root` round-trip cleanly.\n */\nexport function parseExtraFilesSpec(spec: string): {\n\thostDir: string;\n\tvfsRoot: string;\n} {\n\tconst separator = spec.lastIndexOf(':');\n\tif (separator < 0) {\n\t\tthrow new Error(\n\t\t\t`Invalid --extra-files value ${JSON.stringify(\n\t\t\t\tspec\n\t\t\t)}. Expected \"<hostDir>:<vfsRoot>\".`\n\t\t);\n\t}\n\tconst hostDir = spec.slice(0, separator);\n\tconst vfsRoot = spec.slice(separator + 1);\n\tif (!hostDir || !vfsRoot) {\n\t\tthrow new Error(\n\t\t\t`Invalid --extra-files value ${JSON.stringify(\n\t\t\t\tspec\n\t\t\t)}. Expected \"<hostDir>:<vfsRoot>\".`\n\t\t);\n\t}\n\tif (!vfsRoot.startsWith('/')) {\n\t\tthrow new Error(\n\t\t\t`--extra-files vfsRoot must be an absolute VFS path. Received ${JSON.stringify(\n\t\t\t\tvfsRoot\n\t\t\t)}.`\n\t\t);\n\t}\n\treturn { hostDir, vfsRoot };\n}\n\n/**\n * Copies one or more host directories into `outDir` and returns a manifest\n * `extraFiles` group whose `sourcePath` entries are relative to `outDir`.\n *\n * Each spec is `<hostDir>:<vfsRoot>`. All specs must agree on `vfsRoot`\n * because the manifest format only stores a single `vfsRoot` per group.\n *\n * Files keep their relative path under `vfsRoot`. Empty directories are\n * recorded as `type: 'directory'` nodes so the loader creates them.\n */\nexport async function stageExtraFilesIntoOutDir(\n\tspecs: Array<{ hostDir: string; vfsRoot: string }>,\n\toutDir: string,\n\tworkspaceRoot: string\n): Promise<ExtensionManifestExtraFiles | undefined> {\n\tif (!specs.length) {\n\t\treturn undefined;\n\t}\n\tconst vfsRoot = specs[0].vfsRoot;\n\tfor (const spec of specs) {\n\t\tif (spec.vfsRoot !== vfsRoot) {\n\t\t\tthrow new Error(\n\t\t\t\t'All --extra-files entries must share the same vfsRoot. Received ' +\n\t\t\t\t\tJSON.stringify(specs.map((entry) => entry.vfsRoot))\n\t\t\t);\n\t\t}\n\t}\n\n\tconst nodes: ExtensionManifestExtraFile[] = [];\n\tconst claimedVfsPaths = new Set<string>();\n\tconst claimedDestinations = new Set<string>();\n\tfor (const spec of specs) {\n\t\tconst absoluteHostDir = path.resolve(workspaceRoot, spec.hostDir);\n\t\tconst targetSubdir = path.basename(absoluteHostDir);\n\t\tconst destinationDir = path.join(outDir, targetSubdir);\n\t\tif (claimedDestinations.has(destinationDir)) {\n\t\t\tthrow new Error(\n\t\t\t\t`--extra-files destination collides on disk: ${destinationDir}. ` +\n\t\t\t\t\t`Two host directories share the same basename, so one would overwrite the other.`\n\t\t\t);\n\t\t}\n\t\tclaimedDestinations.add(destinationDir);\n\t\tawait mkdir(path.dirname(destinationDir), { recursive: true });\n\t\tawait cp(absoluteHostDir, destinationDir, { recursive: true });\n\n\t\tawait walk(destinationDir, async (entryPath, isDirectory) => {\n\t\t\tconst relativeUnderRoot = path\n\t\t\t\t.relative(destinationDir, entryPath)\n\t\t\t\t.split(path.sep)\n\t\t\t\t.join('/');\n\t\t\tif (!relativeUnderRoot) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst sourcePath = `${targetSubdir}/${relativeUnderRoot}`;\n\t\t\tif (isDirectory) {\n\t\t\t\tconst empty = (await readdir(entryPath)).length === 0;\n\t\t\t\tif (!empty) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tif (claimedVfsPaths.has(relativeUnderRoot)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`--extra-files vfsPath collides across specs: ${relativeUnderRoot}.`\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tclaimedVfsPaths.add(relativeUnderRoot);\n\t\t\t\tnodes.push({\n\t\t\t\t\tvfsPath: relativeUnderRoot,\n\t\t\t\t\ttype: 'directory',\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (claimedVfsPaths.has(relativeUnderRoot)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`--extra-files vfsPath collides across specs: ${relativeUnderRoot}.`\n\t\t\t\t);\n\t\t\t}\n\t\t\tclaimedVfsPaths.add(relativeUnderRoot);\n\t\t\tnodes.push({\n\t\t\t\tvfsPath: relativeUnderRoot,\n\t\t\t\tsourcePath,\n\t\t\t});\n\t\t});\n\t}\n\t// Sort with a locale-independent comparator so the manifest is byte-stable\n\t// across machines (`localeCompare` honors the host locale).\n\tnodes.sort((a, b) =>\n\t\ta.vfsPath < b.vfsPath ? -1 : a.vfsPath > b.vfsPath ? 1 : 0\n\t);\n\n\treturn {\n\t\tvfsRoot,\n\t\tnodes,\n\t};\n}\n\nasync function walk(\n\tdir: string,\n\tvisitor: (entryPath: string, isDirectory: boolean) => Promise<void>\n): Promise<void> {\n\tfor (const entry of await readdir(dir)) {\n\t\tconst entryPath = path.join(dir, entry);\n\t\tconst entryStat = await stat(entryPath);\n\t\tawait visitor(entryPath, entryStat.isDirectory());\n\t\tif (entryStat.isDirectory()) {\n\t\t\tawait walk(entryPath, visitor);\n\t\t}\n\t}\n}\n","#!/usr/bin/env node\nimport { existsSync, realpathSync } from 'node:fs';\nimport path from 'node:path';\nimport { fileURLToPath } from 'node:url';\n\nimport yargs from 'yargs';\nimport { hideBin } from 'yargs/helpers';\n\nimport {\n\tcompileExtensionMatrix,\n\tprepareExtensionBuildImages,\n\tSupportedExtensionPHPVersions,\n} from './compile';\nimport { detectExtensionName } from './detect';\nimport { parseExtraFilesSpec, stageExtraFilesIntoOutDir } from './extra-files';\n\nconst OptionsWithDashPrefixedValues = new Set([\n\t'--config-args',\n\t'--extra-cflags',\n\t'--extra-ldflags',\n]);\n\nexport async function main(args = hideBin(process.argv)) {\n\tconst argv = await parseCliArgs(args);\n\tconst workspaceRoot = findWorkspaceRoot(process.cwd());\n\tconst phpVersions = parseCsv(\n\t\targv['php-versions'] as string,\n\t\t'php-versions'\n\t);\n\n\tif (argv['prepare-image']) {\n\t\tconst result = await prepareExtensionBuildImages({\n\t\t\tworkspaceRoot,\n\t\t\tphpVersions,\n\t\t\tjobs: argv['jobs'] as number | undefined,\n\t\t});\n\t\tconsole.log(\n\t\t\t`Prepared ${result.images.length} PHP.wasm extension build images.`\n\t\t);\n\t\tfor (const image of result.images) {\n\t\t\tconsole.log(image.imageTag);\n\t\t}\n\t\treturn;\n\t}\n\n\tconst source = argv['source'] as string;\n\tconst sourceDir = path.resolve(workspaceRoot, source);\n\tconst name =\n\t\t(argv['name'] as string | undefined) ??\n\t\t(await detectExtensionName(sourceDir));\n\tconst configArgs = splitShellWords((argv['config-args'] as string) || '');\n\tconst extraFilesSpecs = (argv['extra-files'] as string[]).map(\n\t\tparseExtraFilesSpec\n\t);\n\tconst outDir = path.resolve(workspaceRoot, argv['out'] as string);\n\tconst extraFiles = await stageExtraFilesIntoOutDir(\n\t\textraFilesSpecs,\n\t\toutDir,\n\t\tworkspaceRoot\n\t);\n\n\tconst result = await compileExtensionMatrix({\n\t\tworkspaceRoot,\n\t\tsourceDir,\n\t\toutDir: argv['out'] as string,\n\t\tname,\n\t\tphpVersions,\n\t\textraCflags: argv['extra-cflags'] as string | undefined,\n\t\textraLdflags: argv['extra-ldflags'] as string | undefined,\n\t\tconfigArgs,\n\t\toptimize: argv['optimize'] as string,\n\t\tjobs: argv['jobs'] as number | undefined,\n\t\textraFiles,\n\t});\n\n\tconsole.log(`Wrote ${result.artifacts.length} artifacts.`);\n\tconsole.log(`Wrote ${result.manifestPath}.`);\n}\n\nexport async function parseCliArgs(args: string[]) {\n\treturn await yargs(normalizeDashPrefixedOptionValues(args))\n\t\t.scriptName('@php-wasm/compile-extension')\n\t\t.usage('Usage: $0 [--source <dir> | --prepare-image] [options]')\n\t\t.options({\n\t\t\tsource: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extension source directory containing config.m4',\n\t\t\t},\n\t\t\t'prepare-image': {\n\t\t\t\ttype: 'boolean',\n\t\t\t\tdescription:\n\t\t\t\t\t'Build the Docker images for the requested PHP versions and exit without compiling an extension source directory.',\n\t\t\t},\n\t\t\tname: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extension name. Defaults to parsing config.m4.',\n\t\t\t},\n\t\t\t'php-versions': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: SupportedExtensionPHPVersions.join(','),\n\t\t\t\tdescription: 'Comma-separated PHP major.minor versions.',\n\t\t\t},\n\t\t\tout: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: './dist',\n\t\t\t\tdescription: 'Output directory.',\n\t\t\t},\n\t\t\t'extra-cflags': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extra CFLAGS appended to the side-module build.',\n\t\t\t},\n\t\t\t'extra-ldflags': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdescription: 'Extra LDFLAGS appended to the side-module build.',\n\t\t\t},\n\t\t\t'config-args': {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: '',\n\t\t\t\tdescription:\n\t\t\t\t\t'Extra ./configure arguments, parsed as shell words.',\n\t\t\t},\n\t\t\toptimize: {\n\t\t\t\ttype: 'string',\n\t\t\t\tdefault: '2',\n\t\t\t\tdescription: 'Optimization level passed as -O<level>.',\n\t\t\t},\n\t\t\tjobs: {\n\t\t\t\ttype: 'number',\n\t\t\t\tdescription: 'Maximum concurrent docker builds.',\n\t\t\t},\n\t\t\t'extra-files': {\n\t\t\t\ttype: 'string',\n\t\t\t\tarray: true,\n\t\t\t\tdefault: [] as string[],\n\t\t\t\tdescription:\n\t\t\t\t\t'Stage a host directory under an absolute VFS root. Format: <hostDir>:<vfsRoot>. Files are copied next to the manifest and recorded in extraFiles.',\n\t\t\t},\n\t\t})\n\t\t.conflicts('source', 'prepare-image')\n\t\t.check(validateCliMode)\n\t\t.exitProcess(false)\n\t\t.strict()\n\t\t.help()\n\t\t.parse();\n}\n\nif (isCliEntrypoint(import.meta.url)) {\n\tmain().catch((error) => {\n\t\tconsole.error(error instanceof Error ? error.message : error);\n\t\tprocess.exit(1);\n\t});\n}\n\nexport function normalizeDashPrefixedOptionValues(args: string[]): string[] {\n\tconst normalized: string[] = [];\n\tfor (let i = 0; i < args.length; i++) {\n\t\tconst arg = args[i];\n\t\tif (\n\t\t\tOptionsWithDashPrefixedValues.has(arg) &&\n\t\t\ti + 1 < args.length &&\n\t\t\t!args[i + 1].startsWith(`${arg}=`)\n\t\t) {\n\t\t\tnormalized.push(`${arg}=${args[i + 1]}`);\n\t\t\ti++;\n\t\t\tcontinue;\n\t\t}\n\t\tnormalized.push(arg);\n\t}\n\treturn normalized;\n}\n\nexport function validateCliMode(argv: {\n\tsource?: unknown;\n\t'prepare-image'?: unknown;\n\tprepareImage?: unknown;\n\thelp?: unknown;\n}): true {\n\tif (argv.help) {\n\t\treturn true;\n\t}\n\tconst hasSource = typeof argv.source === 'string' && argv.source.length > 0;\n\tconst prepareImage = Boolean(argv['prepare-image'] ?? argv.prepareImage);\n\n\tif (hasSource && prepareImage) {\n\t\tthrow new Error('--source and --prepare-image cannot be used together.');\n\t}\n\tif (!hasSource && !prepareImage) {\n\t\tthrow new Error('--source is required unless --prepare-image is set.');\n\t}\n\n\treturn true;\n}\n\nfunction parseCsv(value: string, name: string): string[] {\n\tconst values = value\n\t\t.split(',')\n\t\t.map((entry) => entry.trim())\n\t\t.filter(Boolean);\n\tif (values.length === 0) {\n\t\tthrow new Error(`--${name} must contain at least one value.`);\n\t}\n\treturn values;\n}\n\nexport function splitShellWords(value: string): string[] {\n\tconst words: string[] = [];\n\tlet current = '';\n\tlet quote: '\"' | \"'\" | null = null;\n\tlet escaping = false;\n\n\tfor (const character of value) {\n\t\tif (escaping) {\n\t\t\tcurrent += character;\n\t\t\tescaping = false;\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\\\\') {\n\t\t\tescaping = true;\n\t\t\tcontinue;\n\t\t}\n\t\tif (quote) {\n\t\t\tif (character === quote) {\n\t\t\t\tquote = null;\n\t\t\t} else {\n\t\t\t\tcurrent += character;\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === '\"' || character === \"'\") {\n\t\t\tquote = character;\n\t\t\tcontinue;\n\t\t}\n\t\tif (/\\s/.test(character)) {\n\t\t\tif (current.length > 0) {\n\t\t\t\twords.push(current);\n\t\t\t\tcurrent = '';\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tcurrent += character;\n\t}\n\n\tif (escaping) {\n\t\tcurrent += '\\\\';\n\t}\n\tif (quote) {\n\t\tthrow new Error('Unterminated quote in --config-args.');\n\t}\n\tif (current.length > 0) {\n\t\twords.push(current);\n\t}\n\treturn words;\n}\n\nfunction findWorkspaceRoot(startDirectory: string): string {\n\tlet directory = path.resolve(startDirectory);\n\twhile (directory !== path.dirname(directory)) {\n\t\tif (\n\t\t\texistsSync(\n\t\t\t\tpath.join(\n\t\t\t\t\tdirectory,\n\t\t\t\t\t'packages/php-wasm/compile-extension/package.json'\n\t\t\t\t)\n\t\t\t) &&\n\t\t\texistsSync(path.join(directory, 'nx.json'))\n\t\t) {\n\t\t\treturn directory;\n\t\t}\n\t\tdirectory = path.dirname(directory);\n\t}\n\treturn process.cwd();\n}\n\nfunction isCliEntrypoint(metaUrl: string): boolean {\n\tconst entrypoint = process.argv[1];\n\tif (!entrypoint) {\n\t\treturn false;\n\t}\n\ttry {\n\t\treturn (\n\t\t\trealpathSync(entrypoint) === realpathSync(fileURLToPath(metaUrl))\n\t\t);\n\t} catch {\n\t\treturn path.resolve(entrypoint) === fileURLToPath(metaUrl);\n\t}\n}\n"],"file":"cli.js"}
package/compile.d.ts CHANGED
@@ -14,6 +14,18 @@ export interface CompileExtensionOptions {
14
14
  /** Sidecar files to record at the manifest level. */
15
15
  extraFiles?: ExtensionManifestExtraFiles;
16
16
  }
17
+ export interface PrepareExtensionBuildImagesOptions {
18
+ workspaceRoot: string;
19
+ phpVersions: string[];
20
+ jobs?: number;
21
+ }
22
+ export declare function prepareExtensionBuildImages(options: PrepareExtensionBuildImagesOptions): Promise<{
23
+ images: {
24
+ phpVersion: string;
25
+ asyncMode: "jspi";
26
+ imageTag: string;
27
+ }[];
28
+ }>;
17
29
  export declare function compileExtensionMatrix(options: CompileExtensionOptions): Promise<{
18
30
  manifestPath: string;
19
31
  artifacts: {
@@ -0,0 +1,30 @@
1
+ export declare const PlaygroundRepositoryUrl = "https://github.com/WordPress/wordpress-playground.git";
2
+ export declare const DockerAssetPaths: string[];
3
+ export interface EnsureDockerAssetsOptions {
4
+ workspaceRoot: string;
5
+ packageRoot: string;
6
+ cacheRoot?: string;
7
+ fetchDockerAssets?: typeof fetchDockerAssets;
8
+ }
9
+ export interface FetchDockerAssetsOptions {
10
+ ref: string;
11
+ cacheRoot: string;
12
+ }
13
+ export declare function ensureDockerAssets({ workspaceRoot, packageRoot, cacheRoot, fetchDockerAssets: fetchDockerAssetsOption, }: EnsureDockerAssetsOptions): Promise<string>;
14
+ export declare function fetchDockerAssets({ ref, cacheRoot, }: FetchDockerAssetsOptions): Promise<string>;
15
+ export declare function isPhpWasmDockerContext(phpWasmRoot: string): boolean;
16
+ export declare function publishFetchedDockerAssets({ tempDir, cacheDir, phpWasmRoot, }: {
17
+ tempDir: string;
18
+ cacheDir: string;
19
+ phpWasmRoot: string;
20
+ }): Promise<void>;
21
+ export declare function resolveDockerAssetsRef({ workspaceRoot, packageRoot, }: {
22
+ workspaceRoot: string;
23
+ packageRoot: string;
24
+ }): string;
25
+ export declare function isPlaygroundWorkspace(workspaceRoot: string): boolean;
26
+ export declare function getDockerAssetsCacheRoot(): string;
27
+ export declare function readDockerAssetSource(phpWasmRoot: string): Promise<{
28
+ repository: string;
29
+ ref: string;
30
+ } | undefined>;
package/docker.d.ts CHANGED
@@ -1,8 +1,10 @@
1
+ import { type EnsureDockerAssetsOptions } from './docker-assets';
1
2
  import type { AsyncMode } from './manifest';
2
3
  export interface DockerBuildContext {
3
4
  workspaceRoot: string;
4
5
  phpWasmRoot: string;
5
6
  compileRoot: string;
7
+ compileExtensionRoot: string;
6
8
  }
7
9
  export interface DockerImageOptions extends DockerBuildContext {
8
10
  phpVersion: string;
@@ -19,7 +21,12 @@ export interface DockerRunOptions extends DockerImageOptions {
19
21
  extraLdflags?: string;
20
22
  configArgs: string[];
21
23
  }
22
- export declare function createDockerContext(workspaceRoot: string): DockerBuildContext;
24
+ export interface CreateDockerContextOptions {
25
+ packageRoot?: string;
26
+ cacheRoot?: string;
27
+ fetchDockerAssets?: EnsureDockerAssetsOptions['fetchDockerAssets'];
28
+ }
29
+ export declare function createDockerContext(workspaceRoot: string, options?: CreateDockerContextOptions): Promise<DockerBuildContext>;
23
30
  export declare function assertDockerIsAvailable(): Promise<void>;
24
31
  export declare function buildBaseImage(context: DockerBuildContext): Promise<void>;
25
32
  export declare function buildExtensionImage(options: DockerImageOptions): Promise<string>;
@@ -0,0 +1,18 @@
1
+ /// <reference types="node" />
2
+ /**
3
+ * Sparse-fetches blobs from a Git repository using the same protocol shape as
4
+ * https://github.com/adamziel/git-sparse-checkout-in-js, with isomorphic-git
5
+ * handling ref discovery, pack indexing, and object reads.
6
+ */
7
+ export declare function sparseCheckoutFiles({ repoUrl, ref, paths, outDir, workDir, }: {
8
+ repoUrl: string;
9
+ ref: string;
10
+ paths: string[];
11
+ outDir: string;
12
+ workDir: string;
13
+ }): Promise<string[]>;
14
+ export declare function pathSegmentMatchesPattern(segment: string, pattern: string): boolean;
15
+ export declare function createTreeFetchRequest(commitHash: string): Buffer;
16
+ export declare function parseUploadPackResponse(response: Buffer): Buffer;
17
+ export declare function stableHash(value: string): string;
18
+ export declare function readJsonFile<T>(filename: string): Promise<T>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@php-wasm/compile-extension",
3
- "version": "3.1.26",
3
+ "version": "3.1.28",
4
4
  "description": "Build PHP.wasm extension side modules across PHP versions",
5
5
  "repository": {
6
6
  "type": "git",
@@ -26,18 +26,19 @@
26
26
  "fast-xml-parser": "^5.5.1",
27
27
  "fs-ext-extra-prebuilt": "2.2.7",
28
28
  "ini": "4.1.2",
29
+ "isomorphic-git": "1.37.6",
29
30
  "jsonc-parser": "3.3.1",
30
31
  "wasm-feature-detect": "1.8.0",
31
32
  "ws": "8.18.0",
32
33
  "yargs": "17.7.2",
33
- "@php-wasm/node": "3.1.26",
34
- "@php-wasm/universal": "3.1.26"
34
+ "@php-wasm/node": "3.1.28",
35
+ "@php-wasm/universal": "3.1.28"
35
36
  },
36
37
  "engines": {
37
38
  "node": ">=20.10.0",
38
39
  "npm": ">=10.2.3"
39
40
  },
40
- "gitHead": "6acfccb8e79f4e664429e3f729f04dbf2ff55303",
41
+ "gitHead": "1f7287114a99a7560576b49108c2af09402ccb9b",
41
42
  "packageManager": "npm@10.9.2",
42
43
  "overrides": {
43
44
  "rollup": "^4.34.6",
package/LICENSE DELETED
@@ -1,339 +0,0 @@
1
- GNU GENERAL PUBLIC LICENSE
2
- Version 2, June 1991
3
-
4
- Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
5
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
6
- Everyone is permitted to copy and distribute verbatim copies
7
- of this license document, but changing it is not allowed.
8
-
9
- Preamble
10
-
11
- The licenses for most software are designed to take away your
12
- freedom to share and change it. By contrast, the GNU General Public
13
- License is intended to guarantee your freedom to share and change free
14
- software--to make sure the software is free for all its users. This
15
- General Public License applies to most of the Free Software
16
- Foundation's software and to any other program whose authors commit to
17
- using it. (Some other Free Software Foundation software is covered by
18
- the GNU Lesser General Public License instead.) You can apply it to
19
- your programs, too.
20
-
21
- When we speak of free software, we are referring to freedom, not
22
- price. Our General Public Licenses are designed to make sure that you
23
- have the freedom to distribute copies of free software (and charge for
24
- this service if you wish), that you receive source code or can get it
25
- if you want it, that you can change the software or use pieces of it
26
- in new free programs; and that you know you can do these things.
27
-
28
- To protect your rights, we need to make restrictions that forbid
29
- anyone to deny you these rights or to ask you to surrender the rights.
30
- These restrictions translate to certain responsibilities for you if you
31
- distribute copies of the software, or if you modify it.
32
-
33
- For example, if you distribute copies of such a program, whether
34
- gratis or for a fee, you must give the recipients all the rights that
35
- you have. You must make sure that they, too, receive or can get the
36
- source code. And you must show them these terms so they know their
37
- rights.
38
-
39
- We protect your rights with two steps: (1) copyright the software, and
40
- (2) offer you this license which gives you legal permission to copy,
41
- distribute and/or modify the software.
42
-
43
- Also, for each author's protection and ours, we want to make certain
44
- that everyone understands that there is no warranty for this free
45
- software. If the software is modified by someone else and passed on, we
46
- want its recipients to know that what they have is not the original, so
47
- that any problems introduced by others will not reflect on the original
48
- authors' reputations.
49
-
50
- Finally, any free program is threatened constantly by software
51
- patents. We wish to avoid the danger that redistributors of a free
52
- program will individually obtain patent licenses, in effect making the
53
- program proprietary. To prevent this, we have made it clear that any
54
- patent must be licensed for everyone's free use or not licensed at all.
55
-
56
- The precise terms and conditions for copying, distribution and
57
- modification follow.
58
-
59
- GNU GENERAL PUBLIC LICENSE
60
- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
61
-
62
- 0. This License applies to any program or other work which contains
63
- a notice placed by the copyright holder saying it may be distributed
64
- under the terms of this General Public License. The "Program", below,
65
- refers to any such program or work, and a "work based on the Program"
66
- means either the Program or any derivative work under copyright law:
67
- that is to say, a work containing the Program or a portion of it,
68
- either verbatim or with modifications and/or translated into another
69
- language. (Hereinafter, translation is included without limitation in
70
- the term "modification".) Each licensee is addressed as "you".
71
-
72
- Activities other than copying, distribution and modification are not
73
- covered by this License; they are outside its scope. The act of
74
- running the Program is not restricted, and the output from the Program
75
- is covered only if its contents constitute a work based on the
76
- Program (independent of having been made by running the Program).
77
- Whether that is true depends on what the Program does.
78
-
79
- 1. You may copy and distribute verbatim copies of the Program's
80
- source code as you receive it, in any medium, provided that you
81
- conspicuously and appropriately publish on each copy an appropriate
82
- copyright notice and disclaimer of warranty; keep intact all the
83
- notices that refer to this License and to the absence of any warranty;
84
- and give any other recipients of the Program a copy of this License
85
- along with the Program.
86
-
87
- You may charge a fee for the physical act of transferring a copy, and
88
- you may at your option offer warranty protection in exchange for a fee.
89
-
90
- 2. You may modify your copy or copies of the Program or any portion
91
- of it, thus forming a work based on the Program, and copy and
92
- distribute such modifications or work under the terms of Section 1
93
- above, provided that you also meet all of these conditions:
94
-
95
- a) You must cause the modified files to carry prominent notices
96
- stating that you changed the files and the date of any change.
97
-
98
- b) You must cause any work that you distribute or publish, that in
99
- whole or in part contains or is derived from the Program or any
100
- part thereof, to be licensed as a whole at no charge to all third
101
- parties under the terms of this License.
102
-
103
- c) If the modified program normally reads commands interactively
104
- when run, you must cause it, when started running for such
105
- interactive use in the most ordinary way, to print or display an
106
- announcement including an appropriate copyright notice and a
107
- notice that there is no warranty (or else, saying that you provide
108
- a warranty) and that users may redistribute the program under
109
- these conditions, and telling the user how to view a copy of this
110
- License. (Exception: if the Program itself is interactive but
111
- does not normally print such an announcement, your work based on
112
- the Program is not required to print an announcement.)
113
-
114
- These requirements apply to the modified work as a whole. If
115
- identifiable sections of that work are not derived from the Program,
116
- and can be reasonably considered independent and separate works in
117
- themselves, then this License, and its terms, do not apply to those
118
- sections when you distribute them as separate works. But when you
119
- distribute the same sections as part of a whole which is a work based
120
- on the Program, the distribution of the whole must be on the terms of
121
- this License, whose permissions for other licensees extend to the
122
- entire whole, and thus to each and every part regardless of who wrote it.
123
-
124
- Thus, it is not the intent of this section to claim rights or contest
125
- your rights to work written entirely by you; rather, the intent is to
126
- exercise the right to control the distribution of derivative or
127
- collective works based on the Program.
128
-
129
- In addition, mere aggregation of another work not based on the Program
130
- with the Program (or with a work based on the Program) on a volume of
131
- a storage or distribution medium does not bring the other work under
132
- the scope of this License.
133
-
134
- 3. You may copy and distribute the Program (or a work based on it,
135
- under Section 2) in object code or executable form under the terms of
136
- Sections 1 and 2 above provided that you also do one of the following:
137
-
138
- a) Accompany it with the complete corresponding machine-readable
139
- source code, which must be distributed under the terms of Sections
140
- 1 and 2 above on a medium customarily used for software interchange; or,
141
-
142
- b) Accompany it with a written offer, valid for at least three
143
- years, to give any third party, for a charge no more than your
144
- cost of physically performing source distribution, a complete
145
- machine-readable copy of the corresponding source code, to be
146
- distributed under the terms of Sections 1 and 2 above on a medium
147
- customarily used for software interchange; or,
148
-
149
- c) Accompany it with the information you received as to the offer
150
- to distribute corresponding source code. (This alternative is
151
- allowed only for noncommercial distribution and only if you
152
- received the program in object code or executable form with such
153
- an offer, in accord with Subsection b above.)
154
-
155
- The source code for a work means the preferred form of the work for
156
- making modifications to it. For an executable work, complete source
157
- code means all the source code for all modules it contains, plus any
158
- associated interface definition files, plus the scripts used to
159
- control compilation and installation of the executable. However, as a
160
- special exception, the source code distributed need not include
161
- anything that is normally distributed (in either source or binary
162
- form) with the major components (compiler, kernel, and so on) of the
163
- operating system on which the executable runs, unless that component
164
- itself accompanies the executable.
165
-
166
- If distribution of executable or object code is made by offering
167
- access to copy from a designated place, then offering equivalent
168
- access to copy the source code from the same place counts as
169
- distribution of the source code, even though third parties are not
170
- compelled to copy the source along with the object code.
171
-
172
- 4. You may not copy, modify, sublicense, or distribute the Program
173
- except as expressly provided under this License. Any attempt
174
- otherwise to copy, modify, sublicense or distribute the Program is
175
- void, and will automatically terminate your rights under this License.
176
- However, parties who have received copies, or rights, from you under
177
- this License will not have their licenses terminated so long as such
178
- parties remain in full compliance.
179
-
180
- 5. You are not required to accept this License, since you have not
181
- signed it. However, nothing else grants you permission to modify or
182
- distribute the Program or its derivative works. These actions are
183
- prohibited by law if you do not accept this License. Therefore, by
184
- modifying or distributing the Program (or any work based on the
185
- Program), you indicate your acceptance of this License to do so, and
186
- all its terms and conditions for copying, distributing or modifying
187
- the Program or works based on it.
188
-
189
- 6. Each time you redistribute the Program (or any work based on the
190
- Program), the recipient automatically receives a license from the
191
- original licensor to copy, distribute or modify the Program subject to
192
- these terms and conditions. You may not impose any further
193
- restrictions on the recipients' exercise of the rights granted herein.
194
- You are not responsible for enforcing compliance by third parties to
195
- this License.
196
-
197
- 7. If, as a consequence of a court judgment or allegation of patent
198
- infringement or for any other reason (not limited to patent issues),
199
- conditions are imposed on you (whether by court order, agreement or
200
- otherwise) that contradict the conditions of this License, they do not
201
- excuse you from the conditions of this License. If you cannot
202
- distribute so as to satisfy simultaneously your obligations under this
203
- License and any other pertinent obligations, then as a consequence you
204
- may not distribute the Program at all. For example, if a patent
205
- license would not permit royalty-free redistribution of the Program by
206
- all those who receive copies directly or indirectly through you, then
207
- the only way you could satisfy both it and this License would be to
208
- refrain entirely from distribution of the Program.
209
-
210
- If any portion of this section is held invalid or unenforceable under
211
- any particular circumstance, the balance of the section is intended to
212
- apply and the section as a whole is intended to apply in other
213
- circumstances.
214
-
215
- It is not the purpose of this section to induce you to infringe any
216
- patents or other property right claims or to contest validity of any
217
- such claims; this section has the sole purpose of protecting the
218
- integrity of the free software distribution system, which is
219
- implemented by public license practices. Many people have made
220
- generous contributions to the wide range of software distributed
221
- through that system in reliance on consistent application of that
222
- system; it is up to the author/donor to decide if he or she is willing
223
- to distribute software through any other system and a licensee cannot
224
- impose that choice.
225
-
226
- This section is intended to make thoroughly clear what is believed to
227
- be a consequence of the rest of this License.
228
-
229
- 8. If the distribution and/or use of the Program is restricted in
230
- certain countries either by patents or by copyrighted interfaces, the
231
- original copyright holder who places the Program under this License
232
- may add an explicit geographical distribution limitation excluding
233
- those countries, so that distribution is permitted only in or among
234
- countries not thus excluded. In such case, this License incorporates
235
- the limitation as if written in the body of this License.
236
-
237
- 9. The Free Software Foundation may publish revised and/or new versions
238
- of the General Public License from time to time. Such new versions will
239
- be similar in spirit to the present version, but may differ in detail to
240
- address new problems or concerns.
241
-
242
- Each version is given a distinguishing version number. If the Program
243
- specifies a version number of this License which applies to it and "any
244
- later version", you have the option of following the terms and conditions
245
- either of that version or of any later version published by the Free
246
- Software Foundation. If the Program does not specify a version number of
247
- this License, you may choose any version ever published by the Free Software
248
- Foundation.
249
-
250
- 10. If you wish to incorporate parts of the Program into other free
251
- programs whose distribution conditions are different, write to the author
252
- to ask for permission. For software which is copyrighted by the Free
253
- Software Foundation, write to the Free Software Foundation; we sometimes
254
- make exceptions for this. Our decision will be guided by the two goals
255
- of preserving the free status of all derivatives of our free software and
256
- of promoting the sharing and reuse of software generally.
257
-
258
- NO WARRANTY
259
-
260
- 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
261
- FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
262
- OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
263
- PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
264
- OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
265
- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
266
- TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
267
- PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
268
- REPAIR OR CORRECTION.
269
-
270
- 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
271
- WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
272
- REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
273
- INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
274
- OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
275
- TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
276
- YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
277
- PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
278
- POSSIBILITY OF SUCH DAMAGES.
279
-
280
- END OF TERMS AND CONDITIONS
281
-
282
- How to Apply These Terms to Your New Programs
283
-
284
- If you develop a new program, and you want it to be of the greatest
285
- possible use to the public, the best way to achieve this is to make it
286
- free software which everyone can redistribute and change under these terms.
287
-
288
- To do so, attach the following notices to the program. It is safest
289
- to attach them to the start of each source file to most effectively
290
- convey the exclusion of warranty; and each file should have at least
291
- the "copyright" line and a pointer to where the full notice is found.
292
-
293
- <one line to give the program's name and a brief idea of what it does.>
294
- Copyright (C) <year> <name of author>
295
-
296
- This program is free software; you can redistribute it and/or modify
297
- it under the terms of the GNU General Public License as published by
298
- the Free Software Foundation; either version 2 of the License, or
299
- (at your option) any later version.
300
-
301
- This program is distributed in the hope that it will be useful,
302
- but WITHOUT ANY WARRANTY; without even the implied warranty of
303
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
304
- GNU General Public License for more details.
305
-
306
- You should have received a copy of the GNU General Public License along
307
- with this program; if not, write to the Free Software Foundation, Inc.,
308
- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
309
-
310
- Also add information on how to contact you by electronic and paper mail.
311
-
312
- If the program is interactive, make it output a short notice like this
313
- when it starts in an interactive mode:
314
-
315
- Gnomovision version 69, Copyright (C) year name of author
316
- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
317
- This is free software, and you are welcome to redistribute it
318
- under certain conditions; type `show c' for details.
319
-
320
- The hypothetical commands `show w' and `show c' should show the appropriate
321
- parts of the General Public License. Of course, the commands you use may
322
- be called something other than `show w' and `show c'; they could even be
323
- mouse-clicks or menu items--whatever suits your program.
324
-
325
- You should also get your employer (if you work as a programmer) or your
326
- school, if any, to sign a "copyright disclaimer" for the program, if
327
- necessary. Here is a sample; alter the names:
328
-
329
- Yoyodyne, Inc., hereby disclaims all copyright interest in the program
330
- `Gnomovision' (which makes passes at compilers) written by James Hacker.
331
-
332
- <signature of Ty Coon>, 1 April 1989
333
- Ty Coon, President of Vice
334
-
335
- This General Public License does not permit incorporating your program into
336
- proprietary programs. If your program is a subroutine library, you may
337
- consider it more useful to permit linking proprietary applications with the
338
- library. If this is what you want to do, use the GNU Lesser General
339
- Public License instead of this License.
@@ -1,64 +0,0 @@
1
- FROM playground-php-wasm:base
2
-
3
- ARG PHP_VERSION
4
- ARG JSPI="no"
5
-
6
- RUN apt-get update && apt-get install -y --no-install-recommends \
7
- bison \
8
- php-cli
9
-
10
- RUN git clone https://github.com/php/php-src.git /root/php-src \
11
- --branch php-$PHP_VERSION \
12
- --single-branch \
13
- --depth 1
14
-
15
- RUN cd /root/php-src && ./buildconf --force
16
-
17
- COPY ./compile/php/php*.patch /root/
18
- RUN cd /root && git apply --no-index /root/php${PHP_VERSION:0:3}*.patch -v
19
-
20
- RUN source /root/emsdk/emsdk_env.sh && \
21
- cd /root/php-src && \
22
- emconfigure ./configure \
23
- --disable-fiber-asm \
24
- --enable-embed \
25
- --disable-cgi \
26
- --disable-opcache-jit \
27
- --disable-opcache \
28
- --disable-phpdbg \
29
- --without-pcre-jit \
30
- --disable-cli \
31
- --disable-libxml \
32
- --without-libxml \
33
- --disable-dom \
34
- --disable-xml \
35
- --disable-simplexml \
36
- --disable-xmlreader \
37
- --disable-xmlwriter \
38
- --without-sqlite3 \
39
- --without-pdo-sqlite \
40
- --without-iconv
41
-
42
- RUN /root/replace.sh 's/ZEND_USE_ASM_ARITHMETIC 1/ZEND_USE_ASM_ARITHMETIC 0/g' /root/php-src/Zend/zend_operators.h
43
- RUN /root/replace.sh 's/defined\(__GNUC__\)/0/g' /root/php-src/Zend/zend_multiply.h
44
- RUN /root/replace.sh 's/defined\(__GNUC__\)/0/g' /root/php-src/Zend/zend_cpuinfo.c
45
- RUN /root/replace.sh 's/defined\(__clang__\)/0/g' /root/php-src/Zend/zend_cpuinfo.c
46
-
47
- RUN source /root/emsdk/emsdk_env.sh && \
48
- cd /root/php-src && \
49
- emmake make install
50
-
51
- RUN mkdir -p /usr/local/include/php/ext/standard && \
52
- if [ -f /root/php-src/ext/standard/php_smart_string.h ]; then \
53
- cp /root/php-src/ext/standard/*.h /usr/local/include/php/ext/standard/; \
54
- else \
55
- echo '#include "Zend/zend_smart_string.h"' > /usr/local/include/php/ext/standard/php_smart_string.h; \
56
- fi && \
57
- if [ -d /root/php-src/ext/random ]; then \
58
- cp /root/php-src/ext/random/*.h /usr/local/include/php/ext/standard/; \
59
- fi
60
-
61
- COPY ./compile-extension/scripts/build-in-docker.sh /usr/local/bin/build-php-wasm-extension
62
- RUN chmod +x /usr/local/bin/build-php-wasm-extension
63
-
64
- ENTRYPOINT ["/usr/local/bin/build-php-wasm-extension"]
@@ -1,114 +0,0 @@
1
- #!/usr/bin/env bash
2
- set -euo pipefail
3
-
4
- if [ ! -d /src ]; then
5
- echo "Missing /src extension source mount." >&2
6
- exit 1
7
- fi
8
-
9
- if [ -z "${EXTENSION_NAME:-}" ]; then
10
- echo "Missing EXTENSION_NAME." >&2
11
- exit 1
12
- fi
13
-
14
- ASYNC_MODE="${ASYNC_MODE:-jspi}"
15
- OPTIMIZE="${OPTIMIZE:-2}"
16
- ARTIFACT_FILENAME="${ARTIFACT_FILENAME:-${EXTENSION_NAME}-php${PHP_VERSION_SHORT:-unknown}-${ASYNC_MODE}.so}"
17
- MAKE_JOBS="${MAKE_JOBS:-$(nproc)}"
18
- USER_EXTRA_CFLAGS="${EXTRA_CFLAGS:-}"
19
- USER_EXTRA_LDFLAGS="${EXTRA_LDFLAGS:-}"
20
- unset EXTRA_CFLAGS EXTRA_LDFLAGS
21
-
22
- rm -rf /build
23
- mkdir -p /build /out
24
- cp -R /src/. /build/
25
- cd /build
26
-
27
- phpize .
28
- source /root/emsdk/emsdk_env.sh
29
- export EMSDK_SYSROOT="${EMSDK_SYSROOT:-${EMSDK}/upstream/emscripten/cache/sysroot}"
30
-
31
- BASE_CFLAGS="-DZEND_ENABLE_ZVAL_LONG64 -D__x86_64__ -fPIC -O${OPTIMIZE}"
32
- BASE_LDFLAGS="-sSIDE_MODULE=1 -sWASM_BIGINT -fPIC -O${OPTIMIZE}"
33
-
34
- if [ "$ASYNC_MODE" != "jspi" ]; then
35
- echo "Unsupported ASYNC_MODE: ${ASYNC_MODE}." >&2
36
- echo "Custom extensions can only be built for JSPI runtimes." >&2
37
- exit 1
38
- fi
39
- ASYNC_FLAGS="-sSUPPORT_LONGJMP=wasm -fwasm-exceptions -sJSPI"
40
-
41
- EXTRA_LINK_FLAGS=""
42
- EXTRA_STATIC_ARCHIVES=""
43
- for flag in $USER_EXTRA_LDFLAGS; do
44
- if [[ "$flag" == *.a ]]; then
45
- EXTRA_STATIC_ARCHIVES="${EXTRA_STATIC_ARCHIVES} ${flag}"
46
- else
47
- EXTRA_LINK_FLAGS="${EXTRA_LINK_FLAGS} ${flag}"
48
- fi
49
- done
50
-
51
- export CFLAGS="${BASE_CFLAGS} ${USER_EXTRA_CFLAGS}"
52
- export CXXFLAGS="${BASE_CFLAGS} ${USER_EXTRA_CFLAGS}"
53
- export BINDGEN_EXTRA_CLANG_ARGS="--target=wasm32-unknown-emscripten --sysroot=${EMSDK_SYSROOT} -DZEND_ENABLE_ZVAL_LONG64 -D__x86_64__ ${BINDGEN_EXTRA_CLANG_ARGS:-}"
54
- export CFLAGS_wasm32_unknown_emscripten="-fPIC ${CFLAGS_wasm32_unknown_emscripten:-}"
55
- export CXXFLAGS_wasm32_unknown_emscripten="-fPIC ${CXXFLAGS_wasm32_unknown_emscripten:-}"
56
- export CC_wasm32_unknown_emscripten="${CC_wasm32_unknown_emscripten:-emcc}"
57
- export CXX_wasm32_unknown_emscripten="${CXX_wasm32_unknown_emscripten:-em++}"
58
- export AR_wasm32_unknown_emscripten="${AR_wasm32_unknown_emscripten:-emar}"
59
- export RANLIB_wasm32_unknown_emscripten="${RANLIB_wasm32_unknown_emscripten:-emranlib}"
60
- CONFIGURE_LDFLAGS="${BASE_LDFLAGS} ${ASYNC_FLAGS}"
61
- BUILD_LDFLAGS="${CONFIGURE_LDFLAGS} ${EXTRA_LINK_FLAGS}"
62
- export LDFLAGS="${CONFIGURE_LDFLAGS}"
63
- # The libtool patch below injects EMCC_FLAGS into the final archive command.
64
- # Keep dependency archives out of LDFLAGS so libtool does not drop or duplicate them.
65
- export EMCC_FLAGS="${BUILD_LDFLAGS}"
66
- export EMCC_STATIC_ARCHIVES="${EXTRA_STATIC_ARCHIVES}"
67
-
68
- configure_args=("--host=i386-unknown-freebsd" "--enable-${EXTENSION_NAME}" "--disable-static" "--enable-shared")
69
- config_args_count="${CONFIG_ARGS_COUNT:-0}"
70
- for ((i = 0; i < config_args_count; i++)); do
71
- arg_name="CONFIG_ARG_${i}"
72
- configure_args+=("${!arg_name}")
73
- done
74
-
75
- if ! emconfigure ./configure "${configure_args[@]}"; then
76
- if [ -f config.log ]; then
77
- cat config.log >&2
78
- fi
79
- exit 1
80
- fi
81
-
82
- if [ -f libtool ]; then
83
- if [ -n "$EMCC_STATIC_ARCHIVES" ]; then
84
- /root/replace.sh 's|^archive_cmds="\\\$CC|archive_cmds="emcc \\\$EMCC_FLAGS -shared --whole-archive \\\$EMCC_STATIC_ARCHIVES --no-whole-archive|' libtool || true
85
- else
86
- /root/replace.sh 's|^archive_cmds="\\\$CC|archive_cmds="emcc \\\$EMCC_FLAGS|' libtool || true
87
- fi
88
- fi
89
-
90
- emmake make -j"${MAKE_JOBS}"
91
-
92
- module_path="modules/${EXTENSION_NAME}.so"
93
- if [ ! -f "$module_path" ]; then
94
- module_path="$(find modules -maxdepth 1 -name '*.so' -print -quit)"
95
- fi
96
-
97
- if [ -z "$module_path" ] || [ ! -f "$module_path" ]; then
98
- echo "Could not find a built .so under /build/modules." >&2
99
- exit 1
100
- fi
101
-
102
- if [ -x /root/emsdk/upstream/bin/wasm-opt ]; then
103
- /root/emsdk/upstream/bin/wasm-opt -Oz \
104
- --enable-bulk-memory \
105
- --enable-nontrapping-float-to-int \
106
- --enable-sign-ext \
107
- --enable-mutable-globals \
108
- --enable-exception-handling \
109
- "$module_path" \
110
- -o "$module_path"
111
- fi
112
-
113
- mkdir -p /out
114
- cp "$module_path" "/out/${ARTIFACT_FILENAME}"