mirror of
https://github.com/LamGC/wp-asciiplayer.git
synced 2026-11-27 05:05:50 +00:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e1cd87f87d | ||
|
|
487eedf0ba | ||
|
|
92de7f86f4 | ||
|
|
ffff9704e5 | ||
|
|
16d8400d76 | ||
|
|
85e5ffa0ec |
+102
-20
@@ -23,7 +23,7 @@ jobs:
|
||||
matrix:
|
||||
php: ['7.4', '8.3']
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- name: Check syntax and execute PHP regression tests
|
||||
run: |
|
||||
docker run --rm -v "$PWD:/app" -w /app "php:${{ matrix.php }}-cli" sh -ec '
|
||||
@@ -31,7 +31,37 @@ jobs:
|
||||
php tests/php/run.php
|
||||
'
|
||||
|
||||
# Only this job publishes the installable package. No WordPress containers or
|
||||
# downloaded plugins run here, and the artifact is immutable once uploaded.
|
||||
build:
|
||||
name: Build and publish pristine package
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 15
|
||||
outputs:
|
||||
package-artifact-id: ${{ steps.package.outputs.artifact-id }}
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
- run: npm run package
|
||||
- name: Upload pristine installable ZIP
|
||||
id: package
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: wp-asciiplayer-package-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
path: dist/wp-asciiplayer.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
|
||||
wordpress:
|
||||
needs: build
|
||||
name: WordPress ${{ matrix.wordpress }} / PHP ${{ matrix.php }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
@@ -44,15 +74,20 @@ jobs:
|
||||
- wordpress: '6.3'
|
||||
php: '7.4'
|
||||
steps:
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24'
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- run: npm run build
|
||||
- run: npm test
|
||||
- run: npm run package
|
||||
- name: Download the pristine package from this run
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
|
||||
with:
|
||||
artifact-ids: ${{ needs.build.outputs.package-artifact-id }}
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Configure clean WordPress version
|
||||
env:
|
||||
WP_TEST_VERSION: ${{ matrix.wordpress }}
|
||||
@@ -67,30 +102,33 @@ jobs:
|
||||
JS
|
||||
- name: Start real WordPress and install only the packaged plugin
|
||||
run: |
|
||||
mkdir -p .wp-env-uploads
|
||||
npx --no-install wp-env start
|
||||
npx --no-install wp-env run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
|
||||
npx --no-install wp-env run cli wp plugin is-active wp-asciiplayer
|
||||
npx --no-install wp-env run cli wp core version | tee wordpress-version.txt
|
||||
npx --no-install wp-env run cli wp plugin list
|
||||
npx --no-install wp-env run cli wp language core install zh_CN
|
||||
npx --no-install wp-env run cli wp site switch-language en_US
|
||||
npx --no-install wp-env run cli wp user meta update admin locale en_US
|
||||
- name: Install Chromium
|
||||
run: npx --no-install playwright install --with-deps chromium
|
||||
- name: Exercise editor iframe, saved blocks, Pages, posts and legacy shortcodes
|
||||
run: npm run test:e2e
|
||||
- name: Run Plugin Check (advisory until directory review)
|
||||
if: always() && matrix.wordpress == 'latest'
|
||||
continue-on-error: true
|
||||
run: |
|
||||
npx --no-install wp-env run cli wp plugin install plugin-check --activate
|
||||
npx --no-install wp-env run cli wp plugin get plugin-check --field=version | tee plugin-check-version.txt
|
||||
npx --no-install wp-env run cli wp plugin check wp-asciiplayer --require=/var/www/html/wp-content/plugins/plugin-check/cli.php --format=json | tee plugin-check-report.txt
|
||||
env:
|
||||
PLAYWRIGHT_HTML_OUTPUT_DIR: playwright-report/en-US
|
||||
run: npm run test:e2e -- --grep-invert @i18n --output=test-results/en-US
|
||||
- name: Exercise real en_US and zh_CN site and user locale combinations
|
||||
env:
|
||||
PLAYWRIGHT_HTML_OUTPUT_DIR: playwright-report/i18n
|
||||
run: npm run test:e2e -- --grep @i18n --output=test-results/i18n
|
||||
- name: Record WordPress and PHP logs
|
||||
if: always()
|
||||
run: |
|
||||
npx --no-install wp-env logs --watch=false > wordpress-logs.txt 2>&1 || true
|
||||
npx --no-install wp-env run cli sh -c 'test ! -f wp-content/debug.log || cat wp-content/debug.log' > wordpress-debug.txt 2>&1 || true
|
||||
- name: Upload integration evidence and installable ZIP
|
||||
- name: Upload integration evidence
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: wordpress-${{ matrix.wordpress }}-php-${{ matrix.php }}
|
||||
if-no-files-found: warn
|
||||
@@ -98,12 +136,56 @@ jobs:
|
||||
path: |
|
||||
playwright-report/
|
||||
test-results/
|
||||
plugin-check-version.txt
|
||||
plugin-check-report.txt
|
||||
wordpress-version.txt
|
||||
wordpress-logs.txt
|
||||
wordpress-debug.txt
|
||||
dist/wp-asciiplayer.zip
|
||||
- name: Stop WordPress
|
||||
if: always()
|
||||
run: npx --no-install wp-env stop
|
||||
|
||||
# Plugin Check receives its own disposable copy. It cannot replace the package
|
||||
# uploaded by build, and this job never republishes files from dist.
|
||||
plugin-check:
|
||||
name: Plugin Check (advisory)
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 20
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6.5.0
|
||||
with:
|
||||
node-version: '24.18.0'
|
||||
cache: npm
|
||||
- name: Use the documented npm toolchain
|
||||
run: npm install --global [email protected]
|
||||
- run: npm ci
|
||||
- name: Download the pristine package from this run
|
||||
uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0
|
||||
with:
|
||||
artifact-ids: ${{ needs.build.outputs.package-artifact-id }}
|
||||
path: dist
|
||||
merge-multiple: true
|
||||
- name: Start WordPress and install the packaged plugin
|
||||
run: |
|
||||
mkdir -p .wp-env-uploads
|
||||
npx --no-install wp-env start
|
||||
npx --no-install wp-env run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
|
||||
- name: Run Plugin Check (advisory until directory review)
|
||||
continue-on-error: true
|
||||
run: |
|
||||
npx --no-install wp-env run cli wp plugin install plugin-check --activate
|
||||
npx --no-install wp-env run cli wp plugin get plugin-check --field=version | tee plugin-check-version.txt
|
||||
npx --no-install wp-env run cli wp plugin check wp-asciiplayer --require=/var/www/html/wp-content/plugins/plugin-check/cli.php --format=json | tee plugin-check-report.txt
|
||||
- name: Upload Plugin Check evidence only
|
||||
if: always()
|
||||
uses: actions/upload-artifact@b7c566a772e6b6bfb58ed0dc250532a479d7789f # v6.0.0
|
||||
with:
|
||||
name: plugin-check-${{ github.run_id }}-${{ github.run_attempt }}
|
||||
if-no-files-found: warn
|
||||
retention-days: 14
|
||||
path: |
|
||||
plugin-check-version.txt
|
||||
plugin-check-report.txt
|
||||
- name: Stop WordPress
|
||||
if: always()
|
||||
run: npx --no-install wp-env stop
|
||||
|
||||
@@ -54,3 +54,4 @@ dist/
|
||||
/playwright-report/
|
||||
/test-results/
|
||||
/.wp-env/
|
||||
/.wp-env-uploads/
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
"SCRIPT_DEBUG": true
|
||||
},
|
||||
"mappings": {
|
||||
"wp-content/uploads": "./.wp-env-uploads",
|
||||
"wp-content/uploads/asciiplayer-fixtures": "./tests/fixtures",
|
||||
"wp-content/asciiplayer-packages": "./dist"
|
||||
},
|
||||
|
||||
+105
-26
@@ -1,46 +1,125 @@
|
||||
# wp-asciiplayer
|
||||
|
||||
为 WordPress 提供原生 Asciicast Player 区块,可在编辑器内真实播放终端录屏,
|
||||
同时兼容原有 `[asciiplayer]` shortcode。
|
||||
把终端录屏放进 WordPress 文章和页面。添加 **Asciicast Player** 区块,就能一边编辑一边预览录屏;
|
||||
旧文章里的 `[asciiplayer]` shortcode 也可以继续使用。
|
||||
|
||||
## 安装与使用
|
||||
[English documentation](README.md)
|
||||
|
||||
将构建得到的 `wp-asciiplayer.zip` 上传到「插件 → 安装插件 → 上传插件」并启用。
|
||||
GitHub 源码 ZIP 需要先构建,不能直接当发行包安装。构建方法见 [SOURCE.md](SOURCE.md)。
|
||||
要求 WordPress 6.3+、PHP 7.4+;具体测试版本见仓库 CI。
|
||||
## 安装
|
||||
|
||||
插入「Asciicast Player」区块,粘贴录制文件的 HTTP(S) URL,应用后即可在编辑器内播放、
|
||||
暂停和拖动。主题、速度、循环、控制栏、尺寸、起始时间和空闲压缩等选项在区块设置中调整。
|
||||
保存文章或页面后,前台使用同一播放器。重新打开已有区块时点击「Load preview」加载预览;
|
||||
编辑预览不会自动播放,前台自动播放设置仍会保留。
|
||||
需要 **WordPress 6.3+** 和 **PHP 7.4+**。
|
||||
|
||||
URL 必须指向录制文件(例如 `.cast`),不能直接使用分享页面地址。跨域文件需要允许
|
||||
来自你站点的 CORS 请求;HTTPS 页面上的 HTTP 文件可能被浏览器阻止。优先使用同源 HTTPS。
|
||||
本插件不提供远程文件代理、不扩展上传类型,也不创建额外的录屏管理文章类型。
|
||||
1. 在 **插件 → 安装插件 → 上传插件** 中上传构建好的 `wp-asciiplayer.zip`。
|
||||
2. 启用 **Asciicast Player**。
|
||||
|
||||
## 旧文章兼容
|
||||
GitHub 下载的源码 ZIP 需要先构建,不能直接安装,步骤见[构建说明](SOURCE.md)。
|
||||
[仓库 CI](.github/workflows/ci.yml) 列出了测试的环境组合;使用前也请检查与你的主题是否兼容。
|
||||
|
||||
原有 shortcode 继续有效,无须批量修改文章:
|
||||
## 添加录屏
|
||||
|
||||
1. 插入 **Asciicast Player** 区块。
|
||||
2. 粘贴录制文件的 URL,或点击 **选择录制文件(Choose recording)**,从媒体库选择或上传 `.cast` 文件。
|
||||
3. 停止输入约半秒后会自动加载预览。点击 **Apply URL** 可以立即加载,然后就能播放、暂停和拖动进度。
|
||||
4. 在 **Display** 中设置宽度和对齐方式。可以选择预设,也可以填写 `480px`、`65%` 等 CSS 长度。
|
||||
播放器下方可以添加说明文字。
|
||||
5. 在区块设置中调整主题、速度、循环、控制栏、适应方式、起始时间和空闲压缩,然后保存文章或页面。
|
||||
|
||||
重新打开文章时,已有有效 URL 的区块会自动加载录屏。编辑预览不会自动播放,即使你给前台启用了自动播放。
|
||||
空白或无效 URL 不会发起请求。区块插入器里的示例是静态的,也不会请求录制文件。
|
||||
|
||||
### 展示宽度与终端尺寸
|
||||
|
||||
展示宽度决定播放器在页面里占多大空间,并且不会超出可用宽度。
|
||||
调整宽度或使用 `fit: width` 只是缩放画面,不会改变终端的行列数。
|
||||
|
||||
**Columns** 和 **Rows** 留空时,会使用录屏本身的尺寸,并跟随录制中的尺寸变化。
|
||||
需要手动设置时,可以使用区块工具栏或侧栏里的 **Terminal size**,两处设置会同步。
|
||||
点击 **Use recording size** 可以清空手动设置,恢复录屏原有尺寸。
|
||||
|
||||
加载后,空白字段会显示录屏的原始行列数作为提示。换一个 URL 会刷新提示,但保留你手动填写的值。
|
||||
提示只读取同一次预览响应的前 **64 KiB**;读取不到时保留通用占位提示,不猜测尺寸。
|
||||
录制过程中后续的尺寸变化不会改变这组提示。
|
||||
|
||||
播放器自带样式,用来保持终端文字对齐和键盘焦点可见。部分主题可能仍需要调整 CSS。
|
||||
播放操作和录屏隐私说明可以在侧栏的 **帮助(Help)** 面板中找到。
|
||||
|
||||
### 录制文件地址
|
||||
|
||||
URL 要直接指向录制文件,例如 `.cast` 文件,而不是 asciinema 分享页面。
|
||||
其他域名上的文件需要允许来自你站点的 CORS 请求。HTTPS 页面可能无法加载 HTTP 文件,优先使用同站点的 HTTPS 地址。
|
||||
插件不会代理请求或复制远程文件。
|
||||
|
||||
## 旧文章与 shortcode
|
||||
|
||||
旧文章可以继续使用原有 shortcode,不需要批量修改:
|
||||
|
||||
```text
|
||||
[asciiplayer]https://example.org/demo.cast[/asciiplayer]
|
||||
[asciiplayer theme="monokai" speed="1.5" controls="false"]https://example.org/demo.cast[/asciiplayer]
|
||||
[asciiplayer startAt="2" idleTimeLimit="3" style="width: 80%;"]https://example.org/demo.cast[/asciiplayer]
|
||||
```
|
||||
|
||||
布尔值、数值和历史 camelCase 参数会归一化处理;自定义 style 经过 WordPress 安全 CSS 过滤。
|
||||
区块提供 shortcode 转换能力,转换后请检查设置再保存,不会自动重写旧文章。
|
||||
经典编辑器继续使用 shortcode,暂不增加 TinyMCE 自定义界面。
|
||||
布尔值、数值和旧的 camelCase 参数会自动处理。自定义 `style` 会经过 WordPress 的安全 CSS 过滤;
|
||||
不安全的 URL、标记,以及可执行或对象形式的选项不会被接受。
|
||||
|
||||
支持的 shortcode 可以转换成区块,保存前请检查设置。插件不会自动重写旧文章。
|
||||
经典编辑器仍可使用 shortcode,但没有专门的播放器编辑界面。
|
||||
|
||||
## 媒体库上传
|
||||
|
||||
已有 WordPress `upload_files` 权限的用户可以上传 `.cast` 文件。
|
||||
多站点还需要网络管理员允许 `cast` 扩展名。插件不会增加用户的上传权限,也不会另建录屏管理文章类型。
|
||||
|
||||
上传和浏览器播放(包括远程录屏)执行以下资源限制:
|
||||
|
||||
- 接收到的录屏数据最多 **32 MiB**;旧的 v1 格式最多 **2 MiB**。
|
||||
- 最多 **100,000** 个事件或流内行,忽略的行也计入。
|
||||
- 每条 JSONL 行最多 **256 KiB**,最多 **1,000** 个时间标记。
|
||||
- 终端每个方向不超过 **1,000** 列或行,列数 × 行数不超过 **40,000** 个单元格。
|
||||
- 录屏时间轴和支持的时间值最多 **2,147,483,647 毫秒**(约 **24.85 天**)。v1/v3 的相对时间按播放器的顺序以毫秒累加。浏览器播放还要求累计录屏时间除以播放速度后不超过此上限;因此在 **0.01×** 速度下,原始录屏时长最多约 **5.97 小时**。这一保守边界确保原生定时器延迟和输出批处理处于支持的数值范围内。起始时间、空闲时间与时间戳封面选项也会检查。
|
||||
- JSON 容器最多嵌套 **15** 层;v1 最多 **400,000** 个标量/键名与 **100,016** 个容器;每条 JSONL 行最多 **20,000** 个标量/键名。解码前检查,未知元数据与重复键名也计入。
|
||||
- 浏览器请求总时限为 **30 秒**,等待下个响应或数据块的时限为 **10 秒**;编辑器加载播放器资源与录屏合计也限 30 秒。
|
||||
|
||||
单元格限制检查初始尺寸、每次尺寸变化,以及 Columns/Rows 覆盖后的实际尺寸。
|
||||
创建终端前,还会用播放器初始默认的 80×24 尺寸检查覆盖值;单独覆盖一个方向时,也须同时满足初始终端和录屏的预算。
|
||||
录屏头中的零尺寸使用播放器默认值;普通空行、注释和安全的未知事件类型仍兼容。
|
||||
Asciicast v2、v3 使用 JSONL,旧的 v1 在较小的数据上限内仍受支持。
|
||||
站点或服务器更低的上传限制仍然生效。无效录屏会被拒绝,也不会因此开放普通 JSON、HTML 或 SVG 上传。
|
||||
|
||||
这些限制也适用于旧文件和外部托管录屏的播放。此前能加载的超大终端或包含大量时间标记的录屏,
|
||||
可能会显示明确的超限提示。建议拆分或简化录屏,而不是让浏览器处理无限数据。
|
||||
已有文件和文章不会被重写。
|
||||
|
||||
浏览器通过一次请求读取并校验录屏,通过后才交给播放器;不会增加服务器代理或额外元数据请求。
|
||||
超时或取消会停止加载,切换录屏或离开预览会取消旧请求。
|
||||
远程服务器仍须允许 CORS,浏览器的凭据和来源信息规则保持不变。
|
||||
|
||||
## 界面语言
|
||||
|
||||
插件界面包含英文和简体中文(`zh_CN`):
|
||||
|
||||
- 编辑器跟随 **用户 → 个人资料 → 语言**;未单独设置时使用站点语言。
|
||||
- 前台跟随 **设置 → 常规 → 站点语言**。
|
||||
|
||||
翻译文件随 ZIP 附带,可离线使用。英文是默认回退语言,不需要单独的 `en_US` 翻译文件。
|
||||
`zh_TW` 等其他中文地区设置不会自动映射成简体中文。
|
||||
|
||||
录屏中的终端内容和你填写的说明文字不会被翻译。
|
||||
内置播放器自身的播放控件和帮助仍为英文,其文件保持上游原样。
|
||||
|
||||
## 资源与隐私
|
||||
|
||||
播放器 JavaScript、CSS、WebAssembly 全部本地附带,不再请求 jsDelivr,
|
||||
旧 `ap_use_local_resources` 开关不再使用。没有统计追踪或后台远程 API 请求。
|
||||
播放器的 JavaScript、CSS 和 WebAssembly 都在插件内,不会从 jsDelivr 加载。
|
||||
插件没有统计追踪,也不会在后台调用远程 API。旧的 `ap_use_local_resources` 选项不再使用。
|
||||
|
||||
你选择的录制文件会由读者浏览器直接请求;外部文件主机可能收到 IP、浏览器请求信息和
|
||||
依浏览器/站点策略发送的来源信息。应用 URL 或点击加载预览时,编辑器也会发起这类请求。
|
||||
请使用可信主机,发布前检查录屏是否包含终端里的敏感信息。外部主机适用其自身隐私政策。
|
||||
录屏文件会由浏览器直接请求你填写的 URL。外部主机可能收到读者的 IP 地址、浏览器请求信息,
|
||||
以及浏览器和站点设置允许发送的来源信息。编辑预览也会发起同样的请求,包括重新打开已有录屏的文章时。
|
||||
|
||||
## 开发与许可
|
||||
请使用可信主机,发布前检查终端录屏是否含有敏感信息。
|
||||
外部主机适用自己的隐私政策,插件无法让外部录屏变成私有文件。
|
||||
|
||||
[构建与测试说明](SOURCE.md) · [第三方许可证](THIRD-PARTY-NOTICES.md)
|
||||
## 构建与许可
|
||||
|
||||
本插件保持 GPL-3.0-only,播放器及依赖保留各自的兼容许可证。
|
||||
构建、测试和 ZIP 打包步骤见 [SOURCE.md](SOURCE.md)。
|
||||
|
||||
插件使用 GPL-3.0-only。播放器和依赖保留各自的兼容许可证,详见[第三方许可证](THIRD-PARTY-NOTICES.md)。
|
||||
|
||||
@@ -1,66 +1,153 @@
|
||||
# wp-asciiplayer
|
||||
|
||||
An Asciicast Player block for WordPress, with real playback in the editor and
|
||||
backwards-compatible `[asciiplayer]` shortcodes. [中文说明](README-zh.md)
|
||||
Play terminal recordings in WordPress posts and pages. Add an **Asciicast Player**
|
||||
block to preview the recording while you edit, or keep using the `[asciiplayer]`
|
||||
shortcode in existing posts.
|
||||
|
||||
[中文说明](README-zh.md)
|
||||
|
||||
## Install
|
||||
|
||||
Install the built `wp-asciiplayer.zip` through **Plugins → Add New → Upload
|
||||
Plugin**, then activate **Asciicast Player**. A GitHub source ZIP must be built
|
||||
first; it does not contain generated assets. See [SOURCE.md](SOURCE.md).
|
||||
Requires **WordPress 6.3+** and **PHP 7.4+**.
|
||||
|
||||
Requires WordPress 6.3+ and PHP 7.4+. Compatibility must be checked against your
|
||||
site and theme; CI tests the versions listed in `.github/workflows/ci.yml`.
|
||||
1. Upload the built `wp-asciiplayer.zip` through **Plugins → Add New → Upload Plugin**.
|
||||
2. Activate **Asciicast Player**.
|
||||
|
||||
## Block editor
|
||||
A GitHub source ZIP needs to be built before you can install it. See the
|
||||
[build instructions](SOURCE.md). The [CI workflow](.github/workflows/ci.yml)
|
||||
lists the combinations we test; check the plugin with your own theme too.
|
||||
|
||||
1. Insert **Asciicast Player**.
|
||||
2. Paste an HTTP(S) recording-file URL (for example a `.cast` file), then apply it.
|
||||
3. Play, pause and seek in the editor. Change theme, speed, looping, controls,
|
||||
width/fit, start time and idle-time limit from the block settings.
|
||||
4. Save the post or page; the same locally bundled player is used on the front end.
|
||||
## Add a recording
|
||||
|
||||
Existing saved blocks show a **Load preview** action on reopening the editor.
|
||||
This keeps external recordings from loading until you choose to preview them.
|
||||
Preview does not autoplay even when front-end autoplay is enabled.
|
||||
1. Insert an **Asciicast Player** block.
|
||||
2. Paste a recording-file URL, or click **Choose recording** to select or upload a
|
||||
`.cast` file from the Media Library.
|
||||
3. The preview loads about half a second after you stop typing. Click **Apply URL**
|
||||
to load it immediately, then play, pause or seek through the recording.
|
||||
4. Use **Display** to set the width and alignment. You can choose a preset or enter
|
||||
a CSS length such as `480px` or `65%`. Add a caption below the player.
|
||||
5. Adjust the theme, speed, looping, controls, fit, start time and idle-time limit
|
||||
in the block settings, then save your post or page.
|
||||
|
||||
The source must be a recording-file URL, not an asciinema share-page URL.
|
||||
A recording on another origin must allow CORS requests from your WordPress site.
|
||||
HTTP recordings on an HTTPS site may be blocked as mixed content. Use a same-site
|
||||
HTTPS URL when possible. The plugin does not proxy or copy remote files, grant
|
||||
new upload types, or add a recording-management post type.
|
||||
Saved recordings load again when you reopen the editor. Previews do not autoplay,
|
||||
even if you enable autoplay for the published page. Empty or invalid URLs do not
|
||||
start a request. The block inserter uses a static example, so it does not fetch a
|
||||
recording either.
|
||||
|
||||
### Display width and terminal size
|
||||
|
||||
The display width controls how much space the player takes on the page. It stays
|
||||
within the available width. Changing it, or using `fit: width`, scales the picture
|
||||
without changing the terminal's columns and rows.
|
||||
|
||||
Leave **Columns** and **Rows** empty to use the recording's dimensions and resize
|
||||
events. To override them, use **Terminal size** in the block toolbar or sidebar;
|
||||
both controls update the same settings. **Use recording size** clears the overrides.
|
||||
|
||||
After loading, the empty fields show the recording's original dimensions as hints.
|
||||
Changing the URL updates those hints but keeps any values you entered. The hints
|
||||
come from the first 64 KiB of the preview response; if they cannot be read, the
|
||||
fields keep a generic placeholder. Later resize events do not change the hints.
|
||||
|
||||
The player includes styles to keep terminal text aligned and keyboard focus
|
||||
visible. Some themes may still need CSS adjustments. Playback tips and recording
|
||||
privacy information are in the sidebar's **Help** panel.
|
||||
|
||||
### Recording URLs
|
||||
|
||||
Use an HTTP(S) URL that points to the recording file, not an asciinema share page.
|
||||
A file hosted on another domain must allow CORS requests from your site. Browsers
|
||||
may block HTTP recordings on HTTPS pages; a same-site HTTPS URL is the simplest
|
||||
option. The plugin does not proxy or copy remote files.
|
||||
|
||||
## Existing shortcodes
|
||||
|
||||
Old articles remain supported; no content migration is required:
|
||||
Existing posts keep working without a content migration:
|
||||
|
||||
```text
|
||||
[asciiplayer]https://example.org/demo.cast[/asciiplayer]
|
||||
[asciiplayer theme="monokai" speed="1.5" controls="false"]https://example.org/demo.cast[/asciiplayer]
|
||||
[asciiplayer startAt="2" idleTimeLimit="3" style="width: 80%;"]https://example.org/demo.cast[/asciiplayer]
|
||||
```
|
||||
|
||||
Boolean and numeric options are typed, and historical camelCase options are
|
||||
normalized after WordPress lowercases shortcode attribute names. Inline styles
|
||||
are filtered through WordPress safe-CSS handling; unsafe protocols and markup
|
||||
are rejected/escaped. Unsupported executable/object options are not accepted.
|
||||
The Classic Editor continues to support shortcodes; it has no custom visual UI.
|
||||
The block supports a shortcode-to-block transform for supported options. Review
|
||||
converted settings before saving; articles are never rewritten automatically.
|
||||
Boolean, numeric and older camelCase options are handled automatically. Inline
|
||||
styles go through WordPress's safe-CSS filter; unsafe URLs, markup and executable
|
||||
or object-valued options are not accepted.
|
||||
|
||||
## Local resources and privacy
|
||||
You can convert supported shortcodes into blocks. Check the settings before
|
||||
saving; the plugin never rewrites old posts automatically. The Classic Editor
|
||||
supports shortcodes, but has no custom player-editing interface.
|
||||
|
||||
All player JavaScript, CSS, and WebAssembly are included in the plugin. The old
|
||||
`ap_use_local_resources` switch is no longer used, and jsDelivr is not contacted.
|
||||
No analytics or background remote API calls are added.
|
||||
## Media Library uploads
|
||||
|
||||
A recording URL you choose is fetched directly by the visitor's browser. Its host
|
||||
can receive the visitor's IP address, browser request metadata and possibly a
|
||||
referrer, according to browser/site policy. Editor previews have the same effect
|
||||
when you apply a URL or click **Load preview**. Choose a trusted host and review
|
||||
recordings for sensitive terminal output before publishing them. The host's own
|
||||
privacy policy applies; the plugin cannot make an external recording private.
|
||||
You can upload `.cast` files if your account already has WordPress's `upload_files`
|
||||
permission. Multisite networks must also allow the `cast` extension. The plugin
|
||||
does not grant extra upload permissions or add a separate recording-management
|
||||
post type.
|
||||
|
||||
## Development
|
||||
Uploads and browser playback (including remote recordings) enforce these resource limits:
|
||||
|
||||
See [SOURCE.md](SOURCE.md) for locked build and ZIP packaging commands. Source
|
||||
code is GPL-3.0-only. The player and its dependencies retain their own compatible
|
||||
licenses; see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
|
||||
- **32 MiB** of received recording data; **2 MiB** for legacy v1.
|
||||
- **100,000** events or stream lines, including ignored lines.
|
||||
- **256 KiB** per JSONL line and **1,000** marker events.
|
||||
- **1,000** columns or rows per axis, and **40,000** terminal cells (columns × rows).
|
||||
- **2,147,483,647 milliseconds** (about **24.85 days**) for recording timelines and supported time values. Relative v1/v3 intervals are accumulated in milliseconds, matching the player. Browser playback also requires cumulative recording time divided by playback speed to fit this ceiling; at **0.01×**, this permits about **5.97 hours** of source time. This conservative bound keeps native timer delays and output batching within their supported numeric range. Playback start, idle-time and timestamp-poster options are checked too.
|
||||
- At most **15** nested JSON containers, **400,000** scalar/key tokens and **100,016** containers in v1, or **20,000** scalar/key tokens per JSONL line, checked before decoding. Unknown metadata and duplicate keys count too.
|
||||
- Browser requests stop after **30 seconds** total or **10 seconds** without the next response/chunk; the editor also allows 30 seconds for player assets and loading together.
|
||||
|
||||
The cell budget covers initial dimensions and every resize, including effective
|
||||
Columns/Rows overrides. Overrides are also checked against the player's initial
|
||||
80×24 defaults before creating its terminal, so a single-axis override must fit
|
||||
both the initial terminal and the recording. A zero header dimension uses the player's default;
|
||||
ordinary blank/comment lines and safe unknown event types remain compatible.
|
||||
Asciicast v2 and v3 use JSONL; legacy v1 remains supported within its smaller limit.
|
||||
Lower site or server upload limits still apply. Invalid recordings are rejected;
|
||||
this does not enable general JSON, HTML or SVG uploads.
|
||||
|
||||
These limits also apply to older or externally hosted recordings at playback.
|
||||
Very large terminals or marker-heavy recordings that previously loaded may now
|
||||
show a clear limit error. Split or simplify those recordings rather than relying
|
||||
on the browser to handle unlimited data. Existing files and posts are not rewritten.
|
||||
|
||||
The browser reads and validates a single recording request before handing it to
|
||||
the player. There is no server proxy or additional metadata request. A timed-out
|
||||
or canceled load is stopped; switching recordings and leaving a preview cancel
|
||||
its old request. Remote hosts must still allow CORS, and browser credentials and
|
||||
referrer rules are unchanged.
|
||||
|
||||
## Languages
|
||||
|
||||
The plugin's interface includes English and Simplified Chinese (`zh_CN`).
|
||||
|
||||
- In the editor, choose **Users → Profile → Language**, or use the site default.
|
||||
- On public pages, the language follows **Settings → General → Site Language**.
|
||||
|
||||
Translations are included in the ZIP and work offline. English is the fallback;
|
||||
there is no separate `en_US` catalog. Other Chinese locales, including `zh_TW`, are
|
||||
not automatically mapped to Simplified Chinese.
|
||||
|
||||
Recorded terminal output and your captions are unchanged. The bundled player's
|
||||
own playback controls and help remain in English; its files are kept as supplied
|
||||
by the upstream project.
|
||||
|
||||
## Resources and privacy
|
||||
|
||||
The player’s JavaScript, CSS and WebAssembly are bundled locally. The plugin does
|
||||
not contact jsDelivr, add analytics or make background remote API calls. The old
|
||||
`ap_use_local_resources` option is no longer used.
|
||||
|
||||
Recordings are different: visitors' browsers fetch the URL you choose directly.
|
||||
An external host may receive their IP address, browser request details and a
|
||||
referrer, depending on browser and site settings. Editor previews make the same
|
||||
request whenever a valid URL loads, including when you reopen a saved block.
|
||||
|
||||
Use a trusted host and check recordings for sensitive terminal output before
|
||||
publishing. The host's privacy policy applies; the plugin cannot make an external
|
||||
recording private.
|
||||
|
||||
## Build and license
|
||||
|
||||
See [SOURCE.md](SOURCE.md) for build, test and ZIP packaging commands.
|
||||
|
||||
The plugin is GPL-3.0-only. The player and its dependencies keep their own
|
||||
compatible licenses; see [THIRD-PARTY-NOTICES.md](THIRD-PARTY-NOTICES.md).
|
||||
|
||||
@@ -4,12 +4,16 @@ This distribution contains the plugin's PHP and JavaScript source, block metadat
|
||||
build configuration, scripts, and npm lockfile. The development repository is
|
||||
https://github.com/LamGC/wp-asciiplayer .
|
||||
|
||||
Use Node.js 24 (24.15 or later), npm, and the standard `zip` command:
|
||||
Use Node.js 24.18+ (24.x) or 26+, npm 11.16+, and the standard `zip` command:
|
||||
|
||||
npm ci
|
||||
npm run build
|
||||
npm run package
|
||||
|
||||
Node.js 22 and 25 are not supported by the complete development toolchain.
|
||||
The Node requirement is for building/testing only; the plugin still supports
|
||||
WordPress 6.3 and PHP 7.4.
|
||||
|
||||
The installable output is `dist/wp-asciiplayer.zip`. Generated assets are never
|
||||
loaded from a CDN. `scripts/vendor.mjs` copies the pinned official npm
|
||||
`[email protected]` distribution, verified by package-lock integrity, into
|
||||
@@ -33,3 +37,46 @@ Chromium; the repository CI records the exact WordPress version under test and
|
||||
installs the release ZIP into the test site before checking it. Refer to the
|
||||
workflow for setup details. Running a unit test is not a substitute for the
|
||||
WordPress browser integration suite.
|
||||
|
||||
## Security recording regression fixtures
|
||||
|
||||
The full repository contains a test-only corpus in
|
||||
[`tests/fixtures/security`](tests/fixtures/security/README.md). Small `.cast`
|
||||
controls are checked in; fixed-seed, exact-boundary larger recordings are generated
|
||||
only when a test requests them. The manifest records expected acceptance, byte
|
||||
counts and hashes so PHP upload checks and the browser loader exercise identical
|
||||
inputs. The corpus README explains official recorder provenance, format-specific
|
||||
coverage, and the distinction between valid-format over-budget and malformed cases.
|
||||
|
||||
node tests/fixtures/security/generate.mjs --list
|
||||
node tests/fixtures/security/generate.mjs --verify
|
||||
|
||||
Use these fixtures only in isolated local/CI test environments. Do not upload
|
||||
resource-limit probes to a live WordPress site or open unvalidated large recordings
|
||||
in a player. The normal test commands above run the regression assertions; the
|
||||
browser cases use representative bounded samples rather than stressing the host.
|
||||
|
||||
## Translation maintenance
|
||||
|
||||
The English gettext strings are the fallback. Edit `languages/wp-asciiplayer-zh_CN.po`
|
||||
to maintain Simplified Chinese; `npm run i18n` extracts the current static PHP/JS
|
||||
and block-metadata strings into the POT and compiles the MO and WordPress Jed JSON.
|
||||
`npm run i18n:check` fails for missing/fuzzy translations, stale generated files,
|
||||
unsupported plural extraction, and mismatched printf placeholders. Build runs
|
||||
compilation and tests check it reproducibly, without a network service or timestamps.
|
||||
For new strings, run `node scripts/i18n.mjs --pot-only`, merge into the maintained
|
||||
PO with a gettext editor, translate, and run `npm run i18n` again.
|
||||
|
||||
JSON files use WordPress's supported domain-locale-script-handle names for the
|
||||
actual `lamgc-asciiplayer-editor` and `lamgc-asciiplayer-view` handles. The editor
|
||||
bundle has no lazy translated chunks. `wp_set_script_translations` registers both
|
||||
paths after scripts; PHP registers `load_plugin_textdomain` during `init`, before
|
||||
block metadata is translated. The generated assets and all catalogs are packaged.
|
||||
The upstream vendor bundle is byte-for-byte unchanged and its own controls remain
|
||||
English. Runtime JS/CSS versions use build content hashes even though the preview
|
||||
package version stays `1.1.0-dev`.
|
||||
|
||||
References:
|
||||
- https://developer.wordpress.org/reference/functions/wp_set_script_translations/
|
||||
- https://developer.wordpress.org/reference/functions/load_script_textdomain/
|
||||
- https://developer.wordpress.org/reference/functions/load_plugin_textdomain/
|
||||
|
||||
@@ -3,13 +3,14 @@
|
||||
* Plugin Name: Asciicast Player
|
||||
* Plugin URI: https://github.com/LamGC/wp-asciiplayer
|
||||
* Description: Add interactive terminal recordings to posts and pages with a block or shortcode.
|
||||
* Version: 1.1.0
|
||||
* Version: 1.1.0-dev
|
||||
* Requires at least: 6.3
|
||||
* Requires PHP: 7.4
|
||||
* Author: LamGC
|
||||
* Author URI: https://blog.lamgc.moe
|
||||
* License: GPL-3.0-only
|
||||
* License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||
* Domain Path: /languages
|
||||
* Text Domain: wp-asciiplayer
|
||||
*
|
||||
* @package LamGC\Asciiplayer
|
||||
@@ -21,14 +22,20 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
const VERSION = '1.1.0';
|
||||
const VERSION = '1.1.0-dev';
|
||||
const PLUGIN_FILE = __FILE__;
|
||||
const SHORTCODE = 'asciiplayer';
|
||||
|
||||
require_once __DIR__ . '/includes/options.php';
|
||||
require_once __DIR__ . '/includes/render.php';
|
||||
require_once __DIR__ . '/includes/assets.php';
|
||||
require_once __DIR__ . '/includes/uploads.php';
|
||||
|
||||
add_action( 'init', __NAMESPACE__ . '\\register_plugin' );
|
||||
add_action( 'wp_enqueue_scripts', __NAMESPACE__ . '\\enqueue_content_assets' );
|
||||
add_action( 'wp_footer', __NAMESPACE__ . '\\print_late_styles', 5 );
|
||||
|
||||
add_filter( 'upload_mimes', __NAMESPACE__ . '\\allow_cast_upload_mime', 10, 2 );
|
||||
add_filter( 'wp_check_filetype_and_ext', __NAMESPACE__ . '\\check_cast_filetype', 10, 5 );
|
||||
add_filter( 'wp_handle_upload_prefilter', __NAMESPACE__ . '\\validate_cast_upload' );
|
||||
add_filter( 'wp_handle_sideload_prefilter', __NAMESPACE__ . '\\validate_cast_upload' );
|
||||
|
||||
+5
-1
@@ -2,7 +2,7 @@
|
||||
"$schema": "https://schemas.wp.org/trunk/block.json",
|
||||
"apiVersion": 3,
|
||||
"name": "lamgc/asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.0-dev",
|
||||
"title": "Asciicast Player",
|
||||
"category": "media",
|
||||
"icon": "editor-code",
|
||||
@@ -21,6 +21,9 @@
|
||||
"autoPlay": { "type": "boolean", "default": false },
|
||||
"preload": { "type": "boolean", "default": true },
|
||||
"width": { "type": "string", "default": "100%" },
|
||||
"displayAlign": { "type": "string", "default": "center", "enum": ["left", "center", "right"] },
|
||||
"caption": { "type": "string", "default": "" },
|
||||
"isExample": { "type": "boolean", "default": false },
|
||||
"legacyStyle": { "type": "string", "default": "" },
|
||||
"cols": { "type": "number" },
|
||||
"rows": { "type": "number" },
|
||||
@@ -29,6 +32,7 @@
|
||||
"terminalLineHeight": { "type": "number" },
|
||||
"poster": { "type": "string" }
|
||||
},
|
||||
"example": { "attributes": { "isExample": true } },
|
||||
"supports": { "html": false, "align": ["wide", "full"] },
|
||||
"editorScript": "lamgc-asciiplayer-editor",
|
||||
"viewScript": "lamgc-asciiplayer-view",
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
# Dependency security review
|
||||
|
||||
Reviewed 2026-10-14 against the main-branch lockfile and fresh npm audit. Baseline: **44 affected package records (2 critical, 19 high, 20 moderate, 3 low), representing 15 distinct advisories**. The package-record count includes vulnerable packages and their affected parents; it is not 44 distinct security defects. All mapped paths originate in development dependencies. The final production-only root-lock audit reports zero findings; the separately vendored browser player is assessed in [player-bundle-review.md](player-bundle-review.md).
|
||||
|
||||
## Implemented narrow changes
|
||||
|
||||
Retain the current WordPress parent packages: npm registry reports `@wordpress/[email protected]` and `@wordpress/[email protected]` as current latest. This change uses scoped overrides:
|
||||
|
||||
```json
|
||||
{
|
||||
"copy-webpack-plugin": { "serialize-javascript": "7.0.5" },
|
||||
"markdownlint-cli": { "js-yaml": "5.4.3", "smol-toml": "1.9.1" },
|
||||
"simple-git": { "@simple-git/argv-parser": "2.0.1" }
|
||||
}
|
||||
```
|
||||
|
||||
- `serialize-javascript`: the current `[email protected]` calls the CommonJS serializer for cache keys. Version 7 retains that callable CommonJS API. Its major-version requirement is Node >=20, already satisfied by this project. Isolated serialization smoke tests passed. Upgrading the entire plugin to 14 would be a larger, unnecessary compatibility change. [v7 release](https://github.com/yahoo/serialize-javascript/releases/tag/v7.0.0)
|
||||
- `js-yaml`: 5.4.1 is the minimum patched version; 5.4.3 is the latest verified patch. Scope it to `markdownlint-cli`; that package pins `~5.2.1`. Do not override js-yaml globally: wp-env still calls `yaml.safeLoad`, which is unavailable in modern majors. The separate wp-env -> js-yaml 3 -> argparse 1 -> sprintf-js path remains.
|
||||
- `smol-toml`: 1.9.0 is the minimum patched version; 1.9.1 is the latest verified patch. Scope it to markdownlint-cli, which pins `~1.7.0`. The CommonJS parse API works and the null-prototype result matches the installed older version.
|
||||
- `qs`: 6.16.0 fixes both findings. **Prefer the in-range Express 4.22.2 -> 4.22.3 update**, because official metadata confirms 4.22.3 pins qs `~6.16.0`. If lockfile regeneration cannot resolve that parent update, a scoped `express -> qs: 6.16.0` override is a fallback. Avoid a disruptive Express 5 migration. The existing body-parser path already has 6.16.0.
|
||||
- `@simple-git/argv-parser`: the scoped 2.0.1 override is a partial mitigation only, with targeted no-execution tests. Preserve and document remaining simple-git alerts; details below.
|
||||
|
||||
These recommendations were based on official npm metadata, published tarballs, source inspection, and small isolated API smoke tests. Local build, 41 JS tests and packaging pass on Node 24.18.0. CI covers PHP 7.4/8.3 and real WordPress 6.3/PHP 7.4 and latest/PHP 8.2 integration.
|
||||
|
||||
## Critical simple-git findings: migration blocker
|
||||
|
||||
Path: `@wordpress/[email protected] -> [email protected] -> @simple-git/[email protected]`.
|
||||
|
||||
**Do not directly override simple-git to v4.** v4 removes the callable CommonJS default export and requires `const { simpleGit } = require('simple-git')`. wp-env currently uses `const SimpleGit = require('simple-git')` and then calls it in both `lib/download-sources.js` and `lib/runtime/docker/download-wp-phpunit.js`. A direct v4 override would fail during Git source/PHPUnit downloads. [Official v4 breaking changes](https://github.com/steveukx/git-js/releases/tag/[email protected])
|
||||
|
||||
The fully patched latest combination is simple-git **4.0.2**, which pins argv-parser **2.0.1**. Note that simple-git 4.0.1 pins parser 2.0.0, so it does not by itself clear the VISUAL finding.
|
||||
|
||||
A scoped parser-only override to 2.0.1 is included as a **partial mitigation**, with regression tests of the CommonJS API and rejected unsafe inputs. The `vulnerabilityCheck(tokens, env)` signature is unchanged, and isolated simple-git 3.36.0 with parser 2.0.1 passed read-only `checkIsRepo('root')`, `raw('rev-parse', '--show-toplevel')`, and `status()` checks. Parser checks rejected VISUAL, trailer command configuration, and include.path. However, `--receive-p` still produced no finding in that parser-only combination, and version-based simple-git advisories remain. This is not a complete fix and has not been validated through all wp-env Docker/download flows. It is reasonable to include the scoped parser override with the focused regressions while explicitly retaining the residual alerts; a full fix still needs a reviewed wp-env migration.
|
||||
|
||||
The examined wp-env call sites use clone/fetch/checkout/reset and fixed sparse-checkout commands; no commit, rebase, interpret-trailers, push, or explicit `.env()` calls were observed in these files. This reduces reachability of the reported flows for ordinary trusted wp-env use, but does not establish that the vulnerable dependency is harmless. Keep development configuration, Git arguments, environment values and source URLs trusted; do not run these tools on attacker-controlled configuration with privileged credentials.
|
||||
|
||||
## Advisory matrix
|
||||
|
||||
Ranges below are the audit's affected ranges and GitHub Advisory Database's patched versions. Registry availability was checked on the review date.
|
||||
|
||||
| Package / baseline | Advisory | Affected range | First patched version | Decision |
|
||||
|---|---|---|---|---|
|
||||
| @simple-git/argv-parser 1.1.1 | [VISUAL editor bypass](https://github.com/advisories/GHSA-v5rq-49vh-5v5c) | <2.0.1 | 2.0.1 | Parser 2.0.1 removes this finding; simple-git mitigation remains incomplete overall |
|
||||
| simple-git 3.36.0 | [Trailer command configuration](https://github.com/advisories/GHSA-x6jw-m9v5-85vh) | >=3.15.0 <4.0.1 | 4.0.1 | v4 is not drop-in for wp-env |
|
||||
| simple-git 3.36.0 | [Git configuration includes](https://github.com/advisories/GHSA-g4wm-2vf7-vfgr) | <=3.36.0 | 4.0.0 | Same migration blocker |
|
||||
| simple-git 3.36.0 | [Long-option abbreviation bypass](https://github.com/advisories/GHSA-858h-whjf-mvg5) | <=3.36.0 | 4.0.0 | Parser-only override does not fix this path |
|
||||
| serialize-javascript 6.0.2 | [RegExp/Date code injection](https://github.com/advisories/GHSA-5c6j-r48x-rmvq) | <=7.0.2 | 7.0.3 | Scoped 7.0.5 clears both findings |
|
||||
| serialize-javascript 6.0.2 | [Array-like object CPU exhaustion](https://github.com/advisories/GHSA-qj8w-gfj5-8c6v) | >=5.0.0 <7.0.5 | 7.0.5 | Scoped 7.0.5 |
|
||||
| braces 3.0.3 | [Deep nesting stack exhaustion](https://github.com/advisories/GHSA-vfj7-8cjw-p6xm) | <=3.0.3 | None | Latest published version still affected; trusted build globs only |
|
||||
| js-yaml 5.2.3 | [Empty merge source CPU exhaustion](https://github.com/advisories/GHSA-r3ph-w7gj-g6xm) | >=5.0.0 <=5.4.0 | 5.4.1 | Scoped 5.4.3 under markdownlint-cli |
|
||||
| smol-toml 1.7.2 | [Quadratic key parsing](https://github.com/advisories/GHSA-r4xh-jqrq-34v2) | <=1.8.0 | 1.9.0 | Scoped 1.9.1 |
|
||||
| sprintf-js 1.0.3 | [Unbounded precision DoS](https://github.com/advisories/GHSA-hp3w-g68c-fv3c) | <=1.1.3 | None | Latest published version still affected; wp-env parent migration needed |
|
||||
| qs 6.15.3 | [Array-limit bypass](https://github.com/advisories/GHSA-x5fp-wj9c-mxmx) | >=6.14.2 <=6.15.3 | 6.16.0 | Express 4.22.3 / qs 6.16.0 |
|
||||
| qs 6.15.3 | [Attacker-controlled isBuffer](https://github.com/advisories/GHSA-4mjr-xmp4-gh2g) | >=2.2.5 <6.16.0 | 6.16.0 | Scoped 6.16.0 |
|
||||
| postcss-selector-parser 6.1.4 | [Flat selector CPU exhaustion](https://github.com/advisories/GHSA-rj75-hqrm-r3gf) | <7.1.6 | 7.1.6 | Requires v6 -> v7 range override or parent migration; defer pending CSS-specific regression tests |
|
||||
| uuid 8.3.2 | [Missing output buffer checks](https://github.com/advisories/GHSA-w5hq-g745-h8pq) | <11.1.1 (installed line) | 11.1.1 | Cross-major candidate; sockjs only calls v4(), not the affected v3/v5/v6 APIs |
|
||||
| katex 0.16.47 | [Prototype pollution trust bypass](https://github.com/advisories/GHSA-238p-pmpm-9mq7) | >=0.11.0 <0.18.2 | 0.18.2 | 0.x minor-range migration; defer pending markdown math regression validation |
|
||||
|
||||
The KaTeX advisory range is from the fresh npm audit. Its GitHub advisory page could not be retrieved during this pass; registry 0.18.2 was downloaded and its rendering API smoke-tested. The fix boundary is inferred from the audit range rather than independently confirmed from that advisory page.
|
||||
|
||||
## Paths behind remaining package records
|
||||
|
||||
- braces: scripts -> fast-glob -> micromatch -> braces; also transitively affects copy-webpack-plugin, stylelint-family tooling, webpack-dev-server's chokidar and http-proxy-middleware paths. No patched braces release is available, despite some propagated `fixAvailable: true` flags in npm audit.
|
||||
- postcss-selector-parser: scripts -> cssnano 6.1.2 -> cssnano-preset-default 6.1.2 -> postcss-calc 9.0.1, postcss-merge-rules 6.1.1, postcss-minify-selectors 6.0.4, postcss-unique-selectors 6.0.4, or postcss-merge-longhand 6.0.5 -> stylehacks 6.1.1. Each currently resolves a nested parser 6.1.4. The hoisted parser 7.1.6 is already patched. v7's notable breaking behavior is safe insertion during iteration; avoid a blind global replacement. The advisory explicitly excludes ordinary build-time parsing of trusted source CSS from exposed request-path scenarios. [v7 release](https://github.com/postcss/postcss-selector-parser/releases/tag/v7.0.0)
|
||||
- sprintf-js: env -> js-yaml 3.15.2 -> argparse 1.0.10 -> sprintf-js 1.0.3. Updating sprintf-js to its latest 1.1.3 does not fix the advisory. Updating js-yaml globally breaks wp-env's safeLoad call.
|
||||
- uuid: scripts -> webpack-dev-server 5.2.6 -> sockjs 0.3.24 -> uuid 8.3.2. Source inspection finds `require('uuid').v4` and `uuidv4()` only. A scoped uuid11.1.1 override retains CommonJS and passed v4()/validate() smoke testing, but it remains outside sockjs's supported ^8 range. Do not choose uuid12+ blindly because of later module-format changes.
|
||||
- KaTeX: scripts -> markdownlint-cli 0.49.1 -> markdownlint 0.41.1 -> micromark-extension-math 3.1.0 -> katex 0.16.47. Minimum nonaffected release 0.18.2 exposes renderToString and passed a basic rendering smoke test, but is outside micromark's ^0.16 range.
|
||||
- qs (recommended fix): env -> @wp-playground/cli 3.1.57 -> express 4.22.2 -> qs 6.15.3; shared Express is also used by webpack-dev-server.
|
||||
- serialize-javascript (recommended fix): scripts -> copy-webpack-plugin 10.2.4 -> serialize-javascript 6.0.2.
|
||||
|
||||
## Engine consistency
|
||||
|
||||
The existing Playground/PHP-WASM 3.1.57 tree requires Node >=24.18.0 and npm >=11.16.0. `@wordpress/[email protected]` accepts Node `^22.22.2 || ^24.15.0 || >=26.0.0`, so the intersection is **`^24.18.0 || >=26.0.0`**, not plain >=24.18.0 (which would misleadingly include Node 25). Use npm >=11.16.0 and test the supported minimum in CI. The build and tests were rerun on Node 24.18.0 with npm 11.19.0. CI pins these versions. Node 26 is admitted by dependency engine declarations but has not been separately exercised here.
|
||||
|
||||
## Verification checklist
|
||||
|
||||
1. Regenerate the lockfile without force and inspect that only intended subtree changes occur.
|
||||
2. Run `npm ci`, build, JS tests, PHP tests where supported, and release packaging.
|
||||
3. Validate markdownlint YAML and TOML configuration loading after its minor-range overrides.
|
||||
4. Run final `npm audit --json` and `npm audit --omit=dev --json`; describe residuals honestly, including the critical simple-git findings.
|
||||
5. Track wp-env's simple-git v4 migration and braces/sprintf-js upstream releases. Do not suppress remaining advisories merely to make the report green.
|
||||
|
||||
## Final audit snapshot
|
||||
|
||||
After these changes, npm 11.19.0 reports **39 affected package records**
|
||||
(1 critical, 20 high, 14 moderate, 4 low), representing **8 distinct advisories**,
|
||||
versus 15 distinct advisories in the initial snapshot. Counts can change as the
|
||||
registry advisory database changes; do not equate affected parents with unique flaws.
|
||||
The remaining advisory packages are braces, KaTeX, postcss-selector-parser,
|
||||
simple-git (three advisories), sprintf-js and uuid. No advisory is suppressed.
|
||||
|
||||
`npm audit --omit=dev --json` reports zero findings for the root production lock.
|
||||
This does not certify arbitrary bundled code or establish a complete security audit.
|
||||
Do not run development servers or wp-env against untrusted configurations or
|
||||
source URLs, or expose development services publicly. A full simple-git fix
|
||||
needs a compatible wp-env migration; the parser override is not a complete fix.
|
||||
@@ -0,0 +1,62 @@
|
||||
# Prebuilt player dependency reachability review
|
||||
|
||||
Reviewed 2026-10-14 for `[email protected]`. This is a static review of
|
||||
specific published bytes, not an independent rebuild or a full security audit.
|
||||
|
||||
`scripts/vendor.mjs` copies the npm package's prebuilt browser bundle unchanged.
|
||||
The root lockfile therefore does not describe all components used to build it.
|
||||
The upstream dependency inventory is deliberately conservative: it includes
|
||||
Seroval 1.5.0 through Solid 1.9.6, including server-only dependency paths.
|
||||
|
||||
## Verified artifact
|
||||
|
||||
The official npm package integrity is recorded in package-lock.json.
|
||||
|
||||
- Minified bundle SHA-256: `a13c37632e1b5c49fe9128417b9319a9b5bc64cb457dd5ae52cbba8a3aceb880`
|
||||
- Readable bundle SHA-256: `4d63cfb88859f158d1eef5d8a5550861abcb7ec195fb5d684f35f6446a29fe11`
|
||||
|
||||
The minified hash also matches THIRD-PARTY-NOTICES.md and the installed package.
|
||||
|
||||
## Import and artifact evidence
|
||||
|
||||
1. [Player view.js](https://github.com/asciinema/asciinema-player/blob/v3.17.0/src/view.js)
|
||||
imports `render` from `solid-js/web`.
|
||||
2. Solid 1.9.6's package exports select `web/dist/web.js` for the browser/default
|
||||
import. Its only external import is `solid-js`; the client `dist/solid.js`
|
||||
has no imports. Neither imports Seroval.
|
||||
3. Seroval is imported by the separate `web/dist/server.js` SSR renderer,
|
||||
not the browser renderer.
|
||||
4. The [Rollup configuration](https://github.com/asciinema/asciinema-player/blob/v3.17.0/rollup.config.mjs)
|
||||
creates both readable and minified IIFEs from the same intermediate ESM bundle.
|
||||
The inspected readable IIFE contains the client renderer and does not contain
|
||||
Seroval deserialization implementations.
|
||||
5. Both bundles lack `Seroval`, `fromJSON`, `fromCrossJSON`, `deserialize`,
|
||||
`__SEROVAL_STREAM__`, and distinctive Seroval error/typed-array registry
|
||||
signatures. Name searches alone are not proof; they corroborate the import trace.
|
||||
6. Recording/live input paths use native `JSON.parse`/`response.json`, not
|
||||
Seroval decoding.
|
||||
|
||||
## Advisory-specific conclusion
|
||||
|
||||
No reachable affected Seroval decoder was found in these browser bundle bytes:
|
||||
|
||||
- [GHSA-mv8w-475r-vwqw](https://github.com/advisories/GHSA-mv8w-475r-vwqw):
|
||||
affected <=1.5.2, fixed 1.5.3; requires `fromJSON` Promise-control deserialization.
|
||||
- [GHSA-p6vx-979v-rg4c](https://github.com/advisories/GHSA-p6vx-979v-rg4c):
|
||||
affected >=0.12.0, <=1.6.0, fixed 1.6.2; requires `fromJSON` with plugin-produced
|
||||
callables and Promise assimilation.
|
||||
- [GHSA-jp82-f5mq-hwhp](https://github.com/advisories/GHSA-jp82-f5mq-hwhp):
|
||||
affected <=1.6.2, fixed 1.6.3; requires Seroval typed-array JSON deserialization.
|
||||
|
||||
Seroval 1.5.0 is inside these version ranges, but the necessary decoder is absent
|
||||
from this browser dependency path. Do not label the player vulnerable solely from
|
||||
that inventory, or claim the entire plugin safe from this limited review.
|
||||
Re-review after any player artifact or build-path change.
|
||||
|
||||
## Reproduction
|
||||
|
||||
Fetch official npm tarballs into separate directories using `npm pack --ignore-scripts`
|
||||
for `[email protected]`, `[email protected]`, and `[email protected]`.
|
||||
Verify both player hashes with `sha256sum`, inspect Solid's package exports and
|
||||
client/server imports, and compare the readable bundle implementation against
|
||||
those modules. Search both bundles for the decoder names/signatures above.
|
||||
+9
-6
@@ -17,6 +17,7 @@ if ( ! defined( 'ABSPATH' ) ) {
|
||||
* @return void
|
||||
*/
|
||||
function register_plugin() {
|
||||
load_plugin_textdomain( 'wp-asciiplayer', false, dirname( plugin_basename( PLUGIN_FILE ) ) . '/languages' );
|
||||
$base = plugin_dir_url( PLUGIN_FILE ) . 'build/';
|
||||
$asset = array(
|
||||
'dependencies' => array( 'wp-blocks', 'wp-element', 'wp-block-editor', 'wp-components', 'wp-i18n' ),
|
||||
@@ -31,7 +32,9 @@ function register_plugin() {
|
||||
$view_asset = require dirname( PLUGIN_FILE ) . '/build/view.asset.php';
|
||||
}
|
||||
|
||||
wp_register_script( 'lamgc-asciiplayer-player', $base . 'player.js', array(), VERSION, true );
|
||||
$versions = file_exists( dirname( PLUGIN_FILE ) . '/build/runtime.asset.php' ) ? require dirname( PLUGIN_FILE ) . '/build/runtime.asset.php' : array();
|
||||
$player_version = $versions['player.js'] ?? VERSION;
|
||||
wp_register_script( 'lamgc-asciiplayer-player', $base . 'player.js', array(), $player_version, true );
|
||||
wp_register_script(
|
||||
'lamgc-asciiplayer-view',
|
||||
$base . 'view.js',
|
||||
@@ -46,16 +49,16 @@ function register_plugin() {
|
||||
$asset['version'],
|
||||
true
|
||||
);
|
||||
wp_register_style( 'lamgc-asciiplayer-player-style', $base . 'player.css', array(), VERSION );
|
||||
wp_register_style( 'lamgc-asciiplayer-style', $base . 'style-index.css', array( 'lamgc-asciiplayer-player-style' ), VERSION );
|
||||
wp_register_style( 'lamgc-asciiplayer-editor-style', $base . 'index.css', array( 'lamgc-asciiplayer-player-style' ), VERSION );
|
||||
wp_register_style( 'lamgc-asciiplayer-player-style', $base . 'player.css', array(), $versions['player.css'] ?? VERSION );
|
||||
wp_register_style( 'lamgc-asciiplayer-style', $base . 'style-index.css', array( 'lamgc-asciiplayer-player-style' ), $versions['style-index.css'] ?? VERSION );
|
||||
wp_register_style( 'lamgc-asciiplayer-editor-style', $base . 'index.css', array( 'lamgc-asciiplayer-player-style' ), $versions['index.css'] ?? VERSION );
|
||||
|
||||
wp_add_inline_script(
|
||||
'lamgc-asciiplayer-editor',
|
||||
'window.wpAsciiplayerSettings = ' . wp_json_encode(
|
||||
array(
|
||||
'playerScriptUrl' => add_query_arg( 'ver', VERSION, $base . 'player.js' ),
|
||||
'playerStyleUrl' => add_query_arg( 'ver', VERSION, $base . 'player.css' ),
|
||||
'playerScriptUrl' => add_query_arg( 'ver', $player_version, $base . 'player.js' ),
|
||||
'playerStyleUrl' => add_query_arg( 'ver', $versions['player.css'] ?? VERSION, $base . 'player.css' ),
|
||||
),
|
||||
JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT
|
||||
) . ';',
|
||||
|
||||
@@ -45,6 +45,8 @@ function normalize_attributes( $attributes ) {
|
||||
'terminallineheight' => 'terminalLineHeight',
|
||||
'poster' => 'poster',
|
||||
'width' => 'width',
|
||||
'displayalign' => 'displayAlign',
|
||||
'caption' => 'caption',
|
||||
'style' => 'legacyStyle',
|
||||
'legacystyle' => 'legacyStyle',
|
||||
);
|
||||
|
||||
+24
-6
@@ -33,15 +33,33 @@ function render_player( $attributes = array(), $content = null, $block = false )
|
||||
|
||||
enqueue_player_assets();
|
||||
$style = player_style( $attributes );
|
||||
$wrapper = $block
|
||||
? get_block_wrapper_attributes( array( 'class' => 'asciiplayer-container', 'style' => $style ) )
|
||||
: 'class="asciiplayer-container"' . ( '' === $style ? '' : ' style="' . esc_attr( $style ) . '"' );
|
||||
return sprintf(
|
||||
'<div %1$s data-ap-src="%2$s" data-ap-options="%3$s"></div>',
|
||||
$wrapper,
|
||||
// The mount point owns only the player. Captions must stay outside it so
|
||||
// upstream disposal/reinitialization cannot remove author-written content.
|
||||
$mount_style = $style;
|
||||
$figure_style = '';
|
||||
if ( $block ) {
|
||||
// Keep height and other legacy player-container declarations on the
|
||||
// mount point. Only width moves to the figure, so captions add height.
|
||||
if ( preg_match_all( '/(?:^|;)\s*width\s*:\s*([^;]+)/i', $style, $widths ) ) {
|
||||
$figure_style = 'width:' . end( $widths[1] ) . ';';
|
||||
}
|
||||
$mount_style = trim( preg_replace( '/(^|;)\s*width\s*:[^;]*/i', '$1', $style ), '; ' );
|
||||
}
|
||||
$player = sprintf(
|
||||
'<div class="asciiplayer-container"%1$s data-ap-src="%2$s" data-ap-options="%3$s"></div>',
|
||||
'' !== $mount_style ? ' style="' . esc_attr( $mount_style ) . '"' : '',
|
||||
esc_url( $source, array( 'http', 'https' ) ),
|
||||
esc_attr( $options )
|
||||
);
|
||||
if ( ! $block ) {
|
||||
return $player;
|
||||
}
|
||||
$alignment = isset( $attributes['displayAlign'] ) && in_array( $attributes['displayAlign'], array( 'left', 'center', 'right' ), true ) ? $attributes['displayAlign'] : 'center';
|
||||
$wrapper = get_block_wrapper_attributes( array( 'class' => 'asciiplayer-block' ) );
|
||||
$figure = 'class="asciiplayer-figure asciiplayer-align-' . esc_attr( $alignment ) . '"' . ( '' !== $figure_style ? ' style="' . esc_attr( $figure_style ) . '"' : '' );
|
||||
// RichText emits escaped text and line breaks. No other markup is needed.
|
||||
$caption = isset( $attributes['caption'] ) ? wp_kses( (string) $attributes['caption'], array( 'br' => array() ) ) : '';
|
||||
return '<div ' . $wrapper . '><figure ' . $figure . '>' . $player . ( '' !== trim( $caption ) ? '<figcaption class="wp-element-caption">' . $caption . '</figcaption>' : '' ) . '</figure></div>';
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,386 @@
|
||||
<?php
|
||||
/**
|
||||
* Extension-scoped, content-validated Media Library support for asciicast files.
|
||||
*
|
||||
* @package LamGC\Asciiplayer
|
||||
*/
|
||||
|
||||
namespace LamGC\Asciiplayer;
|
||||
|
||||
if ( ! defined( 'ABSPATH' ) ) {
|
||||
exit;
|
||||
}
|
||||
|
||||
const CAST_MIME = 'application/x-asciicast';
|
||||
const CAST_MAX_BYTES = 33554432; // 32 MiB; WordPress/server upload limits still apply.
|
||||
const CAST_MAX_LINE_BYTES = 262144; // Bound individual JSON decodes to 256 KiB.
|
||||
const CAST_MAX_V1_BYTES = 2097152; // Legacy v1 is a single JSON document, not a stream.
|
||||
const CAST_MAX_EVENTS = 100000;
|
||||
const CAST_MAX_DIMENSION = 1000;
|
||||
const CAST_MAX_CELLS = 40000;
|
||||
const CAST_MAX_MARKERS = 1000;
|
||||
// Browser timers use signed 32-bit millisecond delays (~24.85 days). Keep the
|
||||
// raw timeline in this range; playback additionally checks the selected speed.
|
||||
const CAST_MAX_TIME_MS = 2147483647;
|
||||
const CAST_MAX_JSON_TOKENS = 400000;
|
||||
const CAST_MAX_JSON_LINE_TOKENS = 20000;
|
||||
const CAST_MAX_JSON_CONTAINERS = 100016;
|
||||
const CAST_JSON_DEPTH = 16;
|
||||
|
||||
/**
|
||||
* Reject allocation-heavy JSON before decoding it, without building a graph.
|
||||
*
|
||||
* Count container openings and scalar/key tokens, including duplicate keys.
|
||||
* Escapes and punctuation inside strings do not contribute to the budget.
|
||||
* Counters may be shared across JSONL records. This lexical resource gate is
|
||||
* not a JSON validator: json_decode remains responsible for grammar and UTF-8.
|
||||
*/
|
||||
function is_cast_json_within_budget( $text, &$containers, &$tokens, $token_limit = CAST_MAX_JSON_TOKENS ) {
|
||||
$length = strlen( $text );
|
||||
$depth = 0;
|
||||
$in_string = false;
|
||||
$escaped = false;
|
||||
$in_atom = false;
|
||||
for ( $index = 0; $index < $length; ++$index ) {
|
||||
$char = $text[ $index ];
|
||||
if ( $in_string ) {
|
||||
if ( $escaped ) {
|
||||
$escaped = false;
|
||||
} elseif ( '\\' === $char ) {
|
||||
$escaped = true;
|
||||
} elseif ( '"' === $char ) {
|
||||
$in_string = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if ( '"' === $char ) {
|
||||
$in_string = true;
|
||||
$in_atom = false;
|
||||
++$tokens;
|
||||
} elseif ( '{' === $char || '[' === $char ) {
|
||||
$in_atom = false;
|
||||
++$containers;
|
||||
++$depth;
|
||||
// json_decode's depth includes the scalar level inside containers.
|
||||
if ( $depth >= CAST_JSON_DEPTH ) {
|
||||
return false;
|
||||
}
|
||||
} elseif ( '}' === $char || ']' === $char ) {
|
||||
--$depth;
|
||||
$in_atom = false;
|
||||
if ( $depth < 0 ) {
|
||||
return false;
|
||||
}
|
||||
} elseif ( ',' === $char || ':' === $char || ' ' === $char || "\n" === $char || "\r" === $char || "\t" === $char ) {
|
||||
$in_atom = false;
|
||||
} elseif ( ! $in_atom ) {
|
||||
++$tokens;
|
||||
$in_atom = true;
|
||||
}
|
||||
if ( $containers > CAST_MAX_JSON_CONTAINERS || $tokens > $token_limit ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identify the last top-level version key without decoding a document graph.
|
||||
*
|
||||
* Run only after the lexical budget. Short JSON key/number decodes correctly
|
||||
* handle escaped keys and duplicate-key last-wins semantics. Nested metadata
|
||||
* never selects the format. This is a discriminator, not a grammar validator.
|
||||
*/
|
||||
function cast_top_level_version( $text ) {
|
||||
$length = strlen( $text );
|
||||
$depth = 0;
|
||||
$expect_key = false;
|
||||
$version = null;
|
||||
for ( $index = 0; $index < $length; ++$index ) {
|
||||
$char = $text[ $index ];
|
||||
if ( '"' === $char ) {
|
||||
$start = $index;
|
||||
$escaped = false;
|
||||
while ( ++$index < $length ) {
|
||||
if ( $escaped ) {
|
||||
$escaped = false;
|
||||
} elseif ( '\\' === $text[ $index ] ) {
|
||||
$escaped = true;
|
||||
} elseif ( '"' === $text[ $index ] ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ( 1 !== $depth || ! $expect_key ) {
|
||||
continue;
|
||||
}
|
||||
$expect_key = false;
|
||||
// Seven fully escaped characters plus quotes need at most 44 bytes.
|
||||
$key_length = $index - $start + 1;
|
||||
if ( $key_length < 9 || $key_length > 44 || 'version' !== json_decode( substr( $text, $start, $key_length ) ) ) {
|
||||
continue;
|
||||
}
|
||||
$version = null;
|
||||
$cursor = $index + 1;
|
||||
while ( $cursor < $length && false !== strpos( " \t\r\n", $text[ $cursor ] ) ) {
|
||||
++$cursor;
|
||||
}
|
||||
if ( $cursor >= $length || ':' !== $text[ $cursor++ ] ) {
|
||||
continue;
|
||||
}
|
||||
while ( $cursor < $length && false !== strpos( " \t\r\n", $text[ $cursor ] ) ) {
|
||||
++$cursor;
|
||||
}
|
||||
$start = $cursor;
|
||||
while ( $cursor < $length && false === strpos( ",}] \t\r\n", $text[ $cursor ] ) ) {
|
||||
++$cursor;
|
||||
if ( $cursor - $start > 32 ) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ( $cursor > $start && $cursor - $start <= 32 ) {
|
||||
$value = json_decode( substr( $text, $start, $cursor - $start ) );
|
||||
$version = is_int( $value ) ? $value : null;
|
||||
}
|
||||
} elseif ( '{' === $char || '[' === $char ) {
|
||||
++$depth;
|
||||
if ( 1 === $depth ) {
|
||||
if ( '{' !== $char ) {
|
||||
return null;
|
||||
}
|
||||
$expect_key = true;
|
||||
}
|
||||
} elseif ( '}' === $char || ']' === $char ) {
|
||||
--$depth;
|
||||
} elseif ( ',' === $char && 1 === $depth ) {
|
||||
$expect_key = true;
|
||||
}
|
||||
}
|
||||
return $version;
|
||||
}
|
||||
|
||||
/** Whether this user and, on multisite, the network permit .cast uploads. */
|
||||
function can_upload_cast( $user = null ) {
|
||||
$allowed = null === $user ? current_user_can( 'upload_files' ) : user_can( $user, 'upload_files' );
|
||||
if ( ! $allowed ) {
|
||||
return false;
|
||||
}
|
||||
if ( is_multisite() ) {
|
||||
$extensions = preg_split( '/\s+/', strtolower( (string) get_site_option( 'upload_filetypes', '' ) ) );
|
||||
return in_array( 'cast', $extensions, true );
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Add only the .cast extension; never enable generic JSON, text, HTML or SVG. */
|
||||
function allow_cast_upload_mime( $mimes, $user = null ) {
|
||||
if ( can_upload_cast( $user ) ) {
|
||||
$mimes['cast'] = CAST_MIME;
|
||||
}
|
||||
return $mimes;
|
||||
}
|
||||
|
||||
/** A filename must actually end in .cast, including before WordPress sanitizes it. */
|
||||
function is_cast_filename( $filename ) {
|
||||
return is_string( $filename ) && 1 === preg_match( '/\.cast\z/i', $filename );
|
||||
}
|
||||
|
||||
/** Nonnegative seconds within the supported browser timer/precision horizon. */
|
||||
function is_cast_time( $value ) {
|
||||
return ( is_int( $value ) || is_float( $value ) ) && $value >= 0 && $value * 1000 <= CAST_MAX_TIME_MS;
|
||||
}
|
||||
|
||||
/** Bound both initial and resize dimensions before they reach the terminal. */
|
||||
function is_cast_dimension( $value ) {
|
||||
return is_int( $value ) && $value > 0 && $value <= CAST_MAX_DIMENSION;
|
||||
}
|
||||
|
||||
/** Bound the cell product as well as each independent axis. */
|
||||
function is_cast_size( $cols, $rows ) {
|
||||
return is_cast_dimension( $cols ) && is_cast_dimension( $rows ) && $cols * $rows <= CAST_MAX_CELLS;
|
||||
}
|
||||
|
||||
/** Validate metadata used by asciinema-player; unknown fields remain compatible. */
|
||||
function is_cast_header( $header ) {
|
||||
if ( ! is_object( $header ) || ! isset( $header->version ) || ! in_array( $header->version, array( 1, 2, 3 ), true ) ) {
|
||||
return false;
|
||||
}
|
||||
$terminal = 3 === $header->version ? ( $header->term ?? null ) : $header;
|
||||
if ( ! is_object( $terminal ) ) {
|
||||
return false;
|
||||
}
|
||||
$cols = 3 === $header->version ? ( $terminal->cols ?? null ) : ( $terminal->width ?? null );
|
||||
$rows = 3 === $header->version ? ( $terminal->rows ?? null ) : ( $terminal->height ?? null );
|
||||
// The bundled player treats explicit zero header dimensions as defaults.
|
||||
$cols = 0 === $cols ? 80 : $cols;
|
||||
$rows = 0 === $rows ? 24 : $rows;
|
||||
if ( ! is_cast_size( $cols, $rows ) ) {
|
||||
return false;
|
||||
}
|
||||
foreach ( array( 'duration', 'idle_time_limit' ) as $key ) {
|
||||
if ( property_exists( $header, $key ) && ! is_cast_time( $header->$key ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Validate a whole bounded legacy v1 document, including every stdout frame. */
|
||||
function is_cast_v1( $text ) {
|
||||
$containers = 0;
|
||||
$tokens = 0;
|
||||
if ( strlen( $text ) > CAST_MAX_V1_BYTES || ! is_cast_json_within_budget( $text, $containers, $tokens ) || 1 !== cast_top_level_version( $text ) ) {
|
||||
return false;
|
||||
}
|
||||
$recording = json_decode( $text, false, CAST_JSON_DEPTH );
|
||||
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_header( $recording ) || 1 !== $recording->version || ! isset( $recording->stdout ) || ! is_array( $recording->stdout ) || count( $recording->stdout ) > CAST_MAX_EVENTS ) {
|
||||
return false;
|
||||
}
|
||||
$time_ms = 0;
|
||||
foreach ( $recording->stdout as $frame ) {
|
||||
if ( ! is_array( $frame ) || 2 !== count( $frame ) || ! is_cast_time( $frame[0] ) || ! is_string( $frame[1] ) ) {
|
||||
return false;
|
||||
}
|
||||
// Match upstream's arithmetic order, including floating-point rounding.
|
||||
$time_ms += $frame[0] * 1000;
|
||||
if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Validate one JSONL event, with absolute v2 time or relative v3 intervals. */
|
||||
function is_cast_event( $event, $version, &$time_ms, &$previous_time ) {
|
||||
if ( ! is_array( $event ) || 3 !== count( $event ) || ! is_cast_time( $event[0] ) || ! is_string( $event[1] ) || '' === $event[1] || ! is_string( $event[2] ) ) {
|
||||
return false;
|
||||
}
|
||||
$event_ms = $event[0] * 1000;
|
||||
if ( 2 === $version && $event[0] < $previous_time ) {
|
||||
return false;
|
||||
}
|
||||
$previous_time = $event[0];
|
||||
$time_ms = 2 === $version ? $event_ms : $time_ms + $event_ms;
|
||||
if ( ! is_finite( $time_ms ) || $time_ms > CAST_MAX_TIME_MS ) {
|
||||
return false;
|
||||
}
|
||||
if ( 'r' === $event[1] ) {
|
||||
if ( 1 !== preg_match( '/^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/D', $event[2], $matches ) || ! is_cast_size( (int) $matches[1], (int) $matches[2] ) ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
// Unknown event codes are intentionally accepted, as required by the format.
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect the entire file, not just a plausible header or a MIME guess.
|
||||
*
|
||||
* v2/v3 are read line by line. v1 needs a bounded complete JSON decode. Limits
|
||||
* bound bytes, per-line memory, nesting and event count, including malformed input.
|
||||
* Formats: https://docs.asciinema.org/manual/asciicast/ (v1, v2 and v3).
|
||||
*
|
||||
* @param string $path Local temporary upload path; stream wrappers are forbidden.
|
||||
* @return bool
|
||||
*/
|
||||
function is_valid_cast_file( $path ) {
|
||||
if ( ! is_string( $path ) || '' === $path || false !== strpos( $path, '://' ) || ! is_file( $path ) || ! is_readable( $path ) ) {
|
||||
return false;
|
||||
}
|
||||
// Read-only local upload validation needs bounded streaming; WP_Filesystem reads whole files.
|
||||
$handle = fopen( $path, 'rb' ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fopen -- Local temporary upload only; wrappers rejected above.
|
||||
if ( false === $handle ) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
$stat = fstat( $handle );
|
||||
if ( false === $stat || $stat['size'] < 1 || $stat['size'] > CAST_MAX_BYTES ) {
|
||||
return false;
|
||||
}
|
||||
$line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 );
|
||||
if ( false === $line ) {
|
||||
return false;
|
||||
}
|
||||
$containers = 0;
|
||||
$tokens = 0;
|
||||
$header = null;
|
||||
if ( strlen( $line ) <= CAST_MAX_LINE_BYTES && is_cast_json_within_budget( $line, $containers, $tokens, CAST_MAX_JSON_LINE_TOKENS ) ) {
|
||||
$header = json_decode( $line, false, CAST_JSON_DEPTH );
|
||||
}
|
||||
if ( ! is_cast_header( $header ) || 1 === $header->version ) {
|
||||
// Legacy v1 may be compact or pretty-printed. Its whole-document
|
||||
// byte and structure budgets apply before any complete decode.
|
||||
if ( $stat['size'] > CAST_MAX_V1_BYTES || 0 !== fseek( $handle, 0 ) ) {
|
||||
return false;
|
||||
}
|
||||
$text = stream_get_contents( $handle, CAST_MAX_V1_BYTES + 1 );
|
||||
return false !== $text && strlen( $text ) <= CAST_MAX_V1_BYTES && feof( $handle ) && is_cast_v1( $text );
|
||||
}
|
||||
$bytes = strlen( $line );
|
||||
$count = 0;
|
||||
$markers = 0;
|
||||
$time_ms = 0;
|
||||
$previous_time = 0;
|
||||
while ( false !== ( $line = fgets( $handle, CAST_MAX_LINE_BYTES + 2 ) ) ) {
|
||||
$bytes += strlen( $line );
|
||||
if ( $bytes > CAST_MAX_BYTES || strlen( $line ) > CAST_MAX_LINE_BYTES || ++$count > CAST_MAX_EVENTS ) {
|
||||
return false;
|
||||
}
|
||||
// Match the bundled player's parser: only lines beginning with '['
|
||||
// are events. Ignored lines still consume byte and line budgets.
|
||||
if ( '[' !== $line[0] ) {
|
||||
continue;
|
||||
}
|
||||
$containers = 0;
|
||||
$tokens = 0;
|
||||
if ( ! is_cast_json_within_budget( $line, $containers, $tokens, CAST_MAX_JSON_LINE_TOKENS ) ) {
|
||||
return false;
|
||||
}
|
||||
$event = json_decode( $line, false, CAST_JSON_DEPTH );
|
||||
if ( JSON_ERROR_NONE !== json_last_error() || ! is_cast_event( $event, $header->version, $time_ms, $previous_time ) ) {
|
||||
return false;
|
||||
}
|
||||
if ( 'm' === $event[1] && ++$markers > CAST_MAX_MARKERS ) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return feof( $handle );
|
||||
} finally {
|
||||
fclose( $handle ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_system_operations_fclose -- Always close the bounded read-only upload stream.
|
||||
}
|
||||
}
|
||||
|
||||
/** Reject invalid .cast uploads even for users with unfiltered_upload permission. */
|
||||
function validate_cast_upload( $file ) {
|
||||
if ( ! isset( $file['name'] ) || ! is_cast_filename( $file['name'] ) || ! empty( $file['error'] ) ) {
|
||||
return $file;
|
||||
}
|
||||
$allowed = get_allowed_mime_types();
|
||||
if ( ! can_upload_cast() || ! isset( $allowed['cast'] ) || CAST_MIME !== $allowed['cast'] ) {
|
||||
$file['error'] = __( 'You are not allowed to upload Asciicast files.', 'wp-asciiplayer' );
|
||||
} elseif ( ! is_valid_cast_file( $file['tmp_name'] ?? null ) ) {
|
||||
$file['error'] = __( 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).', 'wp-asciiplayer' );
|
||||
}
|
||||
return $file;
|
||||
}
|
||||
|
||||
/** Override generic fileinfo MIME guesses only for an allowed, validated .cast. */
|
||||
function check_cast_filetype( $data, $file, $filename, $mimes = null, $real_mime = false ) {
|
||||
if ( ! is_cast_filename( $filename ) ) {
|
||||
return $data;
|
||||
}
|
||||
$global_allowed = get_allowed_mime_types();
|
||||
$allowed = null === $mimes ? $global_allowed : $mimes;
|
||||
// wp_check_filetype() treats an empty map as its default map. Do not let an
|
||||
// explicitly empty allow-list silently re-enable this extension.
|
||||
$checked = is_array( $allowed ) && ! empty( $allowed ) ? wp_check_filetype( $filename, $allowed ) : array( 'ext' => false, 'type' => false );
|
||||
if ( can_upload_cast() && isset( $global_allowed['cast'] ) && CAST_MIME === $global_allowed['cast'] && 'cast' === strtolower( (string) $checked['ext'] ) && CAST_MIME === $checked['type'] && is_valid_cast_file( $file ) ) {
|
||||
$data['ext'] = 'cast';
|
||||
$data['type'] = CAST_MIME;
|
||||
$data['proper_filename'] = false;
|
||||
} else {
|
||||
$data['ext'] = false;
|
||||
$data['type'] = false;
|
||||
$data['proper_filename'] = false;
|
||||
}
|
||||
return $data;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
{
|
||||
"domain": "wp-asciiplayer",
|
||||
"locale_data": {
|
||||
"messages": {
|
||||
"": {
|
||||
"domain": "wp-asciiplayer",
|
||||
"lang": "zh_CN",
|
||||
"plural-forms": "nplurals=1; plural=0;"
|
||||
},
|
||||
"Columns": [
|
||||
"列数"
|
||||
],
|
||||
"From recording": [
|
||||
"使用录制尺寸"
|
||||
],
|
||||
"Rows": [
|
||||
"行数"
|
||||
],
|
||||
"Placeholders show the recording’s original columns and rows once loaded. Leave blank to follow its terminal size and recorded resize events. These overrides change the character grid, not the display width, and may alter or crop the layout.": [
|
||||
"加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
|
||||
],
|
||||
"Use recording size": [
|
||||
"使用录制尺寸"
|
||||
],
|
||||
"Asciinema": [
|
||||
"Asciinema"
|
||||
],
|
||||
"Recording theme (automatic)": [
|
||||
"录制文件主题(自动)"
|
||||
],
|
||||
"Custom": [
|
||||
"自定义"
|
||||
],
|
||||
"Width": [
|
||||
"按宽度缩放"
|
||||
],
|
||||
"Original size": [
|
||||
"原始大小"
|
||||
],
|
||||
"Height (legacy)": [
|
||||
"按高度缩放(旧版)"
|
||||
],
|
||||
"Width and height (legacy)": [
|
||||
"按宽高缩放(旧版)"
|
||||
],
|
||||
"Example terminal recording": [
|
||||
"终端录屏示例"
|
||||
],
|
||||
"A terminal recording, right in your post.": [
|
||||
"在文章中直接播放终端录屏。"
|
||||
],
|
||||
"Terminal size": [
|
||||
"终端尺寸"
|
||||
],
|
||||
"Terminal size (columns × rows)": [
|
||||
"终端尺寸(列数 × 行数)"
|
||||
],
|
||||
"Close": [
|
||||
"关闭"
|
||||
],
|
||||
"Display": [
|
||||
"显示"
|
||||
],
|
||||
"Player width": [
|
||||
"播放器宽度"
|
||||
],
|
||||
"Custom width": [
|
||||
"自定义宽度"
|
||||
],
|
||||
"Use a CSS length, such as 480px or 65%. The player stays within its available space.": [
|
||||
"使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
|
||||
],
|
||||
"Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.": [
|
||||
"请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
|
||||
],
|
||||
"Display alignment": [
|
||||
"对齐方式"
|
||||
],
|
||||
"Left": [
|
||||
"左对齐"
|
||||
],
|
||||
"Center": [
|
||||
"居中"
|
||||
],
|
||||
"Right": [
|
||||
"右对齐"
|
||||
],
|
||||
"Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.": [
|
||||
"显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
|
||||
],
|
||||
"Playback": [
|
||||
"播放"
|
||||
],
|
||||
"Playback speed": [
|
||||
"播放速度"
|
||||
],
|
||||
"Loop playback": [
|
||||
"循环播放"
|
||||
],
|
||||
"Autoplay on published page": [
|
||||
"在发布后的页面自动播放"
|
||||
],
|
||||
"The editor preview always waits for you to press play.": [
|
||||
"编辑器预览始终需要点击播放后才会开始。"
|
||||
],
|
||||
"Preload on published page": [
|
||||
"在发布后的页面预加载"
|
||||
],
|
||||
"Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.": [
|
||||
"在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
|
||||
],
|
||||
"Start at (seconds)": [
|
||||
"起始时间(秒)"
|
||||
],
|
||||
"Idle time limit (seconds)": [
|
||||
"最长空闲时间(秒)"
|
||||
],
|
||||
"Shorten long pauses. Use 0 to keep the recording’s default.": [
|
||||
"缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
|
||||
],
|
||||
"Appearance": [
|
||||
"外观"
|
||||
],
|
||||
"Theme": [
|
||||
"主题"
|
||||
],
|
||||
"Player controls": [
|
||||
"播放控制栏"
|
||||
],
|
||||
"Show on interaction": [
|
||||
"交互时显示"
|
||||
],
|
||||
"Always show": [
|
||||
"始终显示"
|
||||
],
|
||||
"Hide": [
|
||||
"隐藏"
|
||||
],
|
||||
"Fit": [
|
||||
"缩放方式"
|
||||
],
|
||||
"Height-based fitting requires a fixed container height in your site CSS.": [
|
||||
"按高度缩放需要在站点 CSS 中设置固定的容器高度。"
|
||||
],
|
||||
"The custom container style from your shortcode is preserved on the published page.": [
|
||||
"发布后的页面会保留简码中的自定义容器样式。"
|
||||
],
|
||||
"Help": [
|
||||
"帮助"
|
||||
],
|
||||
"A valid recording URL loads its preview automatically, including when reopening this editor. That server receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.": [
|
||||
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast 文件直链;外部服务器需允许跨域请求(CORS)。"
|
||||
],
|
||||
"Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.": [
|
||||
"使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
|
||||
],
|
||||
"Recording URL": [
|
||||
"录制文件 URL"
|
||||
],
|
||||
"Apply URL": [
|
||||
"应用 URL"
|
||||
],
|
||||
"Choose an Asciicast recording": [
|
||||
"选择 Asciicast 录制文件"
|
||||
],
|
||||
"Choose recording": [
|
||||
"选择录制文件"
|
||||
],
|
||||
"Choose an Asciicast (.cast) file from the Media Library.": [
|
||||
"请从媒体库选择 Asciicast(.cast)文件。"
|
||||
],
|
||||
"Enter an HTTP(S) recording URL or a path starting with a single /.": [
|
||||
"请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
|
||||
],
|
||||
"Asciicast Player": [
|
||||
"Asciicast 播放器"
|
||||
],
|
||||
"Enter a recording URL to load its preview automatically. Playback starts only when you press play.": [
|
||||
"输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
|
||||
],
|
||||
"Add a caption…": [
|
||||
"添加说明文字…"
|
||||
],
|
||||
"Recording caption": [
|
||||
"录屏说明文字"
|
||||
],
|
||||
"Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.": [
|
||||
"按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
|
||||
],
|
||||
"block title\u0004Asciicast Player": [
|
||||
"Asciicast 播放器"
|
||||
],
|
||||
"block description\u0004Embed and preview a terminal recording with the locally bundled asciinema player.": [
|
||||
"使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
|
||||
],
|
||||
"block keyword\u0004asciinema": [
|
||||
"asciinema"
|
||||
],
|
||||
"block keyword\u0004terminal": [
|
||||
"终端"
|
||||
],
|
||||
"block keyword\u0004recording": [
|
||||
"录屏"
|
||||
],
|
||||
"Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [
|
||||
"无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
|
||||
],
|
||||
"The local player could not start. Try again, or check that the plugin’s built assets are installed.": [
|
||||
"本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
|
||||
],
|
||||
"Loading recording…": [
|
||||
"正在加载录制文件…"
|
||||
],
|
||||
"Retry preview": [
|
||||
"重试预览"
|
||||
],
|
||||
"Interactive terminal recording preview": [
|
||||
"可交互的终端录屏预览"
|
||||
],
|
||||
"This recording exceeds the file size limit.": [
|
||||
"该录屏超过文件大小限制。"
|
||||
],
|
||||
"This recording contains a line that exceeds the size limit.": [
|
||||
"该录屏包含超出大小限制的行。"
|
||||
],
|
||||
"This recording contains too many events.": [
|
||||
"该录屏包含过多事件。"
|
||||
],
|
||||
"This recording contains too many markers.": [
|
||||
"该录屏包含过多时间标记。"
|
||||
],
|
||||
"This recording requests terminal dimensions that exceed the supported limits.": [
|
||||
"该录屏请求的终端尺寸超出支持范围。"
|
||||
],
|
||||
"This recording requests too many terminal cells.": [
|
||||
"该录屏请求的终端单元格过多。"
|
||||
],
|
||||
"This recording is too complex to load safely.": [
|
||||
"该录屏结构过于复杂,无法安全加载。"
|
||||
],
|
||||
"The recording is taking too long to load. Check your connection and try again.": [
|
||||
"录制文件加载超时。请检查网络连接后重试。"
|
||||
],
|
||||
"This recording contains an invalid or unsupported timestamp.": [
|
||||
"该录屏包含无效或不支持的时间戳。"
|
||||
],
|
||||
"Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [
|
||||
"无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
|
||||
],
|
||||
"You are not allowed to upload Asciicast files.": [
|
||||
"你没有上传 Asciicast 文件的权限。"
|
||||
],
|
||||
"Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).": [
|
||||
"请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。"
|
||||
],
|
||||
"Add interactive terminal recordings to posts and pages with a block or shortcode.": [
|
||||
"通过区块或简码在文章和页面中添加可交互的终端录屏。"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
{
|
||||
"domain": "wp-asciiplayer",
|
||||
"locale_data": {
|
||||
"messages": {
|
||||
"": {
|
||||
"domain": "wp-asciiplayer",
|
||||
"lang": "zh_CN",
|
||||
"plural-forms": "nplurals=1; plural=0;"
|
||||
},
|
||||
"Columns": [
|
||||
"列数"
|
||||
],
|
||||
"From recording": [
|
||||
"使用录制尺寸"
|
||||
],
|
||||
"Rows": [
|
||||
"行数"
|
||||
],
|
||||
"Placeholders show the recording’s original columns and rows once loaded. Leave blank to follow its terminal size and recorded resize events. These overrides change the character grid, not the display width, and may alter or crop the layout.": [
|
||||
"加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
|
||||
],
|
||||
"Use recording size": [
|
||||
"使用录制尺寸"
|
||||
],
|
||||
"Asciinema": [
|
||||
"Asciinema"
|
||||
],
|
||||
"Recording theme (automatic)": [
|
||||
"录制文件主题(自动)"
|
||||
],
|
||||
"Custom": [
|
||||
"自定义"
|
||||
],
|
||||
"Width": [
|
||||
"按宽度缩放"
|
||||
],
|
||||
"Original size": [
|
||||
"原始大小"
|
||||
],
|
||||
"Height (legacy)": [
|
||||
"按高度缩放(旧版)"
|
||||
],
|
||||
"Width and height (legacy)": [
|
||||
"按宽高缩放(旧版)"
|
||||
],
|
||||
"Example terminal recording": [
|
||||
"终端录屏示例"
|
||||
],
|
||||
"A terminal recording, right in your post.": [
|
||||
"在文章中直接播放终端录屏。"
|
||||
],
|
||||
"Terminal size": [
|
||||
"终端尺寸"
|
||||
],
|
||||
"Terminal size (columns × rows)": [
|
||||
"终端尺寸(列数 × 行数)"
|
||||
],
|
||||
"Close": [
|
||||
"关闭"
|
||||
],
|
||||
"Display": [
|
||||
"显示"
|
||||
],
|
||||
"Player width": [
|
||||
"播放器宽度"
|
||||
],
|
||||
"Custom width": [
|
||||
"自定义宽度"
|
||||
],
|
||||
"Use a CSS length, such as 480px or 65%. The player stays within its available space.": [
|
||||
"使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
|
||||
],
|
||||
"Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.": [
|
||||
"请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
|
||||
],
|
||||
"Display alignment": [
|
||||
"对齐方式"
|
||||
],
|
||||
"Left": [
|
||||
"左对齐"
|
||||
],
|
||||
"Center": [
|
||||
"居中"
|
||||
],
|
||||
"Right": [
|
||||
"右对齐"
|
||||
],
|
||||
"Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.": [
|
||||
"显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
|
||||
],
|
||||
"Playback": [
|
||||
"播放"
|
||||
],
|
||||
"Playback speed": [
|
||||
"播放速度"
|
||||
],
|
||||
"Loop playback": [
|
||||
"循环播放"
|
||||
],
|
||||
"Autoplay on published page": [
|
||||
"在发布后的页面自动播放"
|
||||
],
|
||||
"The editor preview always waits for you to press play.": [
|
||||
"编辑器预览始终需要点击播放后才会开始。"
|
||||
],
|
||||
"Preload on published page": [
|
||||
"在发布后的页面预加载"
|
||||
],
|
||||
"Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.": [
|
||||
"在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
|
||||
],
|
||||
"Start at (seconds)": [
|
||||
"起始时间(秒)"
|
||||
],
|
||||
"Idle time limit (seconds)": [
|
||||
"最长空闲时间(秒)"
|
||||
],
|
||||
"Shorten long pauses. Use 0 to keep the recording’s default.": [
|
||||
"缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
|
||||
],
|
||||
"Appearance": [
|
||||
"外观"
|
||||
],
|
||||
"Theme": [
|
||||
"主题"
|
||||
],
|
||||
"Player controls": [
|
||||
"播放控制栏"
|
||||
],
|
||||
"Show on interaction": [
|
||||
"交互时显示"
|
||||
],
|
||||
"Always show": [
|
||||
"始终显示"
|
||||
],
|
||||
"Hide": [
|
||||
"隐藏"
|
||||
],
|
||||
"Fit": [
|
||||
"缩放方式"
|
||||
],
|
||||
"Height-based fitting requires a fixed container height in your site CSS.": [
|
||||
"按高度缩放需要在站点 CSS 中设置固定的容器高度。"
|
||||
],
|
||||
"The custom container style from your shortcode is preserved on the published page.": [
|
||||
"发布后的页面会保留简码中的自定义容器样式。"
|
||||
],
|
||||
"Help": [
|
||||
"帮助"
|
||||
],
|
||||
"A valid recording URL loads its preview automatically, including when reopening this editor. That server receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.": [
|
||||
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast 文件直链;外部服务器需允许跨域请求(CORS)。"
|
||||
],
|
||||
"Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.": [
|
||||
"使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
|
||||
],
|
||||
"Recording URL": [
|
||||
"录制文件 URL"
|
||||
],
|
||||
"Apply URL": [
|
||||
"应用 URL"
|
||||
],
|
||||
"Choose an Asciicast recording": [
|
||||
"选择 Asciicast 录制文件"
|
||||
],
|
||||
"Choose recording": [
|
||||
"选择录制文件"
|
||||
],
|
||||
"Choose an Asciicast (.cast) file from the Media Library.": [
|
||||
"请从媒体库选择 Asciicast(.cast)文件。"
|
||||
],
|
||||
"Enter an HTTP(S) recording URL or a path starting with a single /.": [
|
||||
"请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
|
||||
],
|
||||
"Asciicast Player": [
|
||||
"Asciicast 播放器"
|
||||
],
|
||||
"Enter a recording URL to load its preview automatically. Playback starts only when you press play.": [
|
||||
"输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
|
||||
],
|
||||
"Add a caption…": [
|
||||
"添加说明文字…"
|
||||
],
|
||||
"Recording caption": [
|
||||
"录屏说明文字"
|
||||
],
|
||||
"Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.": [
|
||||
"按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
|
||||
],
|
||||
"block title\u0004Asciicast Player": [
|
||||
"Asciicast 播放器"
|
||||
],
|
||||
"block description\u0004Embed and preview a terminal recording with the locally bundled asciinema player.": [
|
||||
"使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
|
||||
],
|
||||
"block keyword\u0004asciinema": [
|
||||
"asciinema"
|
||||
],
|
||||
"block keyword\u0004terminal": [
|
||||
"终端"
|
||||
],
|
||||
"block keyword\u0004recording": [
|
||||
"录屏"
|
||||
],
|
||||
"Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.": [
|
||||
"无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
|
||||
],
|
||||
"The local player could not start. Try again, or check that the plugin’s built assets are installed.": [
|
||||
"本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
|
||||
],
|
||||
"Loading recording…": [
|
||||
"正在加载录制文件…"
|
||||
],
|
||||
"Retry preview": [
|
||||
"重试预览"
|
||||
],
|
||||
"Interactive terminal recording preview": [
|
||||
"可交互的终端录屏预览"
|
||||
],
|
||||
"This recording exceeds the file size limit.": [
|
||||
"该录屏超过文件大小限制。"
|
||||
],
|
||||
"This recording contains a line that exceeds the size limit.": [
|
||||
"该录屏包含超出大小限制的行。"
|
||||
],
|
||||
"This recording contains too many events.": [
|
||||
"该录屏包含过多事件。"
|
||||
],
|
||||
"This recording contains too many markers.": [
|
||||
"该录屏包含过多时间标记。"
|
||||
],
|
||||
"This recording requests terminal dimensions that exceed the supported limits.": [
|
||||
"该录屏请求的终端尺寸超出支持范围。"
|
||||
],
|
||||
"This recording requests too many terminal cells.": [
|
||||
"该录屏请求的终端单元格过多。"
|
||||
],
|
||||
"This recording is too complex to load safely.": [
|
||||
"该录屏结构过于复杂,无法安全加载。"
|
||||
],
|
||||
"The recording is taking too long to load. Check your connection and try again.": [
|
||||
"录制文件加载超时。请检查网络连接后重试。"
|
||||
],
|
||||
"This recording contains an invalid or unsupported timestamp.": [
|
||||
"该录屏包含无效或不支持的时间戳。"
|
||||
],
|
||||
"Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.": [
|
||||
"无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
|
||||
],
|
||||
"You are not allowed to upload Asciicast files.": [
|
||||
"你没有上传 Asciicast 文件的权限。"
|
||||
],
|
||||
"Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).": [
|
||||
"请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。"
|
||||
],
|
||||
"Add interactive terminal recordings to posts and pages with a block or shortcode.": [
|
||||
"通过区块或简码在文章和页面中添加可交互的终端录屏。"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,402 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: wp-asciiplayer 1.1.0-dev\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=utf-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"X-Domain: wp-asciiplayer\n"
|
||||
"Language: zh_CN\n"
|
||||
"Plural-Forms: nplurals=1; plural=0;\n"
|
||||
"Language-Team: Simplified Chinese\n"
|
||||
|
||||
#: src/edit.js:91
|
||||
msgid "A terminal recording, right in your post."
|
||||
msgstr "在文章中直接播放终端录屏。"
|
||||
|
||||
#: src/edit.js:139
|
||||
msgid ""
|
||||
"A valid recording URL loads its preview automatically, including when "
|
||||
"reopening this editor. That server receives your browser’s request. "
|
||||
"Published players contact the same server. Use a direct .cast URL; external "
|
||||
"servers must allow CORS."
|
||||
msgstr ""
|
||||
"有效的录制文件 URL 会自动加载预览,重新打开编辑器时也一样。文件所在服务器会收到浏览器请求,发布后的播放器也会访问该服务器。请使用 .cast "
|
||||
"文件直链;外部服务器需允许跨域请求(CORS)。"
|
||||
|
||||
#: src/edit.js:165
|
||||
msgid "Add a caption…"
|
||||
msgstr "添加说明文字…"
|
||||
|
||||
#: asciicast-player.php:1
|
||||
msgid ""
|
||||
"Add interactive terminal recordings to posts and pages with a block or "
|
||||
"shortcode."
|
||||
msgstr "通过区块或简码在文章和页面中添加可交互的终端录屏。"
|
||||
|
||||
#: src/edit.js:132
|
||||
msgid "Always show"
|
||||
msgstr "始终显示"
|
||||
|
||||
#: src/edit.js:128
|
||||
msgid "Appearance"
|
||||
msgstr "外观"
|
||||
|
||||
#: src/edit.js:147
|
||||
msgid "Apply URL"
|
||||
msgstr "应用 URL"
|
||||
|
||||
#: src/edit.js:163
|
||||
#: asciicast-player.php:1
|
||||
msgid "Asciicast Player"
|
||||
msgstr "Asciicast 播放器"
|
||||
|
||||
#: src/edit.js:73
|
||||
msgid "Asciinema"
|
||||
msgstr "Asciinema"
|
||||
|
||||
#: src/edit.js:123
|
||||
msgid "Autoplay on published page"
|
||||
msgstr "在发布后的页面自动播放"
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Center"
|
||||
msgstr "居中"
|
||||
|
||||
#: src/edit.js:154
|
||||
msgid "Choose an Asciicast (.cast) file from the Media Library."
|
||||
msgstr "请从媒体库选择 Asciicast(.cast)文件。"
|
||||
|
||||
#: src/edit.js:150
|
||||
msgid "Choose an Asciicast recording"
|
||||
msgstr "选择 Asciicast 录制文件"
|
||||
|
||||
#: src/edit.js:151
|
||||
msgid "Choose recording"
|
||||
msgstr "选择录制文件"
|
||||
|
||||
#: src/edit.js:104
|
||||
msgid "Close"
|
||||
msgstr "关闭"
|
||||
|
||||
#: src/edit.js:12
|
||||
msgid "Columns"
|
||||
msgstr "列数"
|
||||
|
||||
#: src/edit.js:81
|
||||
msgid "Custom"
|
||||
msgstr "自定义"
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid "Custom width"
|
||||
msgstr "自定义宽度"
|
||||
|
||||
#: src/edit.js:113
|
||||
msgid "Display"
|
||||
msgstr "显示"
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Display alignment"
|
||||
msgstr "对齐方式"
|
||||
|
||||
#: src/edit.js:117
|
||||
msgid ""
|
||||
"Display width scales the recording without changing its terminal columns or "
|
||||
"rows. Add a caption directly below the player."
|
||||
msgstr "显示宽度只缩放画面,不改变终端行列数。可在播放器下方直接添加说明文字。"
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid ""
|
||||
"Enter a positive width with a unit, such as 480px or 65%. The last valid "
|
||||
"width is kept."
|
||||
msgstr "请输入带单位的正数宽度,例如 480px 或 65%。将保留上一次有效的宽度。"
|
||||
|
||||
#: src/edit.js:163
|
||||
msgid ""
|
||||
"Enter a recording URL to load its preview automatically. Playback starts "
|
||||
"only when you press play."
|
||||
msgstr "输入录制文件 URL 后会自动加载预览,点击播放才会开始播放。"
|
||||
|
||||
#: src/edit.js:155
|
||||
msgid "Enter an HTTP(S) recording URL or a path starting with a single /."
|
||||
msgstr "请输入 HTTP(S) 录制文件 URL,或以单个 / 开头的路径。"
|
||||
|
||||
#: src/edit.js:91
|
||||
msgid "Example terminal recording"
|
||||
msgstr "终端录屏示例"
|
||||
|
||||
#: src/edit.js:135
|
||||
msgid "Fit"
|
||||
msgstr "缩放方式"
|
||||
|
||||
#: src/edit.js:12
|
||||
#: src/edit.js:13
|
||||
msgid "From recording"
|
||||
msgstr "使用录制尺寸"
|
||||
|
||||
#: src/edit.js:89
|
||||
msgid "Height (legacy)"
|
||||
msgstr "按高度缩放(旧版)"
|
||||
|
||||
#: src/edit.js:135
|
||||
msgid "Height-based fitting requires a fixed container height in your site CSS."
|
||||
msgstr "按高度缩放需要在站点 CSS 中设置固定的容器高度。"
|
||||
|
||||
#: src/edit.js:167
|
||||
msgid ""
|
||||
"Height-based previews use the shortcode’s fixed height when available, or a "
|
||||
"320px editor frame. Published height still comes from your container style."
|
||||
msgstr "按高度缩放的预览会使用简码中的固定高度;未设置时使用 320px 的编辑器预览高度。发布后的高度仍由容器样式决定。"
|
||||
|
||||
#: src/edit.js:138
|
||||
msgid "Help"
|
||||
msgstr "帮助"
|
||||
|
||||
#: src/edit.js:133
|
||||
msgid "Hide"
|
||||
msgstr "隐藏"
|
||||
|
||||
#: src/edit.js:126
|
||||
msgid "Idle time limit (seconds)"
|
||||
msgstr "最长空闲时间(秒)"
|
||||
|
||||
#: src/preview.js:92
|
||||
msgid "Interactive terminal recording preview"
|
||||
msgstr "可交互的终端录屏预览"
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Left"
|
||||
msgstr "左对齐"
|
||||
|
||||
#: src/preview.js:90
|
||||
msgid "Loading recording…"
|
||||
msgstr "正在加载录制文件…"
|
||||
|
||||
#: src/edit.js:124
|
||||
msgid ""
|
||||
"Loads the recording before the visitor presses play. The editor preview "
|
||||
"always preloads a valid recording URL."
|
||||
msgstr "在访客点击播放前加载录制文件。编辑器预览始终会预加载有效的录制文件 URL。"
|
||||
|
||||
#: src/edit.js:122
|
||||
msgid "Loop playback"
|
||||
msgstr "循环播放"
|
||||
|
||||
#: src/edit.js:87
|
||||
msgid "Original size"
|
||||
msgstr "原始大小"
|
||||
|
||||
#: src/edit.js:15
|
||||
msgid ""
|
||||
"Placeholders show the recording’s original columns and rows once loaded. "
|
||||
"Leave blank to follow its terminal size and recorded resize events. These "
|
||||
"overrides change the character grid, not the display width, and may alter "
|
||||
"or crop the layout."
|
||||
msgstr "加载后,占位提示会显示录制文件的原始行列数。留空可使用录制尺寸,并跟随录制中的尺寸变化。手动设置会改变字符网格,而非显示宽度,可能影响排版或裁切内容。"
|
||||
|
||||
#: src/edit.js:120
|
||||
msgid "Playback"
|
||||
msgstr "播放"
|
||||
|
||||
#: src/edit.js:121
|
||||
msgid "Playback speed"
|
||||
msgstr "播放速度"
|
||||
|
||||
#: src/edit.js:130
|
||||
msgid "Player controls"
|
||||
msgstr "播放控制栏"
|
||||
|
||||
#: src/edit.js:114
|
||||
msgid "Player width"
|
||||
msgstr "播放器宽度"
|
||||
|
||||
#: src/edit.js:124
|
||||
msgid "Preload on published page"
|
||||
msgstr "在发布后的页面预加载"
|
||||
|
||||
#: src/edit.js:165
|
||||
msgid "Recording caption"
|
||||
msgstr "录屏说明文字"
|
||||
|
||||
#: src/edit.js:74
|
||||
msgid "Recording theme (automatic)"
|
||||
msgstr "录制文件主题(自动)"
|
||||
|
||||
#: src/edit.js:146
|
||||
msgid "Recording URL"
|
||||
msgstr "录制文件 URL"
|
||||
|
||||
#: src/preview.js:91
|
||||
msgid "Retry preview"
|
||||
msgstr "重试预览"
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Right"
|
||||
msgstr "右对齐"
|
||||
|
||||
#: src/edit.js:13
|
||||
msgid "Rows"
|
||||
msgstr "行数"
|
||||
|
||||
#: src/edit.js:126
|
||||
msgid "Shorten long pauses. Use 0 to keep the recording’s default."
|
||||
msgstr "缩短过长的停顿。设为 0 可保留录制文件的默认设置。"
|
||||
|
||||
#: src/edit.js:131
|
||||
msgid "Show on interaction"
|
||||
msgstr "交互时显示"
|
||||
|
||||
#: src/edit.js:125
|
||||
msgid "Start at (seconds)"
|
||||
msgstr "起始时间(秒)"
|
||||
|
||||
#: src/edit.js:99
|
||||
#: src/edit.js:101
|
||||
#: src/edit.js:110
|
||||
msgid "Terminal size"
|
||||
msgstr "终端尺寸"
|
||||
|
||||
#: src/edit.js:102
|
||||
msgid "Terminal size (columns × rows)"
|
||||
msgstr "终端尺寸(列数 × 行数)"
|
||||
|
||||
#: src/edit.js:136
|
||||
msgid ""
|
||||
"The custom container style from your shortcode is preserved on the "
|
||||
"published page."
|
||||
msgstr "发布后的页面会保留简码中的自定义容器样式。"
|
||||
|
||||
#: src/edit.js:123
|
||||
msgid "The editor preview always waits for you to press play."
|
||||
msgstr "编辑器预览始终需要点击播放后才会开始。"
|
||||
|
||||
#: src/preview.js:77
|
||||
msgid ""
|
||||
"The local player could not start. Try again, or check that the plugin’s "
|
||||
"built assets are installed."
|
||||
msgstr "本地播放器无法启动。请重试,或检查插件的构建资源是否已安装。"
|
||||
|
||||
#: src/recording-errors.js:14
|
||||
msgid ""
|
||||
"The recording is taking too long to load. Check your connection and try "
|
||||
"again."
|
||||
msgstr "录制文件加载超时。请检查网络连接后重试。"
|
||||
|
||||
#: src/edit.js:129
|
||||
msgid "Theme"
|
||||
msgstr "主题"
|
||||
|
||||
#: src/recording-errors.js:8
|
||||
msgid "This recording contains a line that exceeds the size limit."
|
||||
msgstr "该录屏包含超出大小限制的行。"
|
||||
|
||||
#: src/recording-errors.js:15
|
||||
msgid "This recording contains an invalid or unsupported timestamp."
|
||||
msgstr "该录屏包含无效或不支持的时间戳。"
|
||||
|
||||
#: src/recording-errors.js:9
|
||||
msgid "This recording contains too many events."
|
||||
msgstr "该录屏包含过多事件。"
|
||||
|
||||
#: src/recording-errors.js:10
|
||||
msgid "This recording contains too many markers."
|
||||
msgstr "该录屏包含过多时间标记。"
|
||||
|
||||
#: src/recording-errors.js:7
|
||||
msgid "This recording exceeds the file size limit."
|
||||
msgstr "该录屏超过文件大小限制。"
|
||||
|
||||
#: src/recording-errors.js:13
|
||||
msgid "This recording is too complex to load safely."
|
||||
msgstr "该录屏结构过于复杂,无法安全加载。"
|
||||
|
||||
#: src/recording-errors.js:11
|
||||
msgid ""
|
||||
"This recording requests terminal dimensions that exceed the supported "
|
||||
"limits."
|
||||
msgstr "该录屏请求的终端尺寸超出支持范围。"
|
||||
|
||||
#: src/recording-errors.js:12
|
||||
msgid "This recording requests too many terminal cells."
|
||||
msgstr "该录屏请求的终端单元格过多。"
|
||||
|
||||
#: src/preview.js:67
|
||||
#: src/recording-errors.js:20
|
||||
msgid ""
|
||||
"Unable to load the recording. Check the URL, file format, and the source "
|
||||
"server’s CORS permissions."
|
||||
msgstr "无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。"
|
||||
|
||||
#: src/recording-errors.js:19
|
||||
msgid ""
|
||||
"Unable to load this terminal recording. The file may be unavailable, "
|
||||
"invalid, or blocked by the source server’s CORS policy."
|
||||
msgstr "无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。"
|
||||
|
||||
#: includes/uploads.php:354
|
||||
msgid ""
|
||||
"Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; "
|
||||
"v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, "
|
||||
"1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure)."
|
||||
msgstr ""
|
||||
"请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 "
|
||||
"个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。"
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid ""
|
||||
"Use a CSS length, such as 480px or 65%. The player stays within its "
|
||||
"available space."
|
||||
msgstr "使用 CSS 长度,例如 480px 或 65%。播放器不会超出可用空间。"
|
||||
|
||||
#: src/edit.js:16
|
||||
msgid "Use recording size"
|
||||
msgstr "使用录制尺寸"
|
||||
|
||||
#: src/edit.js:140
|
||||
msgid ""
|
||||
"Use the player controls to play, pause, and seek. Autoplay is disabled only "
|
||||
"in the editor."
|
||||
msgstr "使用播放器控件播放、暂停和跳转。仅编辑器预览禁用自动播放。"
|
||||
|
||||
#: src/edit.js:86
|
||||
msgid "Width"
|
||||
msgstr "按宽度缩放"
|
||||
|
||||
#: src/edit.js:89
|
||||
msgid "Width and height (legacy)"
|
||||
msgstr "按宽高缩放(旧版)"
|
||||
|
||||
#: includes/uploads.php:352
|
||||
msgid "You are not allowed to upload Asciicast files."
|
||||
msgstr "你没有上传 Asciicast 文件的权限。"
|
||||
|
||||
#: src/index.js:19
|
||||
#: block.json:1
|
||||
msgctxt "block description"
|
||||
msgid ""
|
||||
"Embed and preview a terminal recording with the locally bundled asciinema "
|
||||
"player."
|
||||
msgstr "使用本地附带的 asciinema 播放器嵌入和预览终端录屏。"
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "asciinema"
|
||||
msgstr "asciinema"
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "recording"
|
||||
msgstr "录屏"
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "terminal"
|
||||
msgstr "终端"
|
||||
|
||||
#: src/index.js:18
|
||||
#: block.json:1
|
||||
msgctxt "block title"
|
||||
msgid "Asciicast Player"
|
||||
msgstr "Asciicast 播放器"
|
||||
@@ -0,0 +1,395 @@
|
||||
msgid ""
|
||||
msgstr ""
|
||||
"Project-Id-Version: wp-asciiplayer 1.1.0-dev\n"
|
||||
"MIME-Version: 1.0\n"
|
||||
"Content-Type: text/plain; charset=utf-8\n"
|
||||
"Content-Transfer-Encoding: 8bit\n"
|
||||
"X-Domain: wp-asciiplayer\n"
|
||||
|
||||
#: src/edit.js:91
|
||||
msgid "A terminal recording, right in your post."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:139
|
||||
msgid ""
|
||||
"A valid recording URL loads its preview automatically, including when "
|
||||
"reopening this editor. That server receives your browser’s request. "
|
||||
"Published players contact the same server. Use a direct .cast URL; external "
|
||||
"servers must allow CORS."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:165
|
||||
msgid "Add a caption…"
|
||||
msgstr ""
|
||||
|
||||
#: asciicast-player.php:1
|
||||
msgid ""
|
||||
"Add interactive terminal recordings to posts and pages with a block or "
|
||||
"shortcode."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:132
|
||||
msgid "Always show"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:128
|
||||
msgid "Appearance"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:147
|
||||
msgid "Apply URL"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:163
|
||||
#: asciicast-player.php:1
|
||||
msgid "Asciicast Player"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:73
|
||||
msgid "Asciinema"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:123
|
||||
msgid "Autoplay on published page"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Center"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:154
|
||||
msgid "Choose an Asciicast (.cast) file from the Media Library."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:150
|
||||
msgid "Choose an Asciicast recording"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:151
|
||||
msgid "Choose recording"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:104
|
||||
msgid "Close"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:12
|
||||
msgid "Columns"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:81
|
||||
msgid "Custom"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid "Custom width"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:113
|
||||
msgid "Display"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Display alignment"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:117
|
||||
msgid ""
|
||||
"Display width scales the recording without changing its terminal columns or "
|
||||
"rows. Add a caption directly below the player."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid ""
|
||||
"Enter a positive width with a unit, such as 480px or 65%. The last valid "
|
||||
"width is kept."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:163
|
||||
msgid ""
|
||||
"Enter a recording URL to load its preview automatically. Playback starts "
|
||||
"only when you press play."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:155
|
||||
msgid "Enter an HTTP(S) recording URL or a path starting with a single /."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:91
|
||||
msgid "Example terminal recording"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:135
|
||||
msgid "Fit"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:12
|
||||
#: src/edit.js:13
|
||||
msgid "From recording"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:89
|
||||
msgid "Height (legacy)"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:135
|
||||
msgid "Height-based fitting requires a fixed container height in your site CSS."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:167
|
||||
msgid ""
|
||||
"Height-based previews use the shortcode’s fixed height when available, or a "
|
||||
"320px editor frame. Published height still comes from your container style."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:138
|
||||
msgid "Help"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:133
|
||||
msgid "Hide"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:126
|
||||
msgid "Idle time limit (seconds)"
|
||||
msgstr ""
|
||||
|
||||
#: src/preview.js:92
|
||||
msgid "Interactive terminal recording preview"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Left"
|
||||
msgstr ""
|
||||
|
||||
#: src/preview.js:90
|
||||
msgid "Loading recording…"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:124
|
||||
msgid ""
|
||||
"Loads the recording before the visitor presses play. The editor preview "
|
||||
"always preloads a valid recording URL."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:122
|
||||
msgid "Loop playback"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:87
|
||||
msgid "Original size"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:15
|
||||
msgid ""
|
||||
"Placeholders show the recording’s original columns and rows once loaded. "
|
||||
"Leave blank to follow its terminal size and recorded resize events. These "
|
||||
"overrides change the character grid, not the display width, and may alter "
|
||||
"or crop the layout."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:120
|
||||
msgid "Playback"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:121
|
||||
msgid "Playback speed"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:130
|
||||
msgid "Player controls"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:114
|
||||
msgid "Player width"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:124
|
||||
msgid "Preload on published page"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:165
|
||||
msgid "Recording caption"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:74
|
||||
msgid "Recording theme (automatic)"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:146
|
||||
msgid "Recording URL"
|
||||
msgstr ""
|
||||
|
||||
#: src/preview.js:91
|
||||
msgid "Retry preview"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:116
|
||||
msgid "Right"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:13
|
||||
msgid "Rows"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:126
|
||||
msgid "Shorten long pauses. Use 0 to keep the recording’s default."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:131
|
||||
msgid "Show on interaction"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:125
|
||||
msgid "Start at (seconds)"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:99
|
||||
#: src/edit.js:101
|
||||
#: src/edit.js:110
|
||||
msgid "Terminal size"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:102
|
||||
msgid "Terminal size (columns × rows)"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:136
|
||||
msgid ""
|
||||
"The custom container style from your shortcode is preserved on the "
|
||||
"published page."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:123
|
||||
msgid "The editor preview always waits for you to press play."
|
||||
msgstr ""
|
||||
|
||||
#: src/preview.js:77
|
||||
msgid ""
|
||||
"The local player could not start. Try again, or check that the plugin’s "
|
||||
"built assets are installed."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:14
|
||||
msgid ""
|
||||
"The recording is taking too long to load. Check your connection and try "
|
||||
"again."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:129
|
||||
msgid "Theme"
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:8
|
||||
msgid "This recording contains a line that exceeds the size limit."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:15
|
||||
msgid "This recording contains an invalid or unsupported timestamp."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:9
|
||||
msgid "This recording contains too many events."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:10
|
||||
msgid "This recording contains too many markers."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:7
|
||||
msgid "This recording exceeds the file size limit."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:13
|
||||
msgid "This recording is too complex to load safely."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:11
|
||||
msgid ""
|
||||
"This recording requests terminal dimensions that exceed the supported "
|
||||
"limits."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:12
|
||||
msgid "This recording requests too many terminal cells."
|
||||
msgstr ""
|
||||
|
||||
#: src/preview.js:67
|
||||
#: src/recording-errors.js:20
|
||||
msgid ""
|
||||
"Unable to load the recording. Check the URL, file format, and the source "
|
||||
"server’s CORS permissions."
|
||||
msgstr ""
|
||||
|
||||
#: src/recording-errors.js:19
|
||||
msgid ""
|
||||
"Unable to load this terminal recording. The file may be unavailable, "
|
||||
"invalid, or blocked by the source server’s CORS policy."
|
||||
msgstr ""
|
||||
|
||||
#: includes/uploads.php:361
|
||||
msgid ""
|
||||
"Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; "
|
||||
"v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, "
|
||||
"1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure)."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:115
|
||||
msgid ""
|
||||
"Use a CSS length, such as 480px or 65%. The player stays within its "
|
||||
"available space."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:16
|
||||
msgid "Use recording size"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:140
|
||||
msgid ""
|
||||
"Use the player controls to play, pause, and seek. Autoplay is disabled only "
|
||||
"in the editor."
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:86
|
||||
msgid "Width"
|
||||
msgstr ""
|
||||
|
||||
#: src/edit.js:89
|
||||
msgid "Width and height (legacy)"
|
||||
msgstr ""
|
||||
|
||||
#: includes/uploads.php:359
|
||||
msgid "You are not allowed to upload Asciicast files."
|
||||
msgstr ""
|
||||
|
||||
#: src/index.js:19
|
||||
#: block.json:1
|
||||
msgctxt "block description"
|
||||
msgid ""
|
||||
"Embed and preview a terminal recording with the locally bundled asciinema "
|
||||
"player."
|
||||
msgstr ""
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "asciinema"
|
||||
msgstr ""
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "recording"
|
||||
msgstr ""
|
||||
|
||||
#: src/index.js:20
|
||||
#: block.json:1
|
||||
msgctxt "block keyword"
|
||||
msgid "terminal"
|
||||
msgstr ""
|
||||
|
||||
#: src/index.js:18
|
||||
#: block.json:1
|
||||
msgctxt "block title"
|
||||
msgid "Asciicast Player"
|
||||
msgstr ""
|
||||
Generated
+179
-59
@@ -1,23 +1,26 @@
|
||||
{
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.0-dev",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.0-dev",
|
||||
"license": "GPL-3.0-only",
|
||||
"dependencies": {
|
||||
"asciinema-player": "3.17.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@babel/parser": "8.0.7",
|
||||
"@playwright/test": "1.64.0",
|
||||
"@wordpress/env": "11.17.0",
|
||||
"@wordpress/scripts": "36.1.0"
|
||||
"@wordpress/scripts": "36.1.0",
|
||||
"gettext-parser": "9.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=22.22.2"
|
||||
"node": "^24.18.0 || >=26.0.0",
|
||||
"npm": ">=11.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/code-frame": {
|
||||
@@ -76,6 +79,22 @@
|
||||
"url": "https://opencollective.com/babel"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/core/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/generator": {
|
||||
"version": "7.29.8",
|
||||
"resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.8.tgz",
|
||||
@@ -93,6 +112,22 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/generator/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helper-annotate-as-pure": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz",
|
||||
@@ -369,19 +404,53 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"version": "8.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-8.0.7.tgz",
|
||||
"integrity": "sha512-UkDwEbPO1px2JQSrdh4qIgaH1JgG7GO/pFeJkpxhDxIETkT/QvGpnigXIw75ViHYPtIgKITmVUJqLjiO+JuWjA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
"@babel/types": "^8.0.6"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
"node": "^22.18.0 || >=24.11.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser/node_modules/@babel/helper-string-parser": {
|
||||
"version": "8.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-8.0.6.tgz",
|
||||
"integrity": "sha512-+6HYEBnsDRZHJtUTAEfMQd0zMDqdFHS7C+5vAsEZqBUr3vEMWOWlHJ0Jz1gS8jJIlCvLsuA6ivmeoqzH936YcA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^22.18.0 || >=24.11.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser/node_modules/@babel/helper-validator-identifier": {
|
||||
"version": "8.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-8.0.6.tgz",
|
||||
"integrity": "sha512-HYx0YmuchRxRSpnjvcNffnPS8DCauKNmnumIuHG3jnQAVewRA7kfJGwF13ayEpSZs7s4R/oBH4eppuXcAQd5JQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": "^22.18.0 || >=24.11.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/parser/node_modules/@babel/types": {
|
||||
"version": "8.0.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-8.0.6.tgz",
|
||||
"integrity": "sha512-c+xgSWboV2pdwXP67BUWDVRHi2BO5Q3KwxyFVs7taVTY+fsK47/L51ZXQoV9rozHJDNHvJ4v4WEsI/IlxV2l2A==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/helper-string-parser": "^8.0.6",
|
||||
"@babel/helper-validator-identifier": "^8.0.6"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^22.18.0 || >=24.11.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/plugin-bugfix-firefox-class-in-computed-class-key": {
|
||||
@@ -1741,6 +1810,22 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/template/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/traverse": {
|
||||
"version": "7.29.10",
|
||||
"resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.10.tgz",
|
||||
@@ -1760,6 +1845,22 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/traverse/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/types": {
|
||||
"version": "7.29.8",
|
||||
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
|
||||
@@ -5525,13 +5626,13 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@simple-git/argv-parser": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@simple-git/argv-parser/-/argv-parser-1.1.1.tgz",
|
||||
"integrity": "sha512-Q9lBcfQ+VQCpQqGJFHe5yooOS5hGdLFFbJ5R+R5aDsnkPCahtn1hSkMcORX65J2Z5lxSkD0lQorMsncuBQxYUw==",
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/@simple-git/argv-parser/-/argv-parser-2.0.1.tgz",
|
||||
"integrity": "sha512-M++IaVWrN+vYalilOHfwvT2IL3wYZtVEBQpmX6DLSOJLtxbZ+SUeIDE3IiPogzhPACLajwtxfa5rp+ZX1FczzQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@simple-git/args-pathspec": "^1.0.3"
|
||||
"@simple-git/args-pathspec": "^1.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@sindresorhus/base62": {
|
||||
@@ -7400,6 +7501,17 @@
|
||||
"node": ">=18.12.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wordpress/i18n/node_modules/gettext-parser": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/gettext-parser/-/gettext-parser-1.4.0.tgz",
|
||||
"integrity": "sha512-sedZYLHlHeBop/gZ1jdg59hlUEcpcZJofLq2JFwJT1zTqAU3l2wFv6IsuwFHGqbiT9DWzMUW4/em2+hspnmMMA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"encoding": "^0.1.12",
|
||||
"safe-buffer": "^5.1.1"
|
||||
}
|
||||
},
|
||||
"node_modules/@wordpress/is-shallow-equal": {
|
||||
"version": "5.57.0",
|
||||
"resolved": "https://registry.npmjs.org/@wordpress/is-shallow-equal/-/is-shallow-equal-5.57.0.tgz",
|
||||
@@ -7895,6 +8007,22 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@wordpress/theme/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@wordpress/undo-manager": {
|
||||
"version": "1.57.0",
|
||||
"resolved": "https://registry.npmjs.org/@wordpress/undo-manager/-/undo-manager-1.57.0.tgz",
|
||||
@@ -8907,23 +9035,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/body-parser/node_modules/qs": {
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
|
||||
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"es-define-property": "^1.0.1",
|
||||
"side-channel": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.6"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/bonjour-service": {
|
||||
"version": "1.4.4",
|
||||
"resolved": "https://registry.npmjs.org/bonjour-service/-/bonjour-service-1.4.4.tgz",
|
||||
@@ -11850,6 +11961,22 @@
|
||||
"eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-plugin-react-hooks/node_modules/@babel/parser": {
|
||||
"version": "7.29.9",
|
||||
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.9.tgz",
|
||||
"integrity": "sha512-CjXrNHTnvqBVqHgdBysY3vk2T8tpJHb5/RMeHJBTyVa9xgugCB0CJTx/3oO8RV2QRQP391RWpB7D6hLjm8V9uA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/types": "^7.29.8"
|
||||
},
|
||||
"bin": {
|
||||
"parser": "bin/babel-parser.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eslint-plugin-react/node_modules/balanced-match": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
|
||||
@@ -12840,14 +12967,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/gettext-parser": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/gettext-parser/-/gettext-parser-1.4.0.tgz",
|
||||
"integrity": "sha512-sedZYLHlHeBop/gZ1jdg59hlUEcpcZJofLq2JFwJT1zTqAU3l2wFv6IsuwFHGqbiT9DWzMUW4/em2+hspnmMMA==",
|
||||
"version": "9.1.1",
|
||||
"resolved": "https://registry.npmjs.org/gettext-parser/-/gettext-parser-9.1.1.tgz",
|
||||
"integrity": "sha512-ZLeqWPz9OMNrTgMuww0C22kkcNqis+e4059R94t7L7ERlZ2rUNpiDbaAUus+esBC6uBAQWbS9N+R5vJIJg//lw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"encoding": "^0.1.12",
|
||||
"safe-buffer": "^5.1.1"
|
||||
"content-type": "^1.0.5",
|
||||
"encoding": "^0.1.13"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/glob": {
|
||||
@@ -15440,9 +15570,9 @@
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/markdownlint-cli/node_modules/js-yaml": {
|
||||
"version": "5.2.3",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.2.3.tgz",
|
||||
"integrity": "sha512-n+mUVyUX5bVv7G/G2zyIHOhdxfuU1dY2NOFzTQUWiMUbFss8b57NFlgCCaggU78wSw5KVS9cllzeLyzyR+n5nw==",
|
||||
"version": "5.4.3",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-5.4.3.tgz",
|
||||
"integrity": "sha512-yzzNtgczwgoVHNigCyKTXcQJU4Y8t/ikU4UxXW0BvrLfHTGWZhsNcOT2s/a7vn81/4KqVnNmHjaUEPlvWnNwVw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
@@ -18717,9 +18847,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/qs": {
|
||||
"version": "6.15.3",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",
|
||||
"integrity": "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==",
|
||||
"version": "6.16.0",
|
||||
"resolved": "https://registry.npmjs.org/qs/-/qs-6.16.0.tgz",
|
||||
"integrity": "sha512-h6fhOIaRrID2CbEY2fqs+7t+UXZo+MLAnU5gRIq85uFtdiUPCdsApMlHhXogKVM4HM2DVbIjGNTTYH2OcmP1vA==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
@@ -18767,16 +18897,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/randombytes": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz",
|
||||
"integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safe-buffer": "^5.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/range-parser": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz",
|
||||
@@ -19841,13 +19961,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/serialize-javascript": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.2.tgz",
|
||||
"integrity": "sha512-Saa1xPByTTq2gdeFZYLLo+RFE35NHZkAbqZeWNd3BpzppeVisAqpDjcp8dyf6uIvEqJRd46jemmyA4iFIeVk8g==",
|
||||
"version": "7.0.5",
|
||||
"resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-7.0.5.tgz",
|
||||
"integrity": "sha512-F4LcB0UqUl1zErq+1nYEEzSHJnIwb3AF2XWB94b+afhrekOUijwooAYqFyRbjYkm2PAKBabx6oYv/xDxNi8IBw==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"randombytes": "^2.1.0"
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/seroval": {
|
||||
@@ -20291,9 +20411,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/smol-toml": {
|
||||
"version": "1.7.2",
|
||||
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.7.2.tgz",
|
||||
"integrity": "sha512-pXFZ9B2WinEPzxWkMmlYE/oYx2BP+qLrE95wP8tCuK901uLSMGdCb6QSr82z+wnhXkG4+cO+OMLbZB2Cn+97zw==",
|
||||
"version": "1.9.1",
|
||||
"resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",
|
||||
"integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==",
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause",
|
||||
"engines": {
|
||||
|
||||
+36
-6
@@ -1,21 +1,24 @@
|
||||
{
|
||||
"name": "wp-asciiplayer",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.0-dev",
|
||||
"private": true,
|
||||
"description": "Native WordPress asciicast block with real playback previews and compatible shortcodes",
|
||||
"type": "module",
|
||||
"license": "GPL-3.0-only",
|
||||
"engines": {
|
||||
"node": ">=22.22.2"
|
||||
"node": "^24.18.0 || >=26.0.0",
|
||||
"npm": ">=11.16.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "wp-scripts build --config webpack.config.cjs && node scripts/vendor.mjs && node scripts/verify-build.mjs",
|
||||
"build": "wp-scripts build --config webpack.config.cjs && node scripts/vendor.mjs && npm run i18n && node scripts/verify-build.mjs",
|
||||
"start": "wp-scripts start --config webpack.config.cjs",
|
||||
"test": "node --test tests/js/*.test.js",
|
||||
"test": "npm run i18n:check && node --test tests/js/*.test.js",
|
||||
"test:php": "php tests/php/run.php",
|
||||
"test:e2e": "playwright test",
|
||||
"wp-env": "wp-env",
|
||||
"package": "node scripts/package.mjs"
|
||||
"package": "node scripts/package.mjs",
|
||||
"i18n": "node scripts/i18n.mjs",
|
||||
"i18n:check": "node scripts/i18n.mjs --check"
|
||||
},
|
||||
"dependencies": {
|
||||
"asciinema-player": "3.17.0"
|
||||
@@ -23,6 +26,33 @@
|
||||
"devDependencies": {
|
||||
"@playwright/test": "1.64.0",
|
||||
"@wordpress/env": "11.17.0",
|
||||
"@wordpress/scripts": "36.1.0"
|
||||
"@wordpress/scripts": "36.1.0",
|
||||
"@babel/parser": "8.0.7",
|
||||
"gettext-parser": "9.1.1"
|
||||
},
|
||||
"cssnano": {
|
||||
"preset": [
|
||||
"default",
|
||||
{
|
||||
"discardComments": {
|
||||
"removeAll": false
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"overrides": {
|
||||
"copy-webpack-plugin": {
|
||||
"serialize-javascript": "7.0.5"
|
||||
},
|
||||
"markdownlint-cli": {
|
||||
"js-yaml": "5.4.3",
|
||||
"smol-toml": "1.9.1"
|
||||
},
|
||||
"express": {
|
||||
"qs": "6.16.0"
|
||||
},
|
||||
"simple-git": {
|
||||
"@simple-git/argv-parser": "2.0.1"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-18
@@ -4,7 +4,7 @@ Tags: asciicast, asciiplayer, asciinema, terminal, block
|
||||
Requires at least: 6.3
|
||||
Tested up to: 7.1
|
||||
Requires PHP: 7.4
|
||||
Stable tag: 1.1.0
|
||||
Stable tag: 1.1.0-dev
|
||||
License: GPL-3.0-only
|
||||
License URI: https://www.gnu.org/licenses/gpl-3.0.html
|
||||
|
||||
@@ -17,14 +17,15 @@ Insert an Asciicast Player block, apply a recording-file URL, and play it direct
|
||||
* Locally bundled asciinema-player, JavaScript, CSS and WebAssembly.
|
||||
* Native block-editor controls and iframe-aware interactive preview.
|
||||
* Compatible shortcode rendering in posts and pages.
|
||||
* Explicit editor preview loading and clear loading/failure feedback.
|
||||
* No account, analytics, remote proxy, custom post type or extra upload permissions.
|
||||
* Automatic preview loading for valid URLs, debounced editing, and clear loading/failure feedback.
|
||||
* Media Library selection and validated .cast uploads using existing WordPress upload permissions.
|
||||
* No account, analytics, remote proxy, custom post type or extra upload capabilities.
|
||||
|
||||
The source and reproducible build instructions are included in the ZIP and available at https://github.com/LamGC/wp-asciiplayer . Third-party licenses are in THIRD-PARTY-NOTICES.md and licenses/.
|
||||
|
||||
= External recordings and privacy =
|
||||
|
||||
The plugin itself uses no external runtime service. When you choose an external recording URL, the visitor's browser requests that URL directly. The host may receive IP address, browser request metadata and a referrer according to browser/site policy. Applying a URL or loading a preview in the editor makes the same request. Choose a trusted host and consult its privacy policy. Use a same-site HTTPS recording URL to avoid third-party requests. Review terminal output for sensitive data before publishing.
|
||||
The plugin itself uses no external runtime service. When you choose an external recording URL, the visitor's browser requests that URL directly. The host may receive IP address, browser request metadata and a referrer according to browser/site policy. A valid URL automatically loads the editor preview and makes the same request, including when reopening a saved block. Choose a trusted host and consult its privacy policy. Use a same-site HTTPS recording URL to avoid third-party requests. Review terminal output for sensitive data before publishing.
|
||||
|
||||
== Installation ==
|
||||
|
||||
@@ -44,6 +45,10 @@ No. The [asciiplayer] shortcode remains available. You can explicitly convert su
|
||||
|
||||
Use a recording-file URL rather than a share-page URL. The remote server must permit cross-origin (CORS) requests. HTTPS sites may block HTTP recordings. Network errors, invalid formats or missing files can also prevent playback. The plugin does not work around these restrictions through a server proxy.
|
||||
|
||||
= What recording limits apply? =
|
||||
|
||||
Uploads and browser playback, including remote files, are bounded to 32 MiB (v1: 2 MiB), 100,000 events or stream lines, 256 KiB per JSONL line, 1,000 markers, 1,000 columns/rows per axis and 40,000 terminal cells. Recording timelines and supported time values are capped at 2,147,483,647 milliseconds (about 24.85 days). Browser playback additionally bounds cumulative time divided by speed; at 0.01x, source time is limited to about 5.97 hours. Relative intervals are accumulated in the player's millisecond order, and start/idle/poster times are checked. Initial dimensions, resize events and effective overrides are checked. JSON nesting and structure are checked before decoding. Existing files/posts are not rewritten; unusually large recordings may need splitting or simplification. The browser validates one request before playback, without an extra metadata request or a server proxy.
|
||||
|
||||
= Are player resources loaded from a CDN? =
|
||||
|
||||
No. The JavaScript, CSS and WebAssembly ship with the plugin. The previous ap_use_local_resources setting is no longer used.
|
||||
@@ -52,18 +57,6 @@ No. The JavaScript, CSS and WebAssembly ship with the plugin. The previous ap_us
|
||||
|
||||
Existing shortcodes work in the Classic Editor. The new visual controls and inline playback preview are for the block editor.
|
||||
|
||||
== Changelog ==
|
||||
= Which languages are included? =
|
||||
|
||||
= 1.1.0 =
|
||||
* Add a native block with typed controls and interactive, iframe-aware preview.
|
||||
* Preserve shortcode support and normalize historical parameter names and types.
|
||||
* Escape output, constrain recording URLs, and filter custom styles.
|
||||
* Bundle player 3.17.0 locally and add reproducible build/install ZIP tooling.
|
||||
* Improve asset loading for posts, pages and render-time shortcode use.
|
||||
* Add unit and real WordPress browser integration tests.
|
||||
|
||||
= 1.0.0 =
|
||||
* Set the version attribute for resource files and add documentation.
|
||||
|
||||
= 0.1.0 =
|
||||
* First available version; asciinema-player 3.4.0.
|
||||
English (en_US fallback) and Simplified Chinese (zh_CN) are bundled and work offline. Plugin-owned editor controls follow the WordPress user language; public pages follow the site language. Set these in Users > Profile and Settings > General. Other Chinese locales, including zh_TW, are not mapped to zh_CN. Recording output and author captions are never translated. The upstream player's own controls and help remain English.
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
/** Deterministic gettext catalogs. English msgids are the en_US fallback. */
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import assert from 'node:assert/strict';
|
||||
import { parse } from '@babel/parser';
|
||||
import gettext from 'gettext-parser';
|
||||
|
||||
const domain = 'wp-asciiplayer';
|
||||
const version = JSON.parse(fs.readFileSync('package.json')).version;
|
||||
const entries = new Map();
|
||||
function add(msgid, context, file, line) {
|
||||
assert.equal(typeof msgid, 'string', `Static gettext string required: ${file}:${line}`);
|
||||
const key = `${context || ''}\u0004${msgid}`;
|
||||
if (!entries.has(key)) entries.set(key, { msgid, msgctxt: context || undefined, msgstr: [''], comments: { reference: '' } });
|
||||
const entry = entries.get(key);
|
||||
entry.comments.reference += `${entry.comments.reference ? '\n' : ''}${file}:${line}`;
|
||||
}
|
||||
function walk(node, file) {
|
||||
if (!node || typeof node !== 'object') return;
|
||||
if (node.type === 'CallExpression' && ['__', '_x', '_n', '_nx'].includes(node.callee?.name)) {
|
||||
const name = node.callee.name;
|
||||
assert.ok(['__', '_x'].includes(name), `Add plural extraction before using ${name}: ${file}`);
|
||||
const args = node.arguments;
|
||||
assert.equal(args[name === '__' ? 1 : 2]?.value, domain, `Explicit textdomain required: ${file}`);
|
||||
assert.equal(args[0]?.type, 'StringLiteral', `Literal gettext message required: ${file}`);
|
||||
if (name === '_x') assert.equal(args[1]?.type, 'StringLiteral');
|
||||
add(args[0].value, name === '_x' ? args[1].value : '', file, node.loc.start.line);
|
||||
}
|
||||
for (const value of Object.values(node)) {
|
||||
if (Array.isArray(value)) for (const child of value) walk(child, file);
|
||||
else if (value && typeof value === 'object') walk(value, file);
|
||||
}
|
||||
}
|
||||
for (const file of fs.readdirSync('src').filter((name) => name.endsWith('.js')).map((name) => `src/${name}`)) {
|
||||
walk(parse(fs.readFileSync(file, 'utf8'), { sourceType: 'module', plugins: ['jsx'] }), file);
|
||||
}
|
||||
for (const file of ['asciicast-player.php', ...fs.readdirSync('includes').filter((name) => name.endsWith('.php')).map((name) => `includes/${name}`)]) {
|
||||
const source = fs.readFileSync(file, 'utf8');
|
||||
const calls = [...source.matchAll(/\b__\s*\(/g)];
|
||||
const matches = [...source.matchAll(/\b__\(\s*'((?:\\.|[^'\\])*)'\s*,\s*'wp-asciiplayer'\s*\)/g)];
|
||||
assert.equal(matches.length, calls.length, `Unsupported PHP gettext syntax in ${file}; extend extractor first.`);
|
||||
assert.ok(!/\b(?:_x|_n|_nx|_e|esc_html__|esc_attr__)\s*\(/.test(source), `Extend PHP extractor for new gettext functions: ${file}`);
|
||||
for (const match of matches) add(match[1].replace(/\\(['\\])/g, '$1'), '', file, source.slice(0, match.index).split('\n').length);
|
||||
}
|
||||
const pluginHeader = fs.readFileSync('asciicast-player.php', 'utf8');
|
||||
for (const label of ['Plugin Name', 'Description']) {
|
||||
const value = pluginHeader.match(new RegExp(` \* ${label}: (.+)`))?.[1];
|
||||
if (value) add(value, '', 'asciicast-player.php', 1);
|
||||
}
|
||||
const metadata = JSON.parse(fs.readFileSync('block.json'));
|
||||
for (const [field, context] of [['title', 'block title'], ['description', 'block description'], ['keywords', 'block keyword']]) {
|
||||
for (const value of [].concat(metadata[field])) add(value, context, 'block.json', 1);
|
||||
}
|
||||
const headers = { 'Project-Id-Version': `${domain} ${version}`, 'MIME-Version': '1.0', 'Content-Type': 'text/plain; charset=UTF-8', 'Content-Transfer-Encoding': '8bit', 'X-Domain': domain };
|
||||
const pot = { charset: 'utf-8', headers, translations: { '': {} } };
|
||||
for (const entry of [...entries.values()].sort((a, b) => `${a.msgctxt || ''}\u0004${a.msgid}`.localeCompare(`${b.msgctxt || ''}\u0004${b.msgid}`, 'en'))) {
|
||||
const context = entry.msgctxt || '';
|
||||
(pot.translations[context] ||= {})[entry.msgid] = entry;
|
||||
}
|
||||
fs.mkdirSync('languages', { recursive: true });
|
||||
const output = new Map([['languages/wp-asciiplayer.pot', gettext.po.compile(pot)]]);
|
||||
if (!process.argv.includes('--pot-only')) {
|
||||
const po = gettext.po.parse(fs.readFileSync('languages/wp-asciiplayer-zh_CN.po'));
|
||||
assert.equal(po.headers.Language, 'zh_CN');
|
||||
assert.match(po.headers['Plural-Forms'], /^nplurals=1;\s*plural=0;$/);
|
||||
const messages = { '': { domain, lang: 'zh_CN', 'plural-forms': 'nplurals=1; plural=0;' } };
|
||||
for (const entry of entries.values()) {
|
||||
const translation = po.translations[entry.msgctxt || '']?.[entry.msgid];
|
||||
assert.ok(translation?.msgstr?.[0], `Missing zh_CN translation: ${entry.msgid}`);
|
||||
assert.ok(!translation.comments?.flag?.includes('fuzzy'), `Fuzzy translation: ${entry.msgid}`);
|
||||
assert.ok(!translation.msgid_plural && translation.msgstr.length === 1, `Unexpected plural: ${entry.msgid}`);
|
||||
const placeholders = (text) => [...text.matchAll(/%(?:\d+\$)?[sdif]/g)].map((match) => match[0]).sort();
|
||||
assert.deepEqual(placeholders(translation.msgstr[0]), placeholders(entry.msgid), `Placeholder mismatch: ${entry.msgid}`);
|
||||
messages[entry.msgctxt ? `${entry.msgctxt}\u0004${entry.msgid}` : entry.msgid] = translation.msgstr;
|
||||
}
|
||||
output.set('languages/wp-asciiplayer-zh_CN.mo', gettext.mo.compile(po));
|
||||
const json = `${JSON.stringify({ domain, locale_data: { messages } }, null, 2)}\n`;
|
||||
for (const handle of ['lamgc-asciiplayer-editor', 'lamgc-asciiplayer-view']) output.set(`languages/wp-asciiplayer-zh_CN-${handle}.json`, json);
|
||||
}
|
||||
for (const [file, content] of output) {
|
||||
if (process.argv.includes('--check')) assert.deepEqual(fs.readFileSync(file), Buffer.from(content), `Stale catalog: ${file}; run npm run i18n.`);
|
||||
else fs.writeFileSync(file, content);
|
||||
}
|
||||
console.log(`Verified ${entries.size} gettext entries; ${output.size} reproducible artifacts${process.argv.includes('--check') ? ' checked' : ' written'}.`);
|
||||
+3
-2
@@ -4,7 +4,8 @@ import path from 'node:path';
|
||||
import os from 'node:os';
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..');
|
||||
const required = ['build/block.json', 'build/index.js', 'build/index.asset.php', 'build/view.js', 'build/view.asset.php', 'build/player.js', 'build/player.css'];
|
||||
execFileSync(process.execPath, ['scripts/i18n.mjs', '--check'], { cwd: root, stdio: 'inherit' });
|
||||
const required = ['build/block.json', 'build/index.js', 'build/index.asset.php', 'build/view.js', 'build/view.asset.php', 'build/player.js', 'build/player.css', 'build/runtime.asset.php', 'languages/wp-asciiplayer-zh_CN.mo', 'languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-editor.json', 'languages/wp-asciiplayer-zh_CN-lamgc-asciiplayer-view.json'];
|
||||
for (const file of required) await stat(path.join(root, file));
|
||||
const pkg = JSON.parse(await readFile(path.join(root, 'package.json'), 'utf8'));
|
||||
const php = await readFile(path.join(root, 'asciicast-player.php'), 'utf8');
|
||||
@@ -12,7 +13,7 @@ const readme = await readFile(path.join(root, 'readme.txt'), 'utf8');
|
||||
if (!php.includes(`Version: ${pkg.version}`) || !readme.includes(`Stable tag: ${pkg.version}`)) throw new Error('Version headers disagree.');
|
||||
const temp = await mkdtemp(path.join(os.tmpdir(), 'wp-asciiplayer-package-'));
|
||||
const target = path.join(temp, 'wp-asciiplayer');
|
||||
const inputs = ['asciicast-player.php', 'includes', 'build', 'LICENSE', 'licenses', 'THIRD-PARTY-NOTICES.md', 'README.md', 'README-zh.md', 'readme.txt', 'SOURCE.md', 'src', 'block.json', 'package.json', 'package-lock.json', 'webpack.config.cjs', 'babel.config.json', 'scripts'];
|
||||
const inputs = ['asciicast-player.php', 'includes', 'build', 'languages', 'LICENSE', 'licenses', 'THIRD-PARTY-NOTICES.md', 'README.md', 'README-zh.md', 'readme.txt', 'SOURCE.md', 'src', 'block.json', 'package.json', 'package-lock.json', 'webpack.config.cjs', 'babel.config.json', 'scripts'];
|
||||
try {
|
||||
await mkdir(target);
|
||||
for (const file of inputs) await cp(path.join(root, file), path.join(target, file), { recursive: true });
|
||||
|
||||
+10
-1
@@ -1,5 +1,6 @@
|
||||
import { copyFile, mkdir, readFile } from 'node:fs/promises';
|
||||
import { copyFile, mkdir, readFile, writeFile } from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const root = path.resolve(import.meta.dirname, '..');
|
||||
const pkg = JSON.parse(await readFile(path.join(root, 'node_modules/asciinema-player/package.json'), 'utf8'));
|
||||
@@ -13,3 +14,11 @@ for (const [source, destination] of [
|
||||
}
|
||||
await copyFile(path.join(root, 'block.json'), path.join(root, 'build/block.json'));
|
||||
console.log(`Bundled local asciinema-player ${pkg.version}; no CDN is used.`);
|
||||
|
||||
// Content hashes avoid stale assets across successive builds of 1.1.0-dev.
|
||||
const versions = [];
|
||||
for (const file of ['player.js', 'player.css', 'style-index.css', 'index.css']) {
|
||||
const hash = createHash('sha256').update(await readFile(path.join(root, 'build', file))).digest('hex').slice(0, 16);
|
||||
versions.push(`'${file}' => '${hash}'`);
|
||||
}
|
||||
await writeFile(path.join(root, 'build/runtime.asset.php'), `<?php return array(${versions.join(', ')});\n`);
|
||||
|
||||
@@ -34,13 +34,15 @@ for (const readyState of ['loading', 'complete']) {
|
||||
assert.equal(event, 'DOMContentLoaded');
|
||||
onReady = callback;
|
||||
},
|
||||
defaultView: { AsciinemaPlayer: { create(source, target) {
|
||||
assert.equal(source, '/recording.cast');
|
||||
defaultView: { AbortController, fetch() { throw new Error('Lazy playback must not fetch during boot.'); }, MutationObserver: class { observe() {} disconnect() {} }, AsciinemaPlayer: { create(source, target) {
|
||||
assert.equal(typeof source.data, 'function');
|
||||
assert.equal(target, container);
|
||||
mounts++;
|
||||
return { addEventListener() {} };
|
||||
} } },
|
||||
};
|
||||
container.ownerDocument = document;
|
||||
container.isConnected = true;
|
||||
runInNewContext(view, { document, window: { wp: { i18n: { __: (text) => text } } }, URL });
|
||||
if (readyState === 'loading') {
|
||||
assert.equal(mounts, 0);
|
||||
@@ -51,3 +53,11 @@ for (const readyState of ['loading', 'complete']) {
|
||||
assert.equal(container.dataset.apStatus, 'idle');
|
||||
}
|
||||
console.log('Verified WordPress 6.3 dependencies, block metadata, exact vendor files, and emitted frontend boot.');
|
||||
|
||||
// Physical placement and terminal direction must not be mirrored by RTLCSS.
|
||||
for (const suffix of ['', '-rtl']) {
|
||||
const css = await readFile(`build/style-index${suffix}.css`, 'utf8');
|
||||
assert.match(css, /asciiplayer-align-left\{[^}]*margin-left:0!important[^}]*margin-right:auto!important/);
|
||||
assert.match(css, /asciiplayer-align-right\{[^}]*margin-left:auto!important[^}]*margin-right:0!important/);
|
||||
assert.match(css, /asciiplayer-container \.ap-wrapper\{text-align:left/);
|
||||
}
|
||||
|
||||
+108
-22
@@ -1,17 +1,51 @@
|
||||
import { InspectorControls, useBlockProps } from '@wordpress/block-editor';
|
||||
import { Button, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl } from '@wordpress/components';
|
||||
import { useEffect, useState } from '@wordpress/element';
|
||||
import { BlockAlignmentToolbar, BlockControls, InspectorControls, MediaUpload, MediaUploadCheck, RichText, useBlockProps } from '@wordpress/block-editor';
|
||||
import { Button, Dropdown, Notice, PanelBody, Placeholder, RangeControl, SelectControl, TextControl, ToggleControl, ToolbarButton, ToolbarGroup } from '@wordpress/components';
|
||||
import { useCallback, useEffect, useState } from '@wordpress/element';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { finiteNumber, normalizeSource, normalizeWidth } from './options.js';
|
||||
import { finiteNumber, normalizeDisplayAlign, normalizeSource, normalizeWidth, terminalDimension } from './options.js';
|
||||
import Preview from './preview.js';
|
||||
|
||||
export default function Edit( { attributes, setAttributes } ) {
|
||||
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width } = attributes;
|
||||
/** One shared set of dimension controls in the block toolbar and settings sidebar. */
|
||||
function TerminalSizeControls( { attributes, setAttributes, recordingSize } ) {
|
||||
return <>
|
||||
<div className="asciiplayer-editor__dimension-fields">
|
||||
<TextControl label={ __( 'Columns', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ attributes.cols ?? '' } placeholder={ recordingSize ? String( recordingSize.cols ) : __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { cols: terminalDimension( value ) } ) } />
|
||||
<TextControl label={ __( 'Rows', 'wp-asciiplayer' ) } type="number" min="1" max="1000" step="1" value={ attributes.rows ?? '' } placeholder={ recordingSize ? String( recordingSize.rows ) : __( 'From recording', 'wp-asciiplayer' ) } onChange={ ( value ) => setAttributes( { rows: terminalDimension( value ) } ) } />
|
||||
</div>
|
||||
<p className="asciiplayer-editor__hint">{ __( 'Placeholders show the recording’s original columns and rows once loaded. Leave blank to follow its terminal size and recorded resize events. These overrides change the character grid, not the display width, and may alter or crop the layout.', 'wp-asciiplayer' ) }</p>
|
||||
<Button variant="secondary" onClick={ () => setAttributes( { cols: undefined, rows: undefined } ) }>{ __( 'Use recording size', 'wp-asciiplayer' ) }</Button>
|
||||
</>;
|
||||
}
|
||||
|
||||
export default function Edit( { attributes, setAttributes, isSelected } ) {
|
||||
const { source, theme, speed, loop, controls, fit, startAt, idleTimeLimit, autoPlay, preload, width, caption, displayAlign } = attributes;
|
||||
const [ draftSource, setDraftSource ] = useState( source );
|
||||
const [ approvedSource, setApprovedSource ] = useState( '' );
|
||||
const [ urlError, setUrlError ] = useState( false );
|
||||
const [ mediaError, setMediaError ] = useState( false );
|
||||
const [ recording, setRecording ] = useState( null );
|
||||
const onRecordingSize = useCallback( ( loadedSource, size ) => setRecording( { source: loadedSource, size } ), [] );
|
||||
const [ attempt, setAttempt ] = useState( 0 );
|
||||
useEffect( () => setDraftSource( source ), [ source ] );
|
||||
const [ draftWidth, setDraftWidth ] = useState( width );
|
||||
useEffect( () => setDraftWidth( width ), [ width ] );
|
||||
useEffect( () => {
|
||||
setDraftSource( source );
|
||||
setRecording( null );
|
||||
setUrlError( Boolean( source.trim() ) && ! normalizeSource( source ) );
|
||||
}, [ source ] );
|
||||
// Saved/undone sources load immediately. Typed changes wait until the user
|
||||
// pauses, and submitting the form applies the same URL without that delay.
|
||||
useEffect( () => {
|
||||
if ( attributes.isExample || draftSource === source ) return undefined;
|
||||
const timer = setTimeout( () => {
|
||||
const next = normalizeSource( draftSource );
|
||||
setUrlError( Boolean( draftSource.trim() ) && ! next );
|
||||
if ( next || ! draftSource.trim() ) setAttributes( { source: next } );
|
||||
}, 500 );
|
||||
return () => clearTimeout( timer );
|
||||
}, [ draftSource, source, attributes.isExample, setAttributes ] );
|
||||
const previewSource = normalizeSource( source );
|
||||
const showPreview = previewSource && previewSource === normalizeSource( draftSource );
|
||||
const recordingSize = showPreview && recording?.source === previewSource ? recording.size : null;
|
||||
const blockProps = useBlockProps( { className: 'asciiplayer-editor' } );
|
||||
const applySource = ( event ) => {
|
||||
event.preventDefault();
|
||||
@@ -20,7 +54,19 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
if ( ! next ) return;
|
||||
setAttributes( { source: next } );
|
||||
setDraftSource( next );
|
||||
setApprovedSource( next );
|
||||
setAttempt( ( current ) => current + 1 );
|
||||
};
|
||||
const selectRecording = ( media ) => {
|
||||
const next = normalizeSource( media?.url );
|
||||
if ( ! next || ! /\.cast$/i.test( next.split( /[?#]/ )[ 0 ] ) ) {
|
||||
setMediaError( true );
|
||||
return;
|
||||
}
|
||||
setMediaError( false );
|
||||
setUrlError( false );
|
||||
setRecording( null );
|
||||
setDraftSource( next );
|
||||
setAttributes( { source: next } );
|
||||
setAttempt( ( current ) => current + 1 );
|
||||
};
|
||||
const themes = [
|
||||
@@ -31,21 +77,51 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
{ label: 'Solarized Light', value: 'solarized-light' }, { label: 'Tango', value: 'tango' },
|
||||
];
|
||||
if ( ! themes.some( ( option ) => option.value === theme ) ) themes.push( { label: theme, value: theme } );
|
||||
const widthOptions = [ '100%', '80%', '60%', '50%' ].map( ( value ) => ( { label: value, value } ) );
|
||||
if ( ! widthOptions.some( ( option ) => option.value === width ) ) widthOptions.push( { label: width, value: width } );
|
||||
const widthPresets = [ '100%', '80%', '60%', '50%', '25%' ];
|
||||
const widthOptions = [ ...widthPresets.map( ( value ) => ( { label: value, value } ) ), { label: __( 'Custom', 'wp-asciiplayer' ), value: 'custom' } ];
|
||||
const [ customWidth, setCustomWidth ] = useState( ! widthPresets.includes( width ) );
|
||||
const widthValid = draftWidth.trim() !== '' && normalizeWidth( draftWidth ) === draftWidth.trim() && parseFloat( draftWidth ) > 0;
|
||||
const placement = normalizeDisplayAlign( displayAlign );
|
||||
const fitOptions = [
|
||||
{ label: __( 'Width', 'wp-asciiplayer' ), value: 'width' },
|
||||
{ label: __( 'Original size', 'wp-asciiplayer' ), value: 'none' },
|
||||
];
|
||||
if ( fit === 'height' || fit === 'both' ) fitOptions.push( { label: fit === 'height' ? __( 'Height (legacy)', 'wp-asciiplayer' ) : __( 'Width and height (legacy)', 'wp-asciiplayer' ), value: fit } );
|
||||
if ( attributes.isExample ) {
|
||||
return <div { ...blockProps }><figure className="asciiplayer-example" aria-label={ __( 'Example terminal recording', 'wp-asciiplayer' ) }><div className="asciiplayer-example__terminal"><span>$ printf 'Hello, terminal!\n'</span><br /><span>Hello, terminal!</span><br /><span>$ <span aria-hidden="true">▋</span></span></div><div className="asciiplayer-example__controls" aria-hidden="true">▶ ━━━━━━━━━━━ 0:00 / 0:12</div><figcaption>{ __( 'A terminal recording, right in your post.', 'wp-asciiplayer' ) }</figcaption></figure></div>;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<BlockControls group="other">
|
||||
<BlockAlignmentToolbar value={ placement } controls={ [ 'left', 'center', 'right' ] } onChange={ ( value ) => setAttributes( { displayAlign: normalizeDisplayAlign( value ) } ) } />
|
||||
<ToolbarGroup>
|
||||
<Dropdown contentClassName="asciiplayer-terminal-popover" popoverProps={ { placement: 'bottom-start' } } renderToggle={ ( { isOpen, onToggle } ) => (
|
||||
<ToolbarButton icon="editor-table" label={ __( 'Terminal size', 'wp-asciiplayer' ) } aria-expanded={ isOpen } onClick={ onToggle } />
|
||||
) } renderContent={ ( { onClose } ) => (
|
||||
<div className="asciiplayer-terminal-popover__content" role="dialog" aria-label={ __( 'Terminal size', 'wp-asciiplayer' ) }>
|
||||
<p><strong>{ __( 'Terminal size (columns × rows)', 'wp-asciiplayer' ) }</strong></p>
|
||||
<TerminalSizeControls attributes={ attributes } setAttributes={ setAttributes } recordingSize={ recordingSize } />
|
||||
<Button variant="tertiary" onClick={ onClose }>{ __( 'Close', 'wp-asciiplayer' ) }</Button>
|
||||
</div>
|
||||
) } />
|
||||
</ToolbarGroup>
|
||||
</BlockControls>
|
||||
<InspectorControls>
|
||||
<PanelBody title={ __( 'Terminal size', 'wp-asciiplayer' ) } initialOpen={ false }>
|
||||
<TerminalSizeControls attributes={ attributes } setAttributes={ setAttributes } recordingSize={ recordingSize } />
|
||||
</PanelBody>
|
||||
<PanelBody title={ __( 'Display', 'wp-asciiplayer' ) }>
|
||||
<SelectControl label={ __( 'Player width', 'wp-asciiplayer' ) } value={ customWidth || ! widthPresets.includes( width ) ? 'custom' : width } options={ widthOptions } onChange={ ( value ) => { setCustomWidth( value === 'custom' ); if ( value !== 'custom' ) setAttributes( { width: value } ); } } />
|
||||
{ ( customWidth || ! widthPresets.includes( width ) ) && <TextControl label={ __( 'Custom width', 'wp-asciiplayer' ) } value={ draftWidth } help={ widthValid ? __( 'Use a CSS length, such as 480px or 65%. The player stays within its available space.', 'wp-asciiplayer' ) : __( 'Enter a positive width with a unit, such as 480px or 65%. The last valid width is kept.', 'wp-asciiplayer' ) } aria-invalid={ ! widthValid } onChange={ ( value ) => { setDraftWidth( value ); if ( value.trim() && normalizeWidth( value ) === value.trim() && parseFloat( value ) > 0 ) setAttributes( { width: value.trim() } ); } } /> }
|
||||
<SelectControl label={ __( 'Display alignment', 'wp-asciiplayer' ) } value={ placement } options={ [ { label: __( 'Left', 'wp-asciiplayer' ), value: 'left' }, { label: __( 'Center', 'wp-asciiplayer' ), value: 'center' }, { label: __( 'Right', 'wp-asciiplayer' ), value: 'right' } ] } onChange={ ( value ) => setAttributes( { displayAlign: value } ) } />
|
||||
<p>{ __( 'Display width scales the recording without changing its terminal columns or rows. Add a caption directly below the player.', 'wp-asciiplayer' ) }</p>
|
||||
</PanelBody>
|
||||
|
||||
<PanelBody title={ __( 'Playback', 'wp-asciiplayer' ) }>
|
||||
<RangeControl label={ __( 'Playback speed', 'wp-asciiplayer' ) } value={ speed } min={ 0.25 } max={ Math.max( 8, speed ) } step={ 0.25 } onChange={ ( value ) => setAttributes( { speed: finiteNumber( value, 1, 0.01, 100 ) } ) } />
|
||||
<ToggleControl label={ __( 'Loop playback', 'wp-asciiplayer' ) } checked={ loop } onChange={ ( value ) => setAttributes( { loop: value } ) } />
|
||||
<ToggleControl label={ __( 'Autoplay on published page', 'wp-asciiplayer' ) } help={ __( 'The editor preview always waits for you to press play.', 'wp-asciiplayer' ) } checked={ autoPlay } onChange={ ( value ) => setAttributes( { autoPlay: value } ) } />
|
||||
<ToggleControl label={ __( 'Preload on published page', 'wp-asciiplayer' ) } help={ __( 'Loads the recording before the visitor presses play. The editor always preloads after you apply the URL.', 'wp-asciiplayer' ) } checked={ preload } onChange={ ( value ) => setAttributes( { preload: value } ) } />
|
||||
<ToggleControl label={ __( 'Preload on published page', 'wp-asciiplayer' ) } help={ __( 'Loads the recording before the visitor presses play. The editor preview always preloads a valid recording URL.', 'wp-asciiplayer' ) } checked={ preload } onChange={ ( value ) => setAttributes( { preload: value } ) } />
|
||||
<TextControl label={ __( 'Start at (seconds)', 'wp-asciiplayer' ) } type="number" min="0" step="0.1" value={ startAt } onChange={ ( value ) => setAttributes( { startAt: finiteNumber( value, 0 ) } ) } />
|
||||
<TextControl label={ __( 'Idle time limit (seconds)', 'wp-asciiplayer' ) } help={ __( 'Shorten long pauses. Use 0 to keep the recording’s default.', 'wp-asciiplayer' ) } type="number" min="0" step="0.1" value={ idleTimeLimit } onChange={ ( value ) => setAttributes( { idleTimeLimit: finiteNumber( value, 0 ) } ) } />
|
||||
</PanelBody>
|
||||
@@ -57,28 +133,38 @@ export default function Edit( { attributes, setAttributes } ) {
|
||||
{ label: __( 'Hide', 'wp-asciiplayer' ), value: 'never' },
|
||||
] } onChange={ ( value ) => setAttributes( { controls: value } ) } />
|
||||
<SelectControl label={ __( 'Fit', 'wp-asciiplayer' ) } value={ fit } options={ fitOptions } help={ [ 'height', 'both' ].includes( fit ) ? __( 'Height-based fitting requires a fixed container height in your site CSS.', 'wp-asciiplayer' ) : undefined } onChange={ ( value ) => setAttributes( { fit: value } ) } />
|
||||
<SelectControl label={ __( 'Player width', 'wp-asciiplayer' ) } value={ width } options={ widthOptions } onChange={ ( value ) => setAttributes( { width: value } ) } />
|
||||
{ attributes.legacyStyle && <p>{ __( 'The custom container style from your shortcode is preserved on the published page.', 'wp-asciiplayer' ) }</p> }
|
||||
</PanelBody>
|
||||
<PanelBody title={ __( 'Help', 'wp-asciiplayer' ) } initialOpen={ false }>
|
||||
<p className="asciiplayer-editor__privacy">{ __( 'A valid recording URL loads its preview automatically, including when reopening this editor. That server receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.', 'wp-asciiplayer' ) }</p>
|
||||
<p className="asciiplayer-editor__hint">{ __( 'Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.', 'wp-asciiplayer' ) }</p>
|
||||
</PanelBody>
|
||||
</InspectorControls>
|
||||
<div { ...blockProps }>
|
||||
<div className="asciiplayer-editor__source">
|
||||
<form onSubmit={ applySource }>
|
||||
<TextControl label={ __( 'Recording URL', 'wp-asciiplayer' ) } placeholder="https://example.com/recording.cast" value={ draftSource } onChange={ ( value ) => { setDraftSource( value ); setUrlError( false ); } } autoComplete="off" />
|
||||
<TextControl label={ __( 'Recording URL', 'wp-asciiplayer' ) } placeholder="https://example.com/recording.cast" value={ draftSource } onChange={ ( value ) => { setDraftSource( value ); setUrlError( false ); setMediaError( false ); } } autoComplete="off" />
|
||||
<Button type="submit" variant="primary">{ __( 'Apply URL', 'wp-asciiplayer' ) }</Button>
|
||||
</form>
|
||||
<p className="asciiplayer-editor__privacy">{ __( 'Applying a URL loads the recording directly from that server, which receives your browser’s request. Published players contact the same server. Use a direct .cast URL; external servers must allow CORS.', 'wp-asciiplayer' ) }</p>
|
||||
<MediaUploadCheck>
|
||||
<MediaUpload title={ __( 'Choose an Asciicast recording', 'wp-asciiplayer' ) } allowedTypes={ [ 'application/x-asciicast', 'text/plain', 'application/json', 'application/octet-stream', 'application/jsonl', 'application/x-ndjson' ] } multiple={ false } onSelect={ selectRecording } render={ ( { open } ) => (
|
||||
<Button className="asciiplayer-editor__media" variant="secondary" onClick={ open }>{ __( 'Choose recording', 'wp-asciiplayer' ) }</Button>
|
||||
) } />
|
||||
</MediaUploadCheck>
|
||||
{ mediaError && <Notice status="error" isDismissible={ false }>{ __( 'Choose an Asciicast (.cast) file from the Media Library.', 'wp-asciiplayer' ) }</Notice> }
|
||||
{ urlError && <Notice status="error" isDismissible={ false }>{ __( 'Enter an HTTP(S) recording URL or a path starting with a single /.', 'wp-asciiplayer' ) }</Notice> }
|
||||
</div>
|
||||
{ approvedSource && approvedSource === source ? (
|
||||
<div style={ { width: normalizeWidth( width ), maxWidth: '100%' } }>
|
||||
<Preview source={ source } attributes={ attributes } attempt={ attempt } onRetry={ () => setAttempt( ( current ) => current + 1 ) } />
|
||||
</div>
|
||||
<figure className={ `asciiplayer-figure asciiplayer-align-${ placement }` } style={ { width: normalizeWidth( width ) } }>
|
||||
{ showPreview ? (
|
||||
<>
|
||||
<Preview source={ previewSource } attributes={ attributes } attempt={ attempt } onRecordingSize={ onRecordingSize } onRetry={ () => setAttempt( ( current ) => current + 1 ) } />
|
||||
</>
|
||||
) : (
|
||||
<Placeholder icon="editor-code" label={ __( 'Asciicast Player', 'wp-asciiplayer' ) } instructions={ source ? __( 'Load the saved recording to play and adjust it here.', 'wp-asciiplayer' ) : __( 'Paste a terminal recording URL above, then apply it to see an interactive preview.', 'wp-asciiplayer' ) }>
|
||||
{ source && <Button variant="secondary" onClick={ () => { setApprovedSource( source ); setAttempt( ( current ) => current + 1 ); } }>{ __( 'Load preview', 'wp-asciiplayer' ) }</Button> }
|
||||
</Placeholder>
|
||||
<Placeholder icon="editor-code" label={ __( 'Asciicast Player', 'wp-asciiplayer' ) } instructions={ __( 'Enter a recording URL to load its preview automatically. Playback starts only when you press play.', 'wp-asciiplayer' ) } />
|
||||
) }
|
||||
<RichText tagName="figcaption" className={ `wp-element-caption${ ! isSelected && ! caption ? ' asciiplayer-caption-empty' : '' }` } value={ caption } allowedFormats={ [] } onChange={ ( value ) => setAttributes( { caption: value } ) } placeholder={ __( 'Add a caption…', 'wp-asciiplayer' ) } aria-label={ __( 'Recording caption', 'wp-asciiplayer' ) } />
|
||||
</figure>
|
||||
{ [ 'height', 'both' ].includes( fit ) && <p className="asciiplayer-editor__hint">{ __( 'Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.', 'wp-asciiplayer' ) }</p> }
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
.asciiplayer-editor {
|
||||
box-sizing: border-box;
|
||||
border: 1px solid #ddd;
|
||||
border-radius: 4px;
|
||||
padding: 16px;
|
||||
@@ -30,10 +31,12 @@
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
/*! rtl:begin:ignore */
|
||||
.asciiplayer-editor__player {
|
||||
min-width: 0;
|
||||
text-align: left;
|
||||
}
|
||||
/*! rtl:end:ignore */
|
||||
|
||||
.asciiplayer-editor__status {
|
||||
display: flex;
|
||||
@@ -48,3 +51,25 @@
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
.asciiplayer-editor > .asciiplayer-figure { margin-top: 16px; }
|
||||
.asciiplayer-editor .asciiplayer-editor__preview { margin-top: 0; }
|
||||
.asciiplayer-example { margin: 0; background: #121314; color: #eee; border-radius: 5px; overflow: hidden; }
|
||||
.asciiplayer-example__terminal { padding: 24px 16px; font: 14px/1.7 monospace; white-space: pre; }
|
||||
.asciiplayer-example__terminal > span:first-child { color: #a9da76; }
|
||||
.asciiplayer-example__controls { padding: 8px 16px; background: #222; font: 12px/1.5 monospace; }
|
||||
.asciiplayer-example figcaption { padding: 8px; background: #fff; color: #333; text-align: center; font-size: 12px; }
|
||||
|
||||
/* Keep an empty caption's footprint stable when another block is selected.
|
||||
* Removing it on pointerdown can move the next block's button before pointerup. */
|
||||
.asciiplayer-editor .asciiplayer-figure > figcaption { min-height: 1.5em; }
|
||||
.asciiplayer-editor .asciiplayer-caption-empty { visibility: hidden; }
|
||||
|
||||
.asciiplayer-editor__dimension-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
|
||||
.asciiplayer-editor__dimension-fields input { max-width: 100%; }
|
||||
|
||||
.asciiplayer-terminal-popover__content { box-sizing: border-box; width: 300px; max-width: calc(100vw - 32px); padding: 16px; }
|
||||
.asciiplayer-terminal-popover__content > p:first-child { margin-top: 0; }
|
||||
.asciiplayer-terminal-popover__content > .components-button { margin-top: 8px; margin-right: 8px; }
|
||||
|
||||
.asciiplayer-editor__source .asciiplayer-editor__media { margin-top: 12px; }
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createBlock, registerBlockType } from '@wordpress/blocks';
|
||||
import { next } from '@wordpress/shortcode';
|
||||
import { decodeEntities } from '@wordpress/html-entities';
|
||||
import metadata from '../block.json';
|
||||
import { _x } from '@wordpress/i18n';
|
||||
import Edit from './edit.js';
|
||||
import { attributesFromShortcode, canTransformShortcode, normalizeSource } from './options.js';
|
||||
import './style.css';
|
||||
@@ -14,6 +15,9 @@ function matchShortcodeBlock( text = '' ) {
|
||||
|
||||
registerBlockType( metadata.name, {
|
||||
...metadata,
|
||||
title: _x( 'Asciicast Player', 'block title', 'wp-asciiplayer' ),
|
||||
description: _x( 'Embed and preview a terminal recording with the locally bundled asciinema player.', 'block description', 'wp-asciiplayer' ),
|
||||
keywords: [ _x( 'asciinema', 'block keyword', 'wp-asciiplayer' ), _x( 'terminal', 'block keyword', 'wp-asciiplayer' ), _x( 'recording', 'block keyword', 'wp-asciiplayer' ) ],
|
||||
edit: Edit,
|
||||
save: () => null,
|
||||
transforms: {
|
||||
|
||||
@@ -39,6 +39,16 @@ export function normalizeWidth( value ) {
|
||||
? value.trim() : DEFAULTS.width;
|
||||
}
|
||||
|
||||
/** Presentation placement never changes the terminal's character grid. */
|
||||
export function normalizeDisplayAlign( value ) {
|
||||
return [ 'left', 'center', 'right' ].includes( value ) ? value : 'center';
|
||||
}
|
||||
|
||||
export function terminalDimension( value ) {
|
||||
const number = finiteNumber( value, 0, 1, 1000 );
|
||||
return Number.isInteger( number ) && number > 0 ? number : undefined;
|
||||
}
|
||||
|
||||
/** A bounded editor frame for old height-fitting shortcodes; never persisted. */
|
||||
export function previewHeight( attributes ) {
|
||||
if ( ! [ 'height', 'both' ].includes( attributes.fit ) ) return undefined;
|
||||
|
||||
+36
-9
@@ -1,39 +1,69 @@
|
||||
import { Button, Notice, Spinner } from '@wordpress/components';
|
||||
import { useRefEffect } from '@wordpress/compose';
|
||||
import { useState } from '@wordpress/element';
|
||||
import { useRef, useState } from '@wordpress/element';
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { normalizePlayerOptions, previewHeight } from './options.js';
|
||||
import { playerAssets, playerForDocument } from './player-bridge.js';
|
||||
import { loadRecording, validateInitialDimensions } from './recording-loader.js';
|
||||
import { recordingErrorMessage } from './recording-errors.js';
|
||||
|
||||
export default function Preview( { source, attributes, attempt, onRetry } ) {
|
||||
export default function Preview( { source, attributes, attempt, onRetry, onRecordingSize } ) {
|
||||
const [ status, setStatus ] = useState( 'loading' );
|
||||
const [ problem, setProblem ] = useState( '' );
|
||||
const onRecordingSizeRef = useRef( onRecordingSize );
|
||||
onRecordingSizeRef.current = onRecordingSize;
|
||||
const optionsJSON = JSON.stringify( normalizePlayerOptions( attributes, { preview: true } ) );
|
||||
const playerRef = useRefEffect( ( container ) => {
|
||||
let disposed = false;
|
||||
let failed = false;
|
||||
let player;
|
||||
let readinessTimer;
|
||||
let deadline;
|
||||
const canvasWindow = container.ownerDocument.defaultView;
|
||||
const request = new canvasWindow.AbortController();
|
||||
const reportSize = ( size ) => {
|
||||
if ( ! disposed ) onRecordingSizeRef.current?.( source, size );
|
||||
};
|
||||
setStatus( 'loading' );
|
||||
setProblem( '' );
|
||||
reportSize( null );
|
||||
const fail = ( message ) => {
|
||||
if ( disposed ) return;
|
||||
if ( disposed || failed ) return;
|
||||
failed = true;
|
||||
request.abort();
|
||||
canvasWindow.clearInterval( readinessTimer );
|
||||
canvasWindow.clearTimeout( deadline );
|
||||
reportSize( null );
|
||||
setProblem( message );
|
||||
setStatus( 'error' );
|
||||
};
|
||||
const ready = () => {
|
||||
if ( disposed ) return;
|
||||
if ( disposed || failed ) return;
|
||||
canvasWindow.clearInterval( readinessTimer );
|
||||
canvasWindow.clearTimeout( deadline );
|
||||
setStatus( 'ready' );
|
||||
};
|
||||
deadline = canvasWindow.setTimeout( () => fail( recordingErrorMessage( { code: 'timeout' } ) ), 30000 );
|
||||
playerForDocument( container.ownerDocument, playerAssets() ).then( ( api ) => {
|
||||
if ( disposed ) return;
|
||||
player = api.create( { url: source, fetchOpts: { signal: request.signal } }, container, JSON.parse( optionsJSON ) );
|
||||
if ( disposed || failed ) return;
|
||||
try {
|
||||
validateInitialDimensions( JSON.parse( optionsJSON ) );
|
||||
} catch ( error ) {
|
||||
fail( recordingErrorMessage( error ) );
|
||||
return;
|
||||
}
|
||||
player = api.create( {
|
||||
data: () => loadRecording( source, {
|
||||
fetchImpl: canvasWindow.fetch.bind( canvasWindow ),
|
||||
signal: request.signal,
|
||||
options: JSON.parse( optionsJSON ),
|
||||
onMetadata: ( size ) => { if ( ! failed ) reportSize( size ); },
|
||||
} ).catch( ( error ) => {
|
||||
const message = recordingErrorMessage( error );
|
||||
if ( message ) fail( message );
|
||||
throw error;
|
||||
} ),
|
||||
}, container, JSON.parse( optionsJSON ) );
|
||||
player.addEventListener( 'error', () => fail( __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' ) ) );
|
||||
player.addEventListener( 'playing', ready );
|
||||
// getDuration is public API; a mounted wrapper alone does not mean the
|
||||
@@ -43,7 +73,6 @@ export default function Preview( { source, attributes, attempt, onRetry } ) {
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready();
|
||||
};
|
||||
readinessTimer = canvasWindow.setInterval( checkReady, 150 );
|
||||
deadline = canvasWindow.setTimeout( () => fail( __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' ) ), 30000 );
|
||||
checkReady();
|
||||
} ).catch( () => fail( __( 'The local player could not start. Try again, or check that the plugin’s built assets are installed.', 'wp-asciiplayer' ) ) );
|
||||
return () => {
|
||||
@@ -61,8 +90,6 @@ export default function Preview( { source, attributes, attempt, onRetry } ) {
|
||||
{ status === 'loading' && <div className="asciiplayer-editor__status" role="status"><Spinner />{ __( 'Loading recording…', 'wp-asciiplayer' ) }</div> }
|
||||
{ status === 'error' && <Notice status="error" isDismissible={ false }><p>{ problem }</p><Button variant="secondary" onClick={ onRetry }>{ __( 'Retry preview', 'wp-asciiplayer' ) }</Button></Notice> }
|
||||
<div className="asciiplayer-editor__player" style={ { height: previewHeight( attributes ) } } ref={ playerRef } aria-label={ __( 'Interactive terminal recording preview', 'wp-asciiplayer' ) } />
|
||||
{ [ 'height', 'both' ].includes( attributes.fit ) && <p className="asciiplayer-editor__hint">{ __( 'Height-based previews use the shortcode’s fixed height when available, or a 320px editor frame. Published height still comes from your container style.', 'wp-asciiplayer' ) }</p> }
|
||||
<p className="asciiplayer-editor__hint">{ __( 'Use the player controls to play, pause, and seek. Autoplay is disabled only in the editor.', 'wp-asciiplayer' ) }</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { __ } from '@wordpress/i18n';
|
||||
|
||||
/** Never expose remote content or raw exception messages in a recording notice. */
|
||||
export function recordingErrorMessage( error, { frontend = false } = {} ) {
|
||||
switch ( error?.code ) {
|
||||
case 'aborted': return '';
|
||||
case 'bytes': return __( 'This recording exceeds the file size limit.', 'wp-asciiplayer' );
|
||||
case 'line': return __( 'This recording contains a line that exceeds the size limit.', 'wp-asciiplayer' );
|
||||
case 'events': return __( 'This recording contains too many events.', 'wp-asciiplayer' );
|
||||
case 'markers': return __( 'This recording contains too many markers.', 'wp-asciiplayer' );
|
||||
case 'dimensions': return __( 'This recording requests terminal dimensions that exceed the supported limits.', 'wp-asciiplayer' );
|
||||
case 'cells': return __( 'This recording requests too many terminal cells.', 'wp-asciiplayer' );
|
||||
case 'complexity': return __( 'This recording is too complex to load safely.', 'wp-asciiplayer' );
|
||||
case 'timeout': return __( 'The recording is taking too long to load. Check your connection and try again.', 'wp-asciiplayer' );
|
||||
case 'time': return __( 'This recording contains an invalid or unsupported timestamp.', 'wp-asciiplayer' );
|
||||
// Invalid data, network/CORS failures, missing stream support, and policy
|
||||
// configuration errors retain the existing localized fallback guidance.
|
||||
default: return frontend
|
||||
? __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' )
|
||||
: __( 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.', 'wp-asciiplayer' );
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
/** Resource policy for untrusted recordings, before handing data to the player. */
|
||||
export const DEFAULT_LIMITS = Object.freeze( {
|
||||
bytes: 32 * 1024 * 1024, v1Bytes: 2 * 1024 * 1024, lineBytes: 256 * 1024,
|
||||
depth: 15, containers: 100016, tokens: 400000, lineTokens: 20000,
|
||||
events: 100000, lines: 100000, markers: 1000, dimension: 1000, cells: 40000,
|
||||
// Web timers take a signed 32-bit millisecond delay (~24.85 days). This
|
||||
// horizon also keeps upstream's 16.67 ms output batches numerically distinct.
|
||||
timelineMs: 2147483647,
|
||||
totalTimeoutMs: 30000, idleTimeoutMs: 10000,
|
||||
} );
|
||||
|
||||
export class RecordingLoadError extends Error {
|
||||
constructor( code ) {
|
||||
super( `Recording load failed: ${ code }` );
|
||||
this.name = 'RecordingLoadError';
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
const fail = ( code ) => { throw new RecordingLoadError( code ); };
|
||||
const boundedTime = ( value, maxMs ) => typeof value === 'number' && value >= 0 && value * 1000 <= maxMs;
|
||||
const object = ( value ) => value !== null && typeof value === 'object' && ! Array.isArray( value );
|
||||
|
||||
/** Guard the terminal allocated by api.create before its data loader runs. */
|
||||
export function validateInitialDimensions( options = {}, limits = {} ) {
|
||||
const dimension = limits.dimension ?? DEFAULT_LIMITS.dimension;
|
||||
const cells = limits.cells ?? DEFAULT_LIMITS.cells;
|
||||
if ( ! Number.isSafeInteger( dimension ) || dimension <= 0 || ! Number.isSafeInteger( cells ) || cells <= 0 ) fail( 'policy' );
|
||||
const cols = options.cols ?? 80;
|
||||
const rows = options.rows ?? 24;
|
||||
if ( ! Number.isSafeInteger( cols ) || cols < 1 || cols > dimension || ! Number.isSafeInteger( rows ) || rows < 1 || rows > dimension ) fail( 'dimensions' );
|
||||
if ( cols * rows > cells ) fail( 'cells' );
|
||||
}
|
||||
|
||||
/** Count allocation-driving JSON tokens before JSON.parse allocates containers. */
|
||||
function parseBounded( text, limits, v1 = false ) {
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
let primitive = false;
|
||||
let depth = 0;
|
||||
let tokens = 0;
|
||||
let containers = 0;
|
||||
const tokenLimit = v1 ? limits.tokens : limits.lineTokens;
|
||||
for ( const character of text ) {
|
||||
if ( quoted ) {
|
||||
if ( escaped ) escaped = false;
|
||||
else if ( character === '\\' ) escaped = true;
|
||||
else if ( character === '"' ) quoted = false;
|
||||
continue;
|
||||
}
|
||||
if ( character === '"' ) {
|
||||
quoted = true;
|
||||
primitive = false;
|
||||
tokens++;
|
||||
} else if ( character === '[' || character === '{' ) {
|
||||
primitive = false;
|
||||
if ( ++depth > limits.depth || ++containers > limits.containers ) fail( 'complexity' );
|
||||
} else if ( character === ']' || character === '}' ) {
|
||||
primitive = false;
|
||||
if ( --depth < 0 ) fail( 'invalid' );
|
||||
} else if ( character === ',' || character === ':' || /\s/.test( character ) ) {
|
||||
primitive = false;
|
||||
} else if ( ! primitive ) {
|
||||
primitive = true;
|
||||
tokens++;
|
||||
}
|
||||
if ( tokens > tokenLimit ) fail( 'complexity' );
|
||||
}
|
||||
if ( quoted || depth !== 0 ) fail( 'invalid' );
|
||||
try { return JSON.parse( text ); } catch { fail( 'invalid' ); }
|
||||
}
|
||||
|
||||
/** Inspect version and structural completeness without allocating a JSON tree. */
|
||||
function inspectFirstLine( text ) {
|
||||
let depth = 0;
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
let start = 0;
|
||||
let version;
|
||||
function member( end ) {
|
||||
let cursor = start;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
if ( text[ cursor ] !== '"' ) return;
|
||||
const keyStart = cursor++;
|
||||
let escape = false;
|
||||
while ( cursor < end ) {
|
||||
const character = text[ cursor++ ];
|
||||
if ( escape ) escape = false;
|
||||
else if ( character === '\\' ) escape = true;
|
||||
else if ( character === '"' ) break;
|
||||
}
|
||||
// "version" has seven characters, at most six JSON bytes each.
|
||||
if ( cursor - keyStart > 44 ) return;
|
||||
let key;
|
||||
try { key = JSON.parse( text.slice( keyStart, cursor ) ); } catch { return; }
|
||||
if ( key !== 'version' ) return;
|
||||
version = undefined;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
if ( text[ cursor++ ] !== ':' ) return;
|
||||
while ( cursor < end && /\s/.test( text[ cursor ] ) ) cursor++;
|
||||
while ( end > cursor && /\s/.test( text[ end - 1 ] ) ) end--;
|
||||
// Numeric conversion allocates no JSON containers; the complete parser
|
||||
// will still reject malformed numeric spellings or nonnumeric values.
|
||||
version = Number( text.slice( cursor, end ) );
|
||||
}
|
||||
for ( let index = 0; index < text.length; index++ ) {
|
||||
const character = text[ index ];
|
||||
if ( quoted ) {
|
||||
if ( escaped ) escaped = false;
|
||||
else if ( character === '\\' ) escaped = true;
|
||||
else if ( character === '"' ) quoted = false;
|
||||
continue;
|
||||
}
|
||||
if ( character === '"' ) quoted = true;
|
||||
else if ( character === '[' || character === '{' ) {
|
||||
if ( ++depth === 1 ) start = index + 1;
|
||||
} else if ( character === ']' || character === '}' ) {
|
||||
if ( depth === 1 ) member( index );
|
||||
depth--;
|
||||
} else if ( character === ',' && depth === 1 ) {
|
||||
member( index );
|
||||
start = index + 1;
|
||||
}
|
||||
}
|
||||
return { version, incomplete: depth > 0 || quoted };
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch once, count actual decoded-body bytes, and validate everything before
|
||||
* returning an upstream-compatible v1 object or v2/v3 [header, ...events] array.
|
||||
* limits are intended for policy configuration/tests, never recording metadata.
|
||||
*/
|
||||
export async function loadRecording( source, { fetchImpl = globalThis.fetch, signal, onMetadata, options = {}, limits = {} } = {} ) {
|
||||
const policy = { ...DEFAULT_LIMITS };
|
||||
for ( const key of Object.keys( policy ) ) {
|
||||
if ( Object.hasOwn( limits, key ) ) {
|
||||
if ( ! Number.isSafeInteger( limits[ key ] ) || limits[ key ] <= 0 ) fail( 'policy' );
|
||||
policy[ key ] = limits[ key ];
|
||||
}
|
||||
}
|
||||
// Policy overrides may lower this safety ceiling, but cannot expand the
|
||||
// platform timer range. Callers supply already-normalized player options.
|
||||
if ( policy.timelineMs > DEFAULT_LIMITS.timelineMs ) fail( 'policy' );
|
||||
const speed = options.speed ?? 1;
|
||||
if ( typeof speed !== 'number' || ! Number.isFinite( speed ) || speed < 0.01 || speed > 100 ) fail( 'time' );
|
||||
for ( const key of [ 'startAt', 'idleTimeLimit' ] ) {
|
||||
if ( options[ key ] !== undefined && ! boundedTime( options[ key ], policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
if ( typeof options.poster === 'string' && options.poster.startsWith( 'npt:' ) ) {
|
||||
// Match upstream parseNpt's order of arithmetic for normalized timecodes.
|
||||
const posterTime = options.poster.slice( 4 ).split( ':' ).reverse().map( parseFloat ).reduce( ( sum, part, index ) => sum + part * 60 ** index, 0 );
|
||||
if ( ! boundedTime( posterTime, policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
function checkTimeline( milliseconds ) {
|
||||
// Core passes (target - elapsed) / speed directly to setTimeout. Bound
|
||||
// the whole horizon conservatively: adjacent gaps alone are insufficient
|
||||
// because output batching can consume future events ahead of wall time.
|
||||
if ( ! Number.isFinite( milliseconds ) || milliseconds > policy.timelineMs || milliseconds / speed > DEFAULT_LIMITS.timelineMs ) fail( 'time' );
|
||||
}
|
||||
const controller = new AbortController();
|
||||
let reader;
|
||||
let totalTimer;
|
||||
let rejectStopped;
|
||||
let stoppedError;
|
||||
const deadline = Date.now() + policy.totalTimeoutMs;
|
||||
const stopped = new Promise( ( _, reject ) => { rejectStopped = reject; } );
|
||||
// A synchronous validation failure can precede the first Promise.race.
|
||||
stopped.catch( () => {} );
|
||||
const stop = ( code ) => {
|
||||
if ( stoppedError ) return;
|
||||
stoppedError = new RecordingLoadError( code );
|
||||
rejectStopped( stoppedError );
|
||||
controller.abort();
|
||||
};
|
||||
const abort = () => stop( 'aborted' );
|
||||
async function waitFor( operation ) {
|
||||
// Also enforce elapsed time when synthetic/cached streams resolve reads in
|
||||
// microtasks without giving browser timer callbacks a turn.
|
||||
if ( Date.now() >= deadline ) stop( 'timeout' );
|
||||
if ( stoppedError ) {
|
||||
Promise.resolve( operation ).catch( () => {} );
|
||||
throw stoppedError;
|
||||
}
|
||||
let idleTimer;
|
||||
try {
|
||||
idleTimer = setTimeout( () => stop( 'timeout' ), policy.idleTimeoutMs );
|
||||
return await Promise.race( [ operation, stopped ] );
|
||||
} finally { clearTimeout( idleTimer ); }
|
||||
}
|
||||
const dimension = ( value, zero = false ) => Number.isSafeInteger( value ) && value >= ( zero ? 0 : 1 ) && value <= policy.dimension;
|
||||
function checkSize( cols, rows, zero = false ) {
|
||||
if ( ! dimension( cols, zero ) || ! dimension( rows, zero ) ) fail( 'dimensions' );
|
||||
// Upstream applies each override independently, including every resize.
|
||||
const effectiveCols = options.cols ?? ( cols || 80 );
|
||||
const effectiveRows = options.rows ?? ( rows || 24 );
|
||||
if ( ! dimension( effectiveCols ) || ! dimension( effectiveRows ) ) fail( 'dimensions' );
|
||||
if ( ( cols || 80 ) * ( rows || 24 ) > policy.cells || effectiveCols * effectiveRows > policy.cells ) fail( 'cells' );
|
||||
}
|
||||
let bytes = 0;
|
||||
let mode = 'first';
|
||||
let header;
|
||||
let timeMs = 0;
|
||||
let lines = 0;
|
||||
let markerCount = Array.isArray( options.markers ) ? options.markers.length : 0;
|
||||
const events = [];
|
||||
const v1Parts = [];
|
||||
let lineParts = [];
|
||||
let lineBytes = 0;
|
||||
const decoder = new TextDecoder( 'utf-8', { fatal: true, ignoreBOM: true } );
|
||||
function checkHeader( value ) {
|
||||
if ( ! object( value ) || ! [ 1, 2, 3 ].includes( value.version ) ) fail( 'invalid' );
|
||||
if ( value.version === 3 ) {
|
||||
if ( ! object( value.term ) ) fail( 'dimensions' );
|
||||
checkSize( value.term.cols, value.term.rows, true );
|
||||
} else checkSize( value.width, value.height, true );
|
||||
for ( const key of [ 'duration', 'idle_time_limit' ] ) {
|
||||
if ( Object.hasOwn( value, key ) && ! boundedTime( value[ key ], policy.timelineMs ) ) fail( 'time' );
|
||||
}
|
||||
}
|
||||
function acceptLine( text, size, newline ) {
|
||||
if ( mode === 'first' ) {
|
||||
// Response.text strips only the document's initial UTF-8 BOM. Keep
|
||||
// later BOMs intact so resetting at LF cannot turn ignored lines into events.
|
||||
if ( text.charCodeAt( 0 ) === 0xfeff ) text = text.slice( 1 );
|
||||
// Pretty-printed v1 is the only supported multiline JSON document.
|
||||
// A syntax-incomplete first line is collected under the smaller v1 cap.
|
||||
const first = inspectFirstLine( text );
|
||||
// A v1 document may put version after a long stdout/title member.
|
||||
// Incomplete first lines therefore use the whole-document v1 budget.
|
||||
if ( first.version === 1 || first.incomplete ) {
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
try { header = parseBounded( text, policy ); } catch ( error ) {
|
||||
if ( error.code !== 'invalid' ) throw error;
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( header?.version === 1 ) {
|
||||
mode = 'v1';
|
||||
v1Parts.push( text, newline ? '\n' : '' );
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
checkHeader( header );
|
||||
mode = 'jsonl';
|
||||
return;
|
||||
}
|
||||
if ( size + Number( newline ) > policy.lineBytes ) fail( 'line' );
|
||||
// Match 3.17's JSONL filter: blank, comment, and other non-event lines
|
||||
// (including indented arrays) are ignored, but still byte/line bounded.
|
||||
if ( ++lines > policy.lines ) fail( 'events' );
|
||||
if ( text[ 0 ] !== '[' ) return;
|
||||
if ( events.length >= policy.events ) fail( 'events' );
|
||||
const event = parseBounded( text, policy );
|
||||
if ( ! Array.isArray( event ) || event.length !== 3 || typeof event[ 1 ] !== 'string' || ! event[ 1 ] || typeof event[ 2 ] !== 'string' ) fail( 'invalid' );
|
||||
if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
|
||||
const eventMs = event[ 0 ] * 1000;
|
||||
if ( header.version === 2 && events.length && event[ 0 ] < events[ events.length - 1 ][ 0 ] ) fail( 'time' );
|
||||
// v1/v3 upstream converts each interval before adding, which can round
|
||||
// differently from summing seconds and multiplying the result by 1000.
|
||||
timeMs = header.version === 3 ? timeMs + eventMs : eventMs;
|
||||
checkTimeline( timeMs );
|
||||
if ( event[ 1 ] === 'r' ) {
|
||||
const match = /^([1-9][0-9]{0,3})x([1-9][0-9]{0,3})$/.exec( event[ 2 ] );
|
||||
if ( ! match ) fail( 'dimensions' );
|
||||
checkSize( Number( match[ 1 ] ), Number( match[ 2 ] ) );
|
||||
}
|
||||
if ( event[ 1 ] === 'm' && ++markerCount > policy.markers ) fail( 'markers' );
|
||||
events.push( event );
|
||||
}
|
||||
try {
|
||||
if ( markerCount > policy.markers ) fail( 'markers' );
|
||||
if ( signal?.aborted ) fail( 'aborted' );
|
||||
signal?.addEventListener( 'abort', abort, { once: true } );
|
||||
totalTimer = setTimeout( () => stop( 'timeout' ), policy.totalTimeoutMs );
|
||||
const response = await waitFor( Promise.resolve().then( () => fetchImpl( source, { signal: controller.signal, credentials: 'same-origin' } ) ) );
|
||||
if ( ! response.ok ) fail( 'network' );
|
||||
if ( ! response.body?.getReader ) fail( 'stream' );
|
||||
reader = response.body.getReader();
|
||||
while ( true ) {
|
||||
const { value, done } = await waitFor( reader.read() );
|
||||
if ( done ) break;
|
||||
bytes += value.byteLength;
|
||||
if ( bytes > policy.bytes || ( mode === 'v1' && bytes > policy.v1Bytes ) ) fail( 'bytes' );
|
||||
if ( mode === 'v1' ) {
|
||||
v1Parts.push( decoder.decode( value, { stream: true } ) );
|
||||
continue;
|
||||
}
|
||||
let start = 0;
|
||||
for ( let index = 0; index <= value.length; index++ ) {
|
||||
if ( index !== value.length && value[ index ] !== 10 ) continue;
|
||||
const part = value.subarray( start, index );
|
||||
lineBytes += part.byteLength;
|
||||
if ( lineBytes > ( mode === 'first' ? policy.v1Bytes : policy.lineBytes ) ) fail( 'line' );
|
||||
if ( part.byteLength ) lineParts.push( decoder.decode( part, { stream: true } ) );
|
||||
if ( index < value.length ) {
|
||||
lineParts.push( decoder.decode() );
|
||||
acceptLine( lineParts.join( '' ), lineBytes, true );
|
||||
lineParts = [];
|
||||
lineBytes = 0;
|
||||
start = index + 1;
|
||||
if ( mode === 'v1' ) {
|
||||
if ( bytes > policy.v1Bytes ) fail( 'bytes' );
|
||||
v1Parts.push( decoder.decode( value.subarray( start ), { stream: true } ) );
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const tail = decoder.decode();
|
||||
if ( mode === 'v1' ) v1Parts.push( tail );
|
||||
else {
|
||||
lineParts.push( tail );
|
||||
if ( lineBytes || mode === 'first' ) acceptLine( lineParts.join( '' ), lineBytes, false );
|
||||
}
|
||||
let result;
|
||||
if ( mode === 'v1' ) {
|
||||
if ( bytes > policy.v1Bytes ) fail( 'bytes' );
|
||||
header = parseBounded( v1Parts.join( '' ), policy, true );
|
||||
checkHeader( header );
|
||||
if ( header.version !== 1 || ! Array.isArray( header.stdout ) ) fail( 'invalid' );
|
||||
if ( header.stdout.length > policy.events ) fail( 'events' );
|
||||
for ( const event of header.stdout ) {
|
||||
if ( ! Array.isArray( event ) || event.length !== 2 || typeof event[ 1 ] !== 'string' ) fail( 'invalid' );
|
||||
if ( ! boundedTime( event[ 0 ], policy.timelineMs ) ) fail( 'time' );
|
||||
timeMs += event[ 0 ] * 1000;
|
||||
checkTimeline( timeMs );
|
||||
}
|
||||
result = header;
|
||||
} else result = [ header, ...events ];
|
||||
const cols = header.version === 3 ? header.term.cols : header.width;
|
||||
const rows = header.version === 3 ? header.term.rows : header.height;
|
||||
if ( Date.now() >= deadline ) stop( 'timeout' );
|
||||
if ( stoppedError ) throw stoppedError;
|
||||
onMetadata?.( cols > 0 && rows > 0 ? { cols, rows } : null );
|
||||
return result;
|
||||
} catch ( error ) {
|
||||
controller.abort();
|
||||
// Cancellation can itself stall (especially custom/teed streams). Never
|
||||
// await it; the public promise must settle promptly on abort/timeout.
|
||||
try { Promise.resolve( reader?.cancel() ).catch( () => {} ); } catch { /* Already closed. */ }
|
||||
if ( stoppedError ) throw stoppedError;
|
||||
if ( error instanceof RecordingLoadError ) throw error;
|
||||
fail( error instanceof TypeError && reader ? 'invalid' : 'network' );
|
||||
} finally {
|
||||
clearTimeout( totalTimer );
|
||||
signal?.removeEventListener( 'abort', abort );
|
||||
try { reader?.releaseLock(); } catch { /* A rejected read may still be pending. */ }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
/** Only inspect a small prefix; metadata must never buffer a second full cast. */
|
||||
export const MAX_HEADER_BYTES = 64 * 1024;
|
||||
|
||||
/** Original dimensions, without the player's fallback or editor overrides. */
|
||||
export function recordingSizeFromHeader( header ) {
|
||||
if ( ! header || typeof header !== 'object' || Array.isArray( header ) ) return null;
|
||||
let cols;
|
||||
let rows;
|
||||
if ( header.version === 1 || header.version === 2 ) {
|
||||
cols = header.width;
|
||||
rows = header.height;
|
||||
} else if ( header.version === 3 ) {
|
||||
cols = header.term?.cols;
|
||||
rows = header.term?.rows;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
// These are display-only hints, so do not apply the editor override limit.
|
||||
const valid = ( value ) => Number.isSafeInteger( value ) && value > 0;
|
||||
return valid( cols ) && valid( rows ) ? { cols, rows } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read complete top-level JSON members, never regex-match nested fields/output.
|
||||
* v1 is one large JSON object, often pretty-printed, so its dimensions can be
|
||||
* returned before stdout. v2/v3 require their complete first header object.
|
||||
*/
|
||||
function createHeaderReader() {
|
||||
let text = '';
|
||||
let cursor = 0;
|
||||
let memberStart;
|
||||
let quoted = false;
|
||||
let escaped = false;
|
||||
let members = 0;
|
||||
const stack = [];
|
||||
const header = Object.create( null );
|
||||
const unknown = { done: true, size: null };
|
||||
|
||||
return ( chunk ) => {
|
||||
text += chunk;
|
||||
for ( ; cursor < text.length; cursor++ ) {
|
||||
const character = text[ cursor ];
|
||||
if ( memberStart === undefined ) {
|
||||
if ( /\s/.test( character ) ) continue;
|
||||
if ( character !== '{' ) return unknown;
|
||||
stack.push( '{' );
|
||||
memberStart = cursor + 1;
|
||||
continue;
|
||||
}
|
||||
if ( quoted ) {
|
||||
if ( escaped ) escaped = false;
|
||||
else if ( character === '\\' ) escaped = true;
|
||||
else if ( character === '"' ) quoted = false;
|
||||
continue;
|
||||
}
|
||||
if ( character === '"' ) {
|
||||
quoted = true;
|
||||
continue;
|
||||
}
|
||||
if ( character === '{' || character === '[' ) {
|
||||
stack.push( character );
|
||||
continue;
|
||||
}
|
||||
const closing = character === '}' || character === ']';
|
||||
if ( closing && stack.at( -1 ) !== ( character === '}' ? '{' : '[' ) ) return unknown;
|
||||
if ( stack.length === 1 && ( character === ',' || closing ) ) {
|
||||
const member = text.slice( memberStart, cursor ).trim();
|
||||
if ( ! member && ( members || ! closing ) ) return unknown;
|
||||
try {
|
||||
Object.assign( header, JSON.parse( `{${ member }}` ) );
|
||||
} catch {
|
||||
return unknown;
|
||||
}
|
||||
members++;
|
||||
const size = recordingSizeFromHeader( header );
|
||||
if ( closing || ( header.version === 1 && size ) ) return { done: true, size };
|
||||
memberStart = cursor + 1;
|
||||
}
|
||||
if ( closing ) stack.pop();
|
||||
}
|
||||
return { done: false, size: null };
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Inspect a clone of the player's existing response. The original response is
|
||||
* untouched, and callers can pass it to the player while this branch is read.
|
||||
* Missing streams, invalid/oversized headers and read failures stay unknown.
|
||||
*/
|
||||
export async function readRecordingSize( response ) {
|
||||
let reader;
|
||||
try {
|
||||
if ( ! response.ok || ! response.body?.getReader ) return null;
|
||||
reader = response.clone().body.getReader();
|
||||
const decode = new TextDecoder( 'utf-8', { fatal: true } );
|
||||
const readHeader = createHeaderReader();
|
||||
let bytes = 0;
|
||||
while ( bytes < MAX_HEADER_BYTES ) {
|
||||
const { value, done } = await reader.read();
|
||||
if ( done ) return readHeader( decode.decode() ).size;
|
||||
const prefix = value.subarray( 0, MAX_HEADER_BYTES - bytes );
|
||||
bytes += prefix.byteLength;
|
||||
const result = readHeader( decode.decode( prefix, { stream: true } ) );
|
||||
if ( result.done ) return result.size;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
// A cloned Response tees the stream. Awaiting cancellation can wait for
|
||||
// the player's other branch to finish, delaying metadata or deadlocking.
|
||||
if ( reader ) reader.cancel().catch( () => {} );
|
||||
}
|
||||
}
|
||||
+63
-1
@@ -1,15 +1,77 @@
|
||||
.wp-block-lamgc-asciiplayer,
|
||||
.asciiplayer-container {
|
||||
box-sizing: border-box;
|
||||
max-width: 100%;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
/*! rtl:begin:ignore */
|
||||
.asciiplayer-container .ap-wrapper {
|
||||
text-align: left;
|
||||
}
|
||||
/*! rtl:end:ignore */
|
||||
|
||||
.asciiplayer-container[data-ap-status="error"] .asciiplayer-error {
|
||||
padding: 1em;
|
||||
border: 1px solid #b32d2e;
|
||||
}
|
||||
|
||||
/* Keep placement separate from terminal dimensions and from theme floats. */
|
||||
.asciiplayer-figure {
|
||||
box-sizing: border-box;
|
||||
max-width: 100%;
|
||||
min-width: 0;
|
||||
margin-block: 0 1em;
|
||||
}
|
||||
|
||||
/*! rtl:begin:ignore */
|
||||
.asciiplayer-figure.asciiplayer-align-left { margin-left: 0 !important; margin-right: auto !important; }
|
||||
.asciiplayer-figure.asciiplayer-align-center { margin-left: auto !important; margin-right: auto !important; }
|
||||
.asciiplayer-figure.asciiplayer-align-right { margin-left: auto !important; margin-right: 0 !important; }
|
||||
/*! rtl:end:ignore */
|
||||
|
||||
.asciiplayer-figure > .asciiplayer-container { width: 100%; }
|
||||
.asciiplayer-figure > figcaption {
|
||||
margin-block: 0.5em 0;
|
||||
font-size: 0.875em;
|
||||
line-height: 1.5;
|
||||
text-align: center;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
/* Terminal glyph geometry must inherit the size calculated by the player,
|
||||
* not a theme's code-block typography. Scope every reset to our mount points. */
|
||||
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term pre.ap-term-text {
|
||||
border: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: none !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
font-family: inherit !important;
|
||||
font-size: inherit !important;
|
||||
line-height: var(--term-line-height) !important;
|
||||
white-space: pre !important;
|
||||
word-break: normal !important;
|
||||
overflow-wrap: normal !important;
|
||||
text-transform: none !important;
|
||||
}
|
||||
|
||||
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term .ap-line,
|
||||
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-term .ap-line span {
|
||||
font-family: inherit !important;
|
||||
font-size: inherit !important;
|
||||
line-height: inherit !important;
|
||||
letter-spacing: normal !important;
|
||||
white-space: pre !important;
|
||||
text-transform: none !important;
|
||||
}
|
||||
|
||||
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-control-bar button.ap-button {
|
||||
border: 0 !important;
|
||||
box-shadow: none !important;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
:is(.asciiplayer-container, .asciiplayer-editor__player) .ap-control-bar button.ap-button:focus-visible {
|
||||
outline: 2px solid currentColor;
|
||||
outline-offset: 3px;
|
||||
}
|
||||
|
||||
+78
-17
@@ -1,23 +1,52 @@
|
||||
import { __ } from '@wordpress/i18n';
|
||||
import { normalizePlayerOptions, normalizeSource } from './options.js';
|
||||
import { loadRecording, validateInitialDimensions } from './recording-loader.js';
|
||||
import { recordingErrorMessage } from './recording-errors.js';
|
||||
|
||||
const instances = new WeakMap();
|
||||
const documents = new WeakMap();
|
||||
|
||||
function showError( container ) {
|
||||
function showError( container, error ) {
|
||||
const message = recordingErrorMessage( error, { frontend: true } );
|
||||
if ( ! message ) return;
|
||||
container.dataset.apStatus = 'error';
|
||||
if ( container.querySelector( '.asciiplayer-error' ) ) return;
|
||||
const notice = container.ownerDocument.createElement( 'p' );
|
||||
notice.className = 'asciiplayer-error';
|
||||
notice.setAttribute( 'role', 'status' );
|
||||
notice.textContent = __( 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.', 'wp-asciiplayer' );
|
||||
notice.textContent = message;
|
||||
container.appendChild( notice );
|
||||
}
|
||||
|
||||
/** One observer per document, visiting only owned players on removals. */
|
||||
function watchRemoval( container, dispose ) {
|
||||
const document = container.ownerDocument;
|
||||
let state = documents.get( document );
|
||||
if ( ! state ) {
|
||||
const entries = new Map();
|
||||
const observer = new document.defaultView.MutationObserver( ( records ) => {
|
||||
if ( ! records.some( ( record ) => record.removedNodes.length ) ) return;
|
||||
for ( const [ node, cleanup ] of entries ) if ( ! node.isConnected ) cleanup();
|
||||
} );
|
||||
observer.observe( document.documentElement, { childList: true, subtree: true } );
|
||||
state = { entries, observer };
|
||||
documents.set( document, state );
|
||||
}
|
||||
state.entries.set( container, dispose );
|
||||
return () => {
|
||||
state.entries.delete( container );
|
||||
if ( ! state.entries.size ) {
|
||||
state.observer.disconnect();
|
||||
documents.delete( document );
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** One explicit instance per front-end container; never scan an editor canvas. */
|
||||
export function mountPlayers( root = document ) {
|
||||
const ownerDocument = root.ownerDocument || root;
|
||||
if ( ownerDocument.body?.classList.contains( 'wp-admin' ) || ownerDocument.querySelector( '.editor-styles-wrapper, .block-editor-block-list__layout' ) ) return;
|
||||
const api = ownerDocument.defaultView?.AsciinemaPlayer;
|
||||
const canvasWindow = ownerDocument.defaultView;
|
||||
const api = canvasWindow?.AsciinemaPlayer;
|
||||
if ( typeof api?.create !== 'function' ) return;
|
||||
root.querySelectorAll( '.asciiplayer-container' ).forEach( ( container ) => {
|
||||
if ( instances.has( container ) ) return;
|
||||
@@ -25,8 +54,7 @@ export function mountPlayers( root = document ) {
|
||||
if ( ! source ) return showError( container );
|
||||
let options;
|
||||
try {
|
||||
// New markup uses escaped plain JSON. The legacy adapter used URL-encoded
|
||||
// JSON; accepting it also lets cached old pages use the new local player.
|
||||
// Accept both current plain JSON and the legacy URL-encoded options.
|
||||
const serialized = container.dataset.apOptions;
|
||||
options = serialized ? JSON.parse( serialized ) : JSON.parse( decodeURIComponent( container.dataset.apOpts || '{}' ) );
|
||||
if ( ! options || Array.isArray( options ) || typeof options !== 'object' ) throw new Error( 'Invalid player options.' );
|
||||
@@ -35,26 +63,59 @@ export function mountPlayers( root = document ) {
|
||||
showError( container );
|
||||
return;
|
||||
}
|
||||
const request = new canvasWindow.AbortController();
|
||||
let disposed = false;
|
||||
let failed = false;
|
||||
let player;
|
||||
let timer;
|
||||
let unwatch;
|
||||
const dispose = () => {
|
||||
if ( disposed ) return;
|
||||
disposed = true;
|
||||
request.abort();
|
||||
canvasWindow.clearInterval( timer );
|
||||
unwatch?.();
|
||||
player?.dispose();
|
||||
instances.delete( container );
|
||||
};
|
||||
const fail = ( error ) => {
|
||||
if ( disposed || failed || ! recordingErrorMessage( error ) ) return;
|
||||
failed = true;
|
||||
request.abort();
|
||||
canvasWindow.clearInterval( timer );
|
||||
showError( container, error );
|
||||
};
|
||||
const ready = () => {
|
||||
if ( ! disposed && ! failed ) {
|
||||
container.dataset.apStatus = 'ready';
|
||||
canvasWindow.clearInterval( timer );
|
||||
}
|
||||
};
|
||||
try {
|
||||
validateInitialDimensions( options );
|
||||
container.dataset.apStatus = 'loading';
|
||||
const player = api.create( source, container, options );
|
||||
instances.set( container, player );
|
||||
player.addEventListener( 'error', () => showError( container ) );
|
||||
player.addEventListener( 'playing', () => { container.dataset.apStatus = 'ready'; } );
|
||||
// The upstream player owns loading/error/controls; readiness is confirmed
|
||||
// by its parsed duration rather than merely by a mounted DOM wrapper.
|
||||
// The player calls data lazily: preload=false causes no eager request.
|
||||
player = api.create( { data: () => loadRecording( source, {
|
||||
fetchImpl: canvasWindow.fetch.bind( canvasWindow ), signal: request.signal, options,
|
||||
} ).catch( ( error ) => { fail( error ); throw error; } ) }, container, options );
|
||||
instances.set( container, { player, dispose } );
|
||||
unwatch = watchRemoval( container, dispose );
|
||||
player.addEventListener( 'error', () => fail() );
|
||||
player.addEventListener( 'playing', ready );
|
||||
if ( options.preload || options.autoPlay || options.poster?.startsWith( 'npt:' ) ) {
|
||||
let ticks = 0;
|
||||
const timer = ownerDocument.defaultView.setInterval( () => {
|
||||
timer = canvasWindow.setInterval( () => {
|
||||
if ( ! container.isConnected ) return dispose();
|
||||
const duration = player.getDuration();
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) container.dataset.apStatus = 'ready';
|
||||
if ( ! container.isConnected || container.dataset.apStatus !== 'loading' || ++ticks > 200 ) ownerDocument.defaultView.clearInterval( timer );
|
||||
if ( typeof duration === 'number' && Number.isFinite( duration ) ) ready();
|
||||
if ( ++ticks > 200 ) canvasWindow.clearInterval( timer );
|
||||
}, 150 );
|
||||
} else {
|
||||
container.dataset.apStatus = 'idle';
|
||||
}
|
||||
} catch {
|
||||
showError( container );
|
||||
} catch ( error ) {
|
||||
fail( error );
|
||||
dispose();
|
||||
}
|
||||
} );
|
||||
}
|
||||
|
||||
+40
-2
@@ -13,8 +13,12 @@ npm ci
|
||||
npm run build
|
||||
npm test
|
||||
npm run package
|
||||
mkdir -p .wp-env-uploads
|
||||
npm run wp-env -- start
|
||||
npm run wp-env -- run cli wp plugin install /var/www/html/wp-content/asciiplayer-packages/wp-asciiplayer.zip --activate --force
|
||||
npm run wp-env -- run cli wp language core install zh_CN
|
||||
npm run wp-env -- run cli wp site switch-language en_US
|
||||
npm run wp-env -- run cli wp user meta update admin locale en_US
|
||||
npx --no-install playwright install chromium
|
||||
npm run test:e2e
|
||||
npm run wp-env -- stop
|
||||
@@ -29,6 +33,8 @@ The plugin's source tree is deliberately not mounted as an active plugin in the
|
||||
committed wp-env configuration. The build ZIP is installed into WordPress through
|
||||
WP-CLI, so missing package files cause a real integration failure. Fixtures are
|
||||
mapped under uploads; the package directory is mapped separately for WP-CLI.
|
||||
The host-owned .wp-env-uploads directory keeps real Media Library uploads writable
|
||||
without relaxing file modes or modifying the fixture files.
|
||||
|
||||
## Coverage
|
||||
|
||||
@@ -42,8 +48,22 @@ mapped under uploads; the package directory is mapped separately for WP-CLI.
|
||||
- Actual terminal output proves successful front-end parsing/playback
|
||||
- Editor and front-end requests must not load plugin assets from jsDelivr
|
||||
|
||||
The preview intentionally requires an Apply URL / Load preview action for each
|
||||
editing session before contacting the recording server. Tests respect that gate.
|
||||
The preview automatically loads valid saved URLs and debounces typed changes.
|
||||
Tests check the request count, stale-response cleanup, immediate Apply, error
|
||||
retry, and no requests for empty/invalid URLs or static inserter examples.
|
||||
Floating-toolbar dimension controls are checked against the collapsed sidebar,
|
||||
including keyboard focus, Escape/close/reopen, and shared attribute values.
|
||||
Both controls show the recording header's native columns and rows as placeholders
|
||||
without saving overrides. URL replacement, pending/error/invalid sources and late
|
||||
responses cover metadata cleanup; recorded resize events still control blank axes.
|
||||
Pretty-printed v1 and comment-bearing v3 fixtures also exercise actual parsing,
|
||||
native-size placeholders and playback output, alongside the existing v2 fixtures.
|
||||
|
||||
Media Library tests use WordPress's real upload dialog, file input and attachment
|
||||
tiles. They upload a valid `.cast`, select and play it without Apply URL, cancel a
|
||||
replacement, reopen to select the existing replacement, and reload the saved URL.
|
||||
A malformed `.cast` must be rejected by the real upload endpoint and shown as an
|
||||
upload error. These tests create small attachments in the isolated wp-env database.
|
||||
|
||||
## CI evidence and limits
|
||||
|
||||
@@ -65,3 +85,21 @@ References:
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/
|
||||
- https://developer.wordpress.org/block-editor/reference-guides/block-api/block-api-versions/block-migration-for-iframe-editor-compatibility/
|
||||
- https://github.com/WordPress/plugin-check/blob/trunk/docs/CLI.md
|
||||
|
||||
Native recording-size hints are checked against v1/v2/v3 headers, explicit
|
||||
overrides, URL replacement, error/empty states and recorded resize events.
|
||||
The Media Library tests use actual isolated WordPress upload dialogs to upload
|
||||
validated fixtures, reject malformed casts, cancel/reopen and select an existing
|
||||
recording. No production-site media is accessed.
|
||||
|
||||
## Plugin localization
|
||||
|
||||
Five `@i18n` cases set real site and user languages via the authenticated WordPress
|
||||
REST API, covering all en_US/zh_CN combinations and site-default inheritance.
|
||||
They verify bundled PHP upload errors, editor metadata and controls, recoverable
|
||||
preview errors, and logged-in/anonymous frontend messages. Author captions and
|
||||
actual recording content remain unchanged, and upstream player controls stay
|
||||
English. Original site/user locale values are restored after each test.
|
||||
Run these only against the isolated test site, with zh_CN installed first.
|
||||
CI runs the existing English suite before the locale suite and retains separate
|
||||
reports/screenshots. No catalog data is injected into the browser by the tests.
|
||||
|
||||
+207
-11
@@ -53,13 +53,6 @@ async function readyPreview(block) {
|
||||
await expect(block.locator('.ap-wrapper')).toBeVisible();
|
||||
}
|
||||
|
||||
async function loadPreview(block) {
|
||||
await expect(block).toBeVisible();
|
||||
const load = block.getByRole('button', { name: 'Load preview', exact: true });
|
||||
if (await load.count()) await load.click();
|
||||
await readyPreview(block);
|
||||
}
|
||||
|
||||
async function publish(page, title) {
|
||||
return page.evaluate(async (postTitle) => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
@@ -145,12 +138,12 @@ test('real iframe preview survives edits, duplicate, delete, undo, save and relo
|
||||
await window.wp.data.dispatch('core/block-editor').duplicateBlocks([clientId]);
|
||||
return window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer' && entry.clientId !== clientId).clientId;
|
||||
}, id);
|
||||
await loadPreview(playerBlock(page, duplicateId));
|
||||
await readyPreview(playerBlock(page, duplicateId));
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
|
||||
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(1);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
|
||||
await loadPreview(playerBlock(page, duplicateId));
|
||||
await readyPreview(playerBlock(page, duplicateId));
|
||||
await expect(canvas(page).locator('.asciiplayer-editor__player .ap-wrapper')).toHaveCount(2);
|
||||
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), duplicateId);
|
||||
|
||||
@@ -161,7 +154,7 @@ test('real iframe preview survives edits, duplicate, delete, undo, save and relo
|
||||
const reloaded = await page.evaluate(() => window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === 'lamgc/asciiplayer'));
|
||||
expect(reloaded.name).toBe(blockName);
|
||||
expect(reloaded.attributes).toMatchObject({ source, speed: 1.5, theme: 'solarized-dark' });
|
||||
await loadPreview(playerBlock(page, reloaded.clientId));
|
||||
await readyPreview(playerBlock(page, reloaded.clientId));
|
||||
|
||||
await page.goto(saved.url);
|
||||
const container = page.locator('.asciiplayer-container');
|
||||
@@ -177,7 +170,7 @@ test('a published Page plays its block at desktop and mobile widths', async ({ p
|
||||
await openEditor(page, 'page');
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const id = await insertPlayer(page, { source, controls: 'always', preload: true });
|
||||
await loadPreview(playerBlock(page, id));
|
||||
await readyPreview(playerBlock(page, id));
|
||||
const saved = await publish(page, 'Page playback integration');
|
||||
await page.goto(saved.url);
|
||||
const container = page.locator('.asciiplayer-container');
|
||||
@@ -259,3 +252,206 @@ test('a real cross-origin server without CORS permission shows an error and reco
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
|
||||
test('a saved Recording URL loads once without a click and never autoplays in the editor', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=saved`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const requests = [];
|
||||
await page.route(source, async (route) => {
|
||||
requests.push(route.request().url());
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page, { source, autoPlay: true, preload: false });
|
||||
const block = playerBlock(page, id);
|
||||
await readyPreview(block);
|
||||
await expect(block.getByRole('button', { name: 'Load preview', exact: true })).toHaveCount(0);
|
||||
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
|
||||
await expect(block.locator('.asciiplayer-editor__privacy')).toHaveCount(0);
|
||||
await expect(block.locator(':scope > .asciiplayer-editor__hint')).toHaveCount(0);
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: 'Choose recording', exact: true })).toBeVisible();
|
||||
await expect(block.locator('figcaption[contenteditable="true"]')).toBeVisible();
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const helpToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Help$/ });
|
||||
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await helpToggle.click();
|
||||
const help = page.locator('.components-panel__body').filter({ has: helpToggle });
|
||||
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/automatic/i);
|
||||
await expect(help.locator('.asciiplayer-editor__privacy')).toContainText(/server/i);
|
||||
await expect(help).toContainText('Use the player controls to play, pause, and seek.');
|
||||
await helpToggle.click();
|
||||
await expect(helpToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await page.waitForTimeout(750); // Catch a second fetch from a pending debounce.
|
||||
expect(requests).toEqual([source]);
|
||||
await expect(block.locator('.ap-overlay-start .ap-play-button')).toBeVisible();
|
||||
});
|
||||
|
||||
test('rapid URL edits debounce to one recording fetch and Apply cancels its pending debounce', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const prefix = new URL(`${fixturePath}?automatic=`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const requests = [];
|
||||
await page.route(`${prefix}*`, async (route) => {
|
||||
requests.push(route.request().url());
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page);
|
||||
const block = playerBlock(page, id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(`${prefix}first`);
|
||||
await input.fill(`${prefix}second`);
|
||||
await input.fill(`${prefix}final`);
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toEqual([`${prefix}final`]);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(`${prefix}final`);
|
||||
await input.fill(`${prefix}applied`);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await expect.poll(() => requests).toEqual([`${prefix}final`, `${prefix}applied`]);
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toEqual([`${prefix}final`, `${prefix}applied`]);
|
||||
});
|
||||
|
||||
test('replacing a pending recording ignores its stale response', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=stale`, page.url()).href;
|
||||
const latest = new URL(`${fixturePath}?automatic=latest`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url), 'utf8');
|
||||
let release;
|
||||
const pending = new Promise((resolve) => { release = resolve; });
|
||||
let oldRequested = false;
|
||||
let oldResponseSettled = false;
|
||||
await page.route(source, async (route) => {
|
||||
oldRequested = true;
|
||||
await pending;
|
||||
// Aborting a replaced player may cancel this intercepted request. Both
|
||||
// cancellation and safely ignoring a late response are valid outcomes.
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording.replace('"width":64', '"width":120') }).catch(() => {});
|
||||
oldResponseSettled = true;
|
||||
});
|
||||
await page.route(latest, (route) => route.fulfill({ contentType: 'text/plain', body: recording }));
|
||||
try {
|
||||
const id = await insertPlayer(page, { source });
|
||||
const block = playerBlock(page, id);
|
||||
await expect.poll(() => oldRequested).toBe(true);
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(latest);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(latest);
|
||||
await readyPreview(block);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
release();
|
||||
await expect.poll(() => oldResponseSettled).toBe(true);
|
||||
await page.waitForTimeout(750);
|
||||
await readyPreview(block);
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) =>
|
||||
Number(terminal.style.getPropertyValue('--term-cols'))
|
||||
)).toBe(64);
|
||||
// A late header from the old 120-column cast must not become a hint.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(latest);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
|
||||
test('automatic preview errors retry the unchanged URL through Retry preview and Apply URL', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(`${fixturePath}?automatic=retry`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
let requests = 0;
|
||||
await page.route(source, async (route) => {
|
||||
requests += 1;
|
||||
await route.fulfill(requests < 3
|
||||
? { status: 503, contentType: 'text/plain', body: 'Temporarily unavailable' }
|
||||
: { contentType: 'text/plain', body: recording });
|
||||
});
|
||||
const id = await insertPlayer(page, { source });
|
||||
const block = playerBlock(page, id);
|
||||
const preview = block.locator('.asciiplayer-editor__preview');
|
||||
await expect(preview).toHaveAttribute('data-preview-status', 'error');
|
||||
expect(requests).toBe(1);
|
||||
await block.getByRole('button', { name: 'Retry preview', exact: true }).click();
|
||||
await expect.poll(() => requests).toBe(2);
|
||||
await expect(preview).toHaveAttribute('data-preview-status', 'error');
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await page.waitForTimeout(750);
|
||||
expect(requests).toBe(3);
|
||||
});
|
||||
|
||||
test('empty and invalid sources never create a preview or fetch a recording', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const requests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) requests.push(request.url());
|
||||
});
|
||||
const emptyId = await insertPlayer(page);
|
||||
const empty = playerBlock(page, emptyId);
|
||||
const invalidId = await insertPlayer(page, { source: 'javascript:alert(1)' });
|
||||
const invalid = playerBlock(page, invalidId);
|
||||
await expect(empty.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
await expect(invalid.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('javascript:alert(1)');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await expect(invalid.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
const input = empty.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(new URL(fixturePath, page.url()).href);
|
||||
await input.fill('');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await input.fill('https://');
|
||||
await page.waitForTimeout(750);
|
||||
await expect(empty.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
test('external source changes and undo clear an invalid draft error and restore the valid preview', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const original = new URL(`${fixturePath}?automatic=undo-original`, page.url()).href;
|
||||
const replacement = new URL(`${fixturePath}?automatic=undo-replacement`, page.url()).href;
|
||||
const id = await insertPlayer(page, { source: original });
|
||||
const block = playerBlock(page, id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
const validation = block.locator('.asciiplayer-editor__source .components-notice');
|
||||
await readyPreview(block);
|
||||
// Save a baseline so Undo below targets the external source replacement,
|
||||
// rather than an insertion or another edit batched into the same history.
|
||||
await publish(page, 'Automatic preview source synchronization regression');
|
||||
await input.fill('https://');
|
||||
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await page.evaluate(({ clientId, source }) =>
|
||||
window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, { source }),
|
||||
{ clientId: id, source: replacement });
|
||||
await expect(input).toHaveValue(replacement);
|
||||
await readyPreview(block);
|
||||
await expect(validation).toHaveCount(0);
|
||||
// An invalid local draft does not change the saved source or undo history.
|
||||
await input.fill('javascript:alert(1)');
|
||||
await expect(validation).toContainText('Enter an HTTP(S) recording URL');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/editor').undo());
|
||||
await expect(input).toHaveValue(original);
|
||||
await readyPreview(block);
|
||||
await expect(validation).toHaveCount(0);
|
||||
await page.waitForTimeout(750); // A canceled invalid-draft timer cannot reappear.
|
||||
await expect(validation).toHaveCount(0);
|
||||
await expect.poll(() => page.evaluate((clientId) =>
|
||||
window.wp.data.select('core/block-editor').getBlockAttributes(clientId).source, id
|
||||
)).toBe(original);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,341 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { DEFAULT_LIMITS } from '../../src/recording-loader.js';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
const messages = {
|
||||
markers: 'This recording contains too many markers.',
|
||||
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
|
||||
cells: 'This recording requests too many terminal cells.',
|
||||
};
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
function canvas(page) {
|
||||
return page.frameLocator('iframe[name="editor-canvas"]');
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: canvas(page).locator(`[data-block="${id}"]`) };
|
||||
}
|
||||
|
||||
async function removePlayer(page, id) {
|
||||
await page.evaluate((clientId) => window.wp.data.dispatch('core/block-editor').removeBlocks([clientId]), id);
|
||||
await expect(canvas(page).locator(`[data-block="${id}"]`)).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function changeSource(block, source) {
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(source);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(block.locator('.ap-term')).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectGrid(block, cols, rows) {
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}))).toEqual({ cols, rows });
|
||||
}
|
||||
|
||||
async function dimensions(page) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toBeVisible();
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
async function expectNativeSize(page, cols, rows) {
|
||||
const controls = await dimensions(page);
|
||||
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
|
||||
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
|
||||
return controls;
|
||||
}
|
||||
|
||||
function recording(version = 2, { cols = 64, rows = 12, label = 'bounded', events } = {}) {
|
||||
const output = (part) => `\u001b[2J\u001b[H${part} ${label}\r\n`;
|
||||
if (version === 1) {
|
||||
return JSON.stringify({ version, width: cols, height: rows, duration: 12, stdout: [
|
||||
[0, output('START')], [8, output('SEEK')], [4, output('END')],
|
||||
] }, null, 2);
|
||||
}
|
||||
const header = version === 3 ? { version, term: { cols, rows } } : { version, width: cols, height: rows };
|
||||
const frames = events || [[0, 'o', output('START')], [8, 'o', output('SEEK')], [version === 3 ? 4 : 12, 'o', output('END')]];
|
||||
// The bundled parser permits blank/comment lines after either JSONL header.
|
||||
// Routing the original bytes tests compatibility through the real loader.
|
||||
return `${JSON.stringify(header)}\n\n# An ignored comment before output.\n${frames.map(JSON.stringify).join('\n\n# Between events.\n')}\n`;
|
||||
}
|
||||
|
||||
async function routeRecording(page, name, body) {
|
||||
const source = new URL(`${fixtureRoot}/bounded-${name}.cast`, page.url()).href;
|
||||
let requests = 0;
|
||||
await page.route(source, async (route) => {
|
||||
requests += 1;
|
||||
await route.fulfill({ contentType: 'text/plain; charset=utf-8', body });
|
||||
});
|
||||
return { source, requests: () => requests };
|
||||
}
|
||||
|
||||
async function playAndSeek(block, label) {
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`);
|
||||
const playback = block.locator('.ap-playback-button');
|
||||
await expect(playback).toHaveAttribute('aria-label', 'Pause');
|
||||
await playback.click();
|
||||
await expect(playback).toHaveAttribute('aria-label', 'Play');
|
||||
// The real player's numeric shortcuts seek to 80% and then back to 0%.
|
||||
// The second frame is eight seconds in, so this cannot pass by just playing.
|
||||
await block.locator('.ap-term-text').press('8');
|
||||
await expect(block.locator('.ap-term-text')).toContainText(`SEEK ${label}`);
|
||||
await expect(block.locator('.ap-term-text')).not.toContainText(`START ${label}`);
|
||||
await block.locator('.ap-term-text').press('0');
|
||||
await expect(block.locator('.ap-term-text')).toContainText(`START ${label}`);
|
||||
await expect(block.locator('.ap-term-text')).not.toContainText(`SEEK ${label}`);
|
||||
}
|
||||
|
||||
for (const version of [1, 2, 3]) {
|
||||
test(`bounded v${version} recordings play and seek in the editor iframe, including zero header dimensions`, async ({ page }) => {
|
||||
await openEditor(page);
|
||||
for (const zero of [false, true]) {
|
||||
const label = `v${version}-${zero ? 'zero' : 'native'}`;
|
||||
const routed = await routeRecording(page, label, recording(version, {
|
||||
cols: zero ? 0 : 64, rows: zero ? 0 : 12, label,
|
||||
}));
|
||||
const { id, block } = await insertPlayer(page, { source: routed.source, controls: 'always' });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, zero ? 80 : 64, zero ? 24 : 12);
|
||||
const controls = await expectNativeSize(page, zero ? undefined : 64, zero ? undefined : 12);
|
||||
await expect(controls.columns).toHaveValue('');
|
||||
await expect(controls.rows).toHaveValue('');
|
||||
await playAndSeek(block, label);
|
||||
// Native-size hints and seeks must reuse the same validated fetch.
|
||||
expect(routed.requests()).toBe(1);
|
||||
const attributes = await page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
expect(attributes.cols).toBeUndefined();
|
||||
expect(attributes.rows).toBeUndefined();
|
||||
await removePlayer(page, id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const firstUnsafeRows = Math.floor(DEFAULT_LIMITS.cells / DEFAULT_LIMITS.dimension) + 1;
|
||||
const rejectedRecordings = [
|
||||
{
|
||||
name: 'marker count limit', code: 'markers',
|
||||
body: () => recording(2, { events: Array.from({ length: DEFAULT_LIMITS.markers + 1 }, (_, index) => [index / 1000, 'm', 'marker']) }),
|
||||
},
|
||||
{
|
||||
name: 'resize axis limit', code: 'dimensions',
|
||||
body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension + 1}x12`]] }),
|
||||
},
|
||||
{
|
||||
name: 'resize cell limit', code: 'cells',
|
||||
body: () => recording(3, { events: [[0, 'o', 'safe'], [1, 'r', `${DEFAULT_LIMITS.dimension}x${firstUnsafeRows}`]] }),
|
||||
},
|
||||
{
|
||||
name: 'initial terminal dimensions before player creation', code: 'cells', noFetch: true,
|
||||
attributes: { cols: DEFAULT_LIMITS.dimension, rows: firstUnsafeRows },
|
||||
body: () => recording(),
|
||||
},
|
||||
{
|
||||
name: 'effective resize dimensions with one overridden axis', code: 'cells',
|
||||
attributes: { cols: DEFAULT_LIMITS.dimension },
|
||||
body: () => recording(2, { events: [[0, 'o', 'safe'], [1, 'r', `64x${firstUnsafeRows}`]] }),
|
||||
},
|
||||
];
|
||||
|
||||
for (const entry of rejectedRecordings) {
|
||||
test(`bounded preview rejects ${entry.name} with a useful error and recovers`, async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const rejected = await routeRecording(page, `reject-${entry.code}`, entry.body());
|
||||
const valid = await routeRecording(page, 'recovery', recording(2, { label: 'recovered' }));
|
||||
const { id, block } = await insertPlayer(page, { source: rejected.source, ...entry.attributes });
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await expect(block.locator('.components-notice')).toContainText(messages[entry.code]);
|
||||
await expect(block.getByRole('button', { name: 'Retry preview', exact: true })).toBeVisible();
|
||||
await expectNativeSize(page);
|
||||
expect(rejected.requests()).toBe(entry.noFetch ? 0 : 1);
|
||||
if (entry.noFetch) await expect(block.locator('.ap-wrapper')).toHaveCount(0);
|
||||
// Remove intentional overrides while changing source in one store update,
|
||||
// so recovery cannot fail for the previous effective-size violation.
|
||||
await page.evaluate(({ clientId, source }) => window.wp.data.dispatch('core/block-editor').updateBlockAttributes(clientId, {
|
||||
source, cols: undefined, rows: undefined,
|
||||
}), { clientId: id, source: valid.source });
|
||||
await readyPreview(block);
|
||||
await expect(block.locator('.components-notice')).toHaveCount(0);
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await expectGrid(block, 64, 12);
|
||||
await playAndSeek(block, 'recovered');
|
||||
expect(valid.requests()).toBe(1);
|
||||
});
|
||||
}
|
||||
|
||||
test('bounded playback preserves independent dimension overrides across recorded resizes', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const routed = await routeRecording(page, 'safe-overrides', recording(2, { events: [
|
||||
[0, 'o', 'Original terminal\r\n'], [8, 'r', '100x30'], [8, 'o', 'Resized terminal\r\n'], [12, 'o', 'Finished\r\n'],
|
||||
] }));
|
||||
for (const rows of [undefined, 20]) {
|
||||
const { id, block } = await insertPlayer(page, { source: routed.source, cols: 80, rows, controls: 'always' });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 80, rows || 12);
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Original terminal');
|
||||
await block.locator('.ap-playback-button').click();
|
||||
await block.locator('.ap-term-text').press('8');
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Resized terminal');
|
||||
await expectGrid(block, 80, rows || 30);
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await removePlayer(page, id);
|
||||
}
|
||||
expect(routed.requests()).toBe(2);
|
||||
});
|
||||
|
||||
function deferred() {
|
||||
let release;
|
||||
const promise = new Promise((resolve) => { release = resolve; });
|
||||
return { promise, release };
|
||||
}
|
||||
|
||||
async function observeNativeFetch(page) {
|
||||
await canvas(page).locator('body').evaluate((body) => {
|
||||
const window = body.ownerDocument.defaultView;
|
||||
const fetch = window.fetch;
|
||||
window.__boundedFetches = [];
|
||||
// Observation only: retain the actual browser fetch, Response/stream,
|
||||
// player, parser, and AbortController. No player API is mocked.
|
||||
window.fetch = function (source, options) {
|
||||
const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) };
|
||||
window.__boundedFetches.push(entry);
|
||||
options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true });
|
||||
return fetch.call(this, source, options);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function expectFetchAborted(page, source) {
|
||||
await expect.poll(() => canvas(page).locator('body').evaluate((body, url) =>
|
||||
body.ownerDocument.defaultView.__boundedFetches?.find((entry) => entry.source === url)?.aborted, source
|
||||
)).toBe(true);
|
||||
}
|
||||
|
||||
for (const action of ['change URL', 'unmount block']) {
|
||||
test(`${action} aborts an in-flight bounded fetch and ignores its delayed result`, async ({ page }) => {
|
||||
await openEditor(page);
|
||||
await observeNativeFetch(page);
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
const oldSource = new URL(`${fixtureRoot}/bounded-delayed.cast`, page.url()).href;
|
||||
const current = await routeRecording(page, 'current', recording(2, { label: 'current' }));
|
||||
const gate = deferred();
|
||||
let requested = false;
|
||||
let settled = false;
|
||||
await page.route(oldSource, async (route) => {
|
||||
requested = true;
|
||||
await gate.promise;
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording(2, { cols: 120, rows: 30, label: 'stale' }) }).catch(() => {});
|
||||
settled = true;
|
||||
});
|
||||
try {
|
||||
const old = await insertPlayer(page, { source: oldSource });
|
||||
await expect.poll(() => requested).toBe(true);
|
||||
let active = old;
|
||||
if (action === 'change URL') await changeSource(old.block, current.source);
|
||||
else {
|
||||
await removePlayer(page, old.id);
|
||||
active = await insertPlayer(page, { source: current.source });
|
||||
}
|
||||
await expectFetchAborted(page, oldSource);
|
||||
await readyPreview(active.block);
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await active.block.locator('.ap-term').evaluate((terminal) => { terminal.dataset.boundedIdentity = 'current'; });
|
||||
gate.release();
|
||||
await expect.poll(() => settled).toBe(true);
|
||||
await readyPreview(active.block);
|
||||
await expect(active.block.locator('.ap-term')).toHaveAttribute('data-bounded-identity', 'current');
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await expectGrid(active.block, 64, 12);
|
||||
await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1);
|
||||
await playAndSeek(active.block, 'current');
|
||||
expect(current.requests()).toBe(1);
|
||||
expect(pageErrors).toEqual([]);
|
||||
} finally {
|
||||
gate.release();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const action of ['change URL', 'unmount block']) {
|
||||
test(`${action} while player assets are pending never starts the stale recording fetch`, async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
const old = await routeRecording(page, 'before-assets', recording(2, { cols: 120, rows: 30, label: 'stale' }));
|
||||
const current = await routeRecording(page, 'after-assets', recording(2, { label: 'current' }));
|
||||
const scriptUrl = await page.evaluate(() => window.wpAsciiplayerSettings.playerScriptUrl);
|
||||
expect(await canvas(page).locator('body').evaluate((body) => typeof body.ownerDocument.defaultView.AsciinemaPlayer)).toBe('undefined');
|
||||
const gate = deferred();
|
||||
let assetRequested = false;
|
||||
await page.route(scriptUrl, async (route) => {
|
||||
assetRequested = true;
|
||||
await gate.promise;
|
||||
// Resume the installed plugin's real local asset, not a test double.
|
||||
await route.continue().catch(() => {});
|
||||
});
|
||||
try {
|
||||
let active = await insertPlayer(page, { source: old.source });
|
||||
await expect.poll(() => assetRequested).toBe(true);
|
||||
await expect(active.block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'loading');
|
||||
if (action === 'change URL') await changeSource(active.block, current.source);
|
||||
else {
|
||||
await removePlayer(page, active.id);
|
||||
active = await insertPlayer(page, { source: current.source });
|
||||
}
|
||||
expect(old.requests()).toBe(0);
|
||||
expect(current.requests()).toBe(0);
|
||||
gate.release();
|
||||
await readyPreview(active.block);
|
||||
await expectNativeSize(page, 64, 12);
|
||||
await expectGrid(active.block, 64, 12);
|
||||
await expect(canvas(page).locator('.ap-wrapper')).toHaveCount(1);
|
||||
await playAndSeek(active.block, 'current');
|
||||
expect(old.requests()).toBe(0);
|
||||
expect(current.requests()).toBe(1);
|
||||
expect(pageErrors).toEqual([]);
|
||||
} finally {
|
||||
gate.release();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
import { test as base, expect } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
const copy = {
|
||||
en_US: {
|
||||
title: 'Asciicast Player', source: 'Recording URL', apply: 'Apply URL',
|
||||
choose: 'Choose recording', dimensions: 'Terminal size', columns: 'Columns', rows: 'Rows',
|
||||
help: 'Help', retry: 'Retry preview', captionLabel: 'Recording caption',
|
||||
previewError: 'Unable to load the recording. Check the URL, file format, and the source server’s CORS permissions.',
|
||||
frontendError: 'Unable to load this terminal recording. The file may be unavailable, invalid, or blocked by the source server’s CORS policy.',
|
||||
uploadError: 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).',
|
||||
},
|
||||
zh_CN: {
|
||||
title: 'Asciicast 播放器', source: '录制文件 URL', apply: '应用 URL',
|
||||
choose: '选择录制文件', dimensions: '终端尺寸', columns: '列数', rows: '行数',
|
||||
help: '帮助', retry: '重试预览', captionLabel: '录屏说明文字',
|
||||
previewError: '无法加载录制文件。请检查 URL、文件格式及来源服务器的跨域请求(CORS)权限。',
|
||||
frontendError: '无法加载此终端录屏。文件可能无法访问、格式无效,或被来源服务器的跨域请求(CORS)策略阻止。',
|
||||
uploadError: '请上传有效的 Asciicast v2/v3 JSONL 或 v1 .cast 录屏(最大 32 MiB;v1 最大 2 MiB、100,000 个事件、每行 JSONL 最大 256 KiB、1,000 个时间标记、1,000 列或行、40,000 个终端单元格,且 JSON 结构复杂度受限)。',
|
||||
},
|
||||
};
|
||||
|
||||
async function login(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
}
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.apiFetch && window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
// Change actual WordPress settings, never navigator.language or wp.i18n mocks.
|
||||
// Keep an authenticated control page alive so cleanup also works if a test
|
||||
// finishes on the public site or fails during a player/media interaction.
|
||||
const test = base.extend({
|
||||
localeSession: async ({ context }, use) => {
|
||||
const control = await context.newPage();
|
||||
await login(control);
|
||||
await control.goto('/wp-admin/profile.php');
|
||||
const language = control.locator('#locale');
|
||||
await expect(language, 'Install the zh_CN core language pack before this suite.').toBeVisible();
|
||||
await expect(language.locator('option[value="zh_CN"]')).toHaveCount(1);
|
||||
const selectedUserLocale = await language.inputValue();
|
||||
const originalUserLocale = selectedUserLocale === 'site-default' ? '' : selectedUserLocale;
|
||||
await openEditor(control);
|
||||
const originalSiteLocale = await control.evaluate(async () =>
|
||||
(await window.wp.apiFetch({ path: '/wp/v2/settings' })).language
|
||||
);
|
||||
const setLocales = async (siteLocale, userLocale) => control.evaluate(async ({ site, user }) => {
|
||||
const settings = await window.wp.apiFetch({ path: '/wp/v2/settings', method: 'POST', data: { language: site } });
|
||||
const currentUser = await window.wp.apiFetch({ path: '/wp/v2/users/me', method: 'POST', data: { locale: user } });
|
||||
return { site: settings.language || 'en_US', user: currentUser.locale };
|
||||
}, { site: siteLocale, user: userLocale });
|
||||
try {
|
||||
await use({ setLocales, control });
|
||||
} finally {
|
||||
await setLocales(originalSiteLocale, originalUserLocale);
|
||||
await control.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
async function insertPlayer(page) {
|
||||
const id = await page.evaluate((name) => {
|
||||
const block = window.wp.blocks.createBlock(name, { controls: 'always' });
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, blockName);
|
||||
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
|
||||
}
|
||||
|
||||
async function assertTranslatedError(locator, locale, kind) {
|
||||
// Expected strings are independent literals, never read from the loaded
|
||||
// catalog: a missing translation must fail instead of defining expectations.
|
||||
await expect(locator).toHaveText(copy[locale][kind]);
|
||||
}
|
||||
|
||||
async function rejectInvalidUpload(page, block, locale, testInfo) {
|
||||
await block.getByRole('button', { name: copy[locale].choose, exact: true }).click();
|
||||
const dialog = page.locator('.media-modal[role="dialog"]');
|
||||
await expect(dialog).toBeVisible();
|
||||
await dialog.locator('#menu-item-upload').click();
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({
|
||||
name: `asciiplayer-locale-invalid-${Date.now()}-${testInfo.retry}.cast`,
|
||||
mimeType: 'application/x-asciicast',
|
||||
buffer: await readFile(new URL('../fixtures/malformed.cast', import.meta.url)),
|
||||
});
|
||||
const result = await (await response).json();
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
expect(result.data.message).toBe(copy[locale].uploadError);
|
||||
await expect(dialog).toContainText(result.data.message);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
}
|
||||
|
||||
async function verifyFrontend(page, url, locale) {
|
||||
await page.goto(url);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', locale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
|
||||
const players = page.locator('.asciiplayer-container');
|
||||
await expect(players).toHaveCount(3);
|
||||
await assertTranslatedError(players.nth(1).locator('.asciiplayer-error'), locale, 'frontendError');
|
||||
for (const index of [0, 2]) {
|
||||
const player = players.nth(index);
|
||||
await expect(player.locator('.ap-wrapper')).toBeVisible();
|
||||
await player.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(player.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
}
|
||||
await expect(page.locator('.asciiplayer-figure figcaption')).toHaveText('Author caption / 作者说明');
|
||||
}
|
||||
|
||||
test.describe('@i18n real WordPress site and user locales', () => {
|
||||
// Locale is site-global. The repository config has one worker; do not run
|
||||
// these cases concurrently against a shared WordPress database.
|
||||
test.describe.configure({ mode: 'default' });
|
||||
for (const [siteLocale, userLocale] of [
|
||||
['en_US', 'en_US'], ['zh_CN', 'zh_CN'],
|
||||
['zh_CN', 'en_US'], ['en_US', 'zh_CN'],
|
||||
]) {
|
||||
test(`site ${siteLocale}, user ${userLocale}: editor, PHP upload and public player`, async ({ page, browser, localeSession }, testInfo) => {
|
||||
test.setTimeout(150_000);
|
||||
const locales = await localeSession.setLocales(siteLocale, userLocale);
|
||||
expect(locales).toEqual({ site: siteLocale, user: userLocale });
|
||||
const ui = copy[userLocale];
|
||||
const pageErrors = [];
|
||||
page.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await openEditor(page);
|
||||
await expect(page.locator('html')).toHaveAttribute('lang', userLocale === 'zh_CN' ? /^zh-(CN|Hans)$/ : 'en-US');
|
||||
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(ui.title);
|
||||
const block = await insertPlayer(page);
|
||||
const source = block.getByRole('textbox', { name: ui.source, exact: true });
|
||||
await expect(source).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: ui.apply, exact: true })).toBeVisible();
|
||||
await expect(block.getByRole('button', { name: ui.choose, exact: true })).toBeVisible();
|
||||
await expect(block.locator('figcaption[contenteditable="true"]')).toHaveAttribute('aria-label', ui.captionLabel);
|
||||
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.dimensions}$`) }).click();
|
||||
await expect(page.getByRole('spinbutton', { name: ui.columns, exact: true })).toBeVisible();
|
||||
await expect(page.getByRole('spinbutton', { name: ui.rows, exact: true })).toBeVisible();
|
||||
await expect(page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${ui.help}$`) })).toBeVisible();
|
||||
|
||||
const valid = new URL(`${fixturePath}/hello.cast`, page.url()).href;
|
||||
const missing = new URL(`${fixturePath}/missing-i18n.cast`, page.url()).href;
|
||||
await source.fill(missing);
|
||||
await block.getByRole('button', { name: ui.apply, exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await assertTranslatedError(block.locator('.components-notice__content > p'), userLocale, 'previewError');
|
||||
await expect(block.getByRole('button', { name: ui.retry, exact: true })).toBeVisible();
|
||||
await source.fill(valid);
|
||||
await block.getByRole('button', { name: ui.apply, exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
// Upstream 3.17.0 has no localization API. Its unmodified controls
|
||||
// deliberately retain their English accessibility labels in both locales.
|
||||
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Pause');
|
||||
await block.locator('.ap-playback-button').click();
|
||||
await expect(block.locator('.ap-playback-button')).toHaveAttribute('aria-label', 'Play');
|
||||
await rejectInvalidUpload(page, block, userLocale, testInfo);
|
||||
|
||||
const editorShot = testInfo.outputPath(`editor-${siteLocale}-${userLocale}.png`);
|
||||
await page.screenshot({ path: editorShot, fullPage: true });
|
||||
await testInfo.attach('editor-locale', { path: editorShot, contentType: 'image/png' });
|
||||
const saved = await page.evaluate(async ({ name, good, bad }) => {
|
||||
const blockContent = window.wp.blocks.serialize(window.wp.blocks.createBlock(name, {
|
||||
source: good, controls: 'always', preload: true, caption: 'Author caption / 作者说明',
|
||||
}));
|
||||
return window.wp.apiFetch({ path: '/wp/v2/posts', method: 'POST', data: {
|
||||
title: `Asciiplayer locale integration ${Date.now()}`, status: 'publish',
|
||||
content: `${blockContent}\n[asciiplayer preload="true"]${bad}[/asciiplayer]\n[asciiplayer preload="true"]${good}[/asciiplayer]`,
|
||||
} });
|
||||
}, { name: blockName, good: valid, bad: missing });
|
||||
// A logged-in user's language must not leak into public frontend JS.
|
||||
await verifyFrontend(page, saved.link, siteLocale);
|
||||
const anonymous = await browser.newContext();
|
||||
try {
|
||||
const visitor = await anonymous.newPage();
|
||||
visitor.on('pageerror', (error) => pageErrors.push(error.message));
|
||||
await verifyFrontend(visitor, saved.link, siteLocale);
|
||||
const frontendShot = testInfo.outputPath(`frontend-${siteLocale}-${userLocale}.png`);
|
||||
await visitor.screenshot({ path: frontendShot, fullPage: true });
|
||||
await testInfo.attach('frontend-locale', { path: frontendShot, contentType: 'image/png' });
|
||||
} finally {
|
||||
await anonymous.close();
|
||||
}
|
||||
expect(pageErrors).toEqual([]);
|
||||
});
|
||||
}
|
||||
|
||||
test('a user with the site default language inherits zh_CN in the editor', async ({ page, localeSession }) => {
|
||||
expect(await localeSession.setLocales('zh_CN', '')).toEqual({ site: 'zh_CN', user: 'zh_CN' });
|
||||
await openEditor(page);
|
||||
expect(await page.evaluate((name) => window.wp.blocks.getBlockType(name).title, blockName)).toBe(copy.zh_CN.title);
|
||||
const block = await insertPlayer(page);
|
||||
await expect(block.getByRole('textbox', { name: copy.zh_CN.source, exact: true })).toBeVisible();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,548 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixturePath = '/wp-content/uploads/asciiplayer-fixtures/hello.cast';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
}
|
||||
|
||||
async function openInspectorPanel(page, name, control) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
if (!await control.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: new RegExp(`^${name}$`) }).click();
|
||||
}
|
||||
await expect(control).toBeVisible();
|
||||
}
|
||||
|
||||
async function publish(page, title) {
|
||||
return page.evaluate(async (postTitle) => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: postTitle, status: 'publish' });
|
||||
await editor.savePost();
|
||||
const state = window.wp.data.select('core/editor');
|
||||
if (state.didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
return { id: state.getCurrentPostId(), url: state.getPermalink() };
|
||||
}, title);
|
||||
}
|
||||
|
||||
async function grid(container) {
|
||||
// These are the live VT dimensions rendered by bundled asciinema-player,
|
||||
// not the WordPress attributes or an inferred CSS aspect ratio.
|
||||
return container.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}));
|
||||
}
|
||||
|
||||
async function expectGrid(container, cols, rows) {
|
||||
await expect(container.locator('.ap-term')).toBeVisible();
|
||||
await expect.poll(() => grid(container)).toEqual({ cols, rows });
|
||||
await expect(container.locator('.ap-term-text > .ap-line')).toHaveCount(rows);
|
||||
}
|
||||
|
||||
async function figureMetrics(figure) {
|
||||
return figure.evaluate((element) => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
const parent = element.parentElement;
|
||||
const outer = parent.getBoundingClientRect();
|
||||
const style = getComputedStyle(parent);
|
||||
const left = outer.left + parseFloat(style.borderLeftWidth) + parseFloat(style.paddingLeft);
|
||||
const right = outer.right - parseFloat(style.borderRightWidth) - parseFloat(style.paddingRight);
|
||||
return {
|
||||
width: rect.width,
|
||||
available: right - left,
|
||||
leftGap: rect.left - left,
|
||||
rightGap: right - rect.right,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function expectAlignment(figure, alignment, fraction = 0.5) {
|
||||
await expect.poll(async () => {
|
||||
const dimensions = await figureMetrics(figure);
|
||||
return Math.abs(dimensions.width - dimensions.available * fraction);
|
||||
}).toBeLessThan(3);
|
||||
await expect.poll(async () => {
|
||||
const { leftGap, rightGap } = await figureMetrics(figure);
|
||||
return alignment === 'center' ? Math.abs(leftGap - rightGap) : Math.abs(alignment === 'left' ? leftGap : rightGap);
|
||||
}).toBeLessThan(3);
|
||||
}
|
||||
|
||||
async function screenshot(page, testInfo, name) {
|
||||
const path = testInfo.outputPath(`${name}.png`);
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach(name, { path, contentType: 'image/png' });
|
||||
}
|
||||
|
||||
test('display width, alignment and caption survive editor save/reload without changing the recording grid', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source, controls: 'always' });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const figure = block.locator('.asciiplayer-figure');
|
||||
const width = page.getByRole('combobox', { name: 'Player width', exact: true });
|
||||
await openInspectorPanel(page, 'Display', width);
|
||||
// Keep a marker on the actual terminal: display-only changes must neither
|
||||
// reconstruct it nor alter rows/columns, so playback position is preserved.
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.layoutIdentity = 'unchanged'; });
|
||||
await width.selectOption('50%');
|
||||
const alignment = page.getByRole('combobox', { name: 'Display alignment', exact: true });
|
||||
for (const value of ['left', 'center', 'right']) {
|
||||
await alignment.selectOption(value);
|
||||
await expectAlignment(figure, value);
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-layout-identity', 'unchanged');
|
||||
}
|
||||
await width.selectOption('custom');
|
||||
const customWidth = page.getByRole('textbox', { name: 'Custom width', exact: true });
|
||||
await customWidth.fill('240px');
|
||||
await customWidth.press('Tab');
|
||||
await expect.poll(async () => Math.abs((await figure.boundingBox()).width - 240)).toBeLessThan(2);
|
||||
await customWidth.fill('calc(100% - 20px)');
|
||||
await customWidth.press('Tab');
|
||||
await expect(customWidth).toHaveAttribute('aria-invalid', 'true');
|
||||
expect((await attributes(page, id)).width).toBe('240px');
|
||||
await width.selectOption('50%');
|
||||
const caption = figure.locator('figcaption[contenteditable="true"]');
|
||||
await caption.fill('Example terminal session');
|
||||
await caption.press('Tab');
|
||||
await expect.poll(async () => (await attributes(page, id)).caption).toContain('Example terminal session');
|
||||
const saved = await publish(page, 'Player display layout regression');
|
||||
await screenshot(page, testInfo, 'layout-editor-desktop');
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((block) => block.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => window.wp.data.select('core/block-editor').getBlocks().find((block) => block.name === name), blockName);
|
||||
expect(reloaded.attributes).toMatchObject({ source, width: '50%', displayAlign: 'right', caption: 'Example terminal session' });
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
const reloadedBlock = page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${reloaded.clientId}"]`);
|
||||
await readyPreview(reloadedBlock);
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
await expectAlignment(reloadedBlock.locator('.asciiplayer-figure'), 'right');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(reloadedBlock, 64, 12);
|
||||
const editorCanvasWidth = await page.locator('iframe[name="editor-canvas"]').evaluate((element) => element.clientWidth);
|
||||
await expect.poll(async () => (await reloadedBlock.locator('.ap-wrapper').boundingBox()).width).toBeLessThanOrEqual(editorCanvasWidth);
|
||||
await screenshot(page, testInfo, 'layout-editor-mobile');
|
||||
await page.setViewportSize({ width: 1280, height: 720 });
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
const frontendFigure = page.locator('.asciiplayer-figure');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expect(frontendFigure.locator('figcaption')).toHaveText('Example terminal session');
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
expect(options).not.toHaveProperty('width');
|
||||
expect(options).not.toHaveProperty('caption');
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await expectGrid(frontend, 64, 12);
|
||||
await expectAlignment(frontendFigure, 'right');
|
||||
const bounds = await frontendFigure.boundingBox();
|
||||
expect(bounds.x).toBeGreaterThanOrEqual(0);
|
||||
expect(bounds.x + bounds.width).toBeLessThanOrEqual(391);
|
||||
await screenshot(page, testInfo, 'layout-frontend-mobile');
|
||||
});
|
||||
|
||||
test('toolbar terminal dimensions are discoverable, preserve focus and synchronize with the collapsed sidebar', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await readyPreview(block);
|
||||
await expect(block.getByRole('spinbutton', { name: 'Columns', exact: true })).toHaveCount(0);
|
||||
await expect(block.getByRole('spinbutton', { name: 'Rows', exact: true })).toHaveCount(0);
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').closeGeneralSidebar());
|
||||
// Core hides contextual tools while typing; mirror its own test utility.
|
||||
await page.mouse.move(50, 50);
|
||||
await page.mouse.move(75, 75);
|
||||
await page.mouse.move(100, 100);
|
||||
const toolbar = page.getByRole('toolbar', { name: 'Block tools', exact: true });
|
||||
const toggle = toolbar.getByRole('button', { name: 'Terminal size', exact: true });
|
||||
await expect(toggle).toBeVisible();
|
||||
await block.scrollIntoViewIfNeeded();
|
||||
await page.waitForTimeout(300); // Let the sidebar-close layout transition settle.
|
||||
const before = await block.boundingBox();
|
||||
await toggle.click();
|
||||
const popover = page.getByRole('dialog', { name: 'Terminal size', exact: true });
|
||||
const columns = popover.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = popover.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await expect(popover).toBeVisible();
|
||||
await expect(columns).toBeVisible();
|
||||
await expect(rows).toBeVisible();
|
||||
await expect(columns).toBeFocused();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const after = await block.boundingBox();
|
||||
expect(Math.abs(after.width - before.width)).toBeLessThan(2);
|
||||
expect(Math.abs(after.height - before.height)).toBeLessThan(2);
|
||||
await screenshot(page, testInfo, 'terminal-size-toolbar-popover');
|
||||
// Invalid overrides are cleared rather than changing the recording grid.
|
||||
await columns.fill('0');
|
||||
await columns.press('Tab');
|
||||
await rows.fill('1001');
|
||||
await rows.press('Tab');
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await expectGrid(block, 64, 12);
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await rows.fill('16');
|
||||
await rows.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await rows.press('Escape');
|
||||
await expect(popover).toBeHidden();
|
||||
await expect(toggle).toBeFocused();
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('88');
|
||||
await expect(rows).toHaveValue('16');
|
||||
// A manual override must not become the displayed recording metadata.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await columns.fill('');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 64, 16);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
await columns.fill('88');
|
||||
await columns.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await popover.getByRole('button', { name: 'Use recording size', exact: true }).click();
|
||||
await expectGrid(block, 64, 12);
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await columns.fill('88');
|
||||
await rows.fill('16');
|
||||
await rows.press('Tab');
|
||||
await expectGrid(block, 88, 16);
|
||||
await popover.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
await expect(popover).toBeHidden();
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const panelToggle = page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ });
|
||||
await expect(panelToggle).toHaveAttribute('aria-expanded', 'false');
|
||||
await panelToggle.click();
|
||||
const sidebarColumns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const sidebarRows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await expect(sidebarColumns).toHaveValue('88');
|
||||
await expect(sidebarRows).toHaveValue('16');
|
||||
await expect(sidebarColumns).toHaveAttribute('placeholder', '64');
|
||||
await expect(sidebarRows).toHaveAttribute('placeholder', '12');
|
||||
await sidebarRows.fill('');
|
||||
await sidebarRows.press('Tab');
|
||||
await expectGrid(block, 88, 12);
|
||||
await page.getByRole('button', { name: 'Use recording size', exact: true }).click();
|
||||
await expectGrid(block, 64, 12);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await toggle.click();
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(rows).toHaveValue('');
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
await popover.getByRole('button', { name: 'Close', exact: true }).click();
|
||||
const saved = await publish(page, 'Reset terminal dimensions regression');
|
||||
await page.goto(saved.url);
|
||||
const frontend = page.locator('.asciiplayer-container');
|
||||
await expectGrid(frontend, 64, 12);
|
||||
const options = JSON.parse(await frontend.getAttribute('data-ap-options'));
|
||||
expect(options).not.toHaveProperty('cols');
|
||||
expect(options).not.toHaveProperty('rows');
|
||||
});
|
||||
|
||||
test('recorded resize events remain authoritative except on explicitly overridden axes', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const source = new URL('/wp-content/uploads/asciiplayer-fixtures/resize.cast', page.url()).href;
|
||||
const cases = [
|
||||
{ overrides: {}, cols: 96, rows: 18 },
|
||||
{ overrides: { cols: 80 }, cols: 80, rows: 18 },
|
||||
{ overrides: { rows: 24 }, cols: 96, rows: 24 },
|
||||
{ overrides: { cols: 80, rows: 24 }, cols: 80, rows: 24 },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const { id, block } = await insertPlayer(page, { source, startAt: 2, ...entry.overrides });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
await openInspectorPanel(page, 'Terminal size', columns);
|
||||
// Placeholders describe the cast header, even after its resize event.
|
||||
await expect(columns).toHaveAttribute('placeholder', '64');
|
||||
await expect(rows).toHaveAttribute('placeholder', '12');
|
||||
expect((await attributes(page, id)).cols).toBe(entry.overrides.cols);
|
||||
expect((await attributes(page, id)).rows).toBe(entry.overrides.rows);
|
||||
}
|
||||
const saved = await publish(page, 'Recording resize and explicit axes regression');
|
||||
await page.goto(saved.url);
|
||||
const players = page.locator('.asciiplayer-container');
|
||||
await expect(players).toHaveCount(cases.length);
|
||||
for (const [index, entry] of cases.entries()) {
|
||||
await expectGrid(players.nth(index), entry.overrides.cols ?? 64, entry.overrides.rows ?? 12);
|
||||
await players.nth(index).locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
await expect(players.nth(index).locator('.ap-term-text')).toContainText('Resized recording grid');
|
||||
}
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, entry] of cases.entries()) await expectGrid(players.nth(index), entry.cols, entry.rows);
|
||||
});
|
||||
|
||||
test('published figures preserve all alignments, safe captions and terminal typography under theme CSS', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const caption = 'Safe caption<br>with a second line & literal text';
|
||||
for (const displayAlign of ['left', 'center', 'right']) {
|
||||
await insertPlayer(page, { source, width: '50%', displayAlign, caption });
|
||||
}
|
||||
// Raw block attributes can come from REST/imported post content, bypassing
|
||||
// RichText's editor filtering. The server must sanitize them independently.
|
||||
await insertPlayer(page, {
|
||||
source,
|
||||
caption: '<script>window.__captionXss = true</script><img src="x" onerror="window.__captionXss = true"><a href="javascript:window.__captionXss=true">unsafe link</a><strong>Still safe</strong>',
|
||||
});
|
||||
const saved = await publish(page, 'Frontend figure and caption sanitization regression');
|
||||
await page.addInitScript((content) => {
|
||||
const install = () => {
|
||||
if (!document.documentElement) return false;
|
||||
const stylesheet = document.createElement('style');
|
||||
stylesheet.textContent = content;
|
||||
document.documentElement.appendChild(stylesheet);
|
||||
return true;
|
||||
};
|
||||
if (!install()) {
|
||||
const observer = new MutationObserver(() => { if (install()) observer.disconnect(); });
|
||||
observer.observe(document, { childList: true, subtree: true });
|
||||
}
|
||||
}, `
|
||||
body { letter-spacing: 1.5px; line-height: 2; text-align: center; }
|
||||
figure { margin: 2em 40px; }
|
||||
pre { padding: 24px !important; margin: 24px !important; font-family: serif !important; font-size: 24px !important; line-height: 2 !important; white-space: pre-wrap !important; border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
pre span { font-family: serif !important; font-size: 24px !important; line-height: 2 !important; letter-spacing: 2px !important; }
|
||||
button { border: 2px solid red !important; box-shadow: 0 0 0 3px red !important; }
|
||||
`);
|
||||
await page.goto(saved.url);
|
||||
const figures = page.locator('.asciiplayer-figure');
|
||||
const desktopFontSizes = [];
|
||||
await expect(figures).toHaveCount(4);
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
const figure = figures.nth(index);
|
||||
await expectAlignment(figure, displayAlign);
|
||||
await expectGrid(figure, 64, 12);
|
||||
await figure.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(figure.locator('.ap-term-text')).toContainText('Hello from wp-asciiplayer');
|
||||
await expect(figure.locator('figcaption')).toHaveText('Safe captionwith a second line & literal text');
|
||||
await expect(figure.locator('figcaption br')).toHaveCount(1);
|
||||
const typography = await figure.locator('.ap-term-text').evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const parent = getComputedStyle(element.parentElement);
|
||||
return {
|
||||
padding: style.padding,
|
||||
margin: style.margin,
|
||||
whiteSpace: style.whiteSpace,
|
||||
borderWidth: style.borderWidth,
|
||||
boxShadow: style.boxShadow,
|
||||
familyMatches: style.fontFamily === parent.fontFamily,
|
||||
fontSizeMatches: style.fontSize === parent.fontSize,
|
||||
textAlign: style.textAlign,
|
||||
};
|
||||
});
|
||||
expect(typography).toEqual({ padding: '0px', margin: '0px', whiteSpace: 'pre', borderWidth: '0px', boxShadow: 'none', familyMatches: true, fontSizeMatches: true, textAlign: 'left' });
|
||||
desktopFontSizes.push(await figure.locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize)));
|
||||
const rowTypography = await figure.locator('.ap-term-text .ap-line').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily };
|
||||
});
|
||||
expect(rowTypography).toEqual({ fontSizeMatches: true, familyMatches: true });
|
||||
const spanTypography = await figure.locator('.ap-term-text .ap-line span').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
const terminal = getComputedStyle(element.closest('.ap-term'));
|
||||
return { fontSizeMatches: style.fontSize === terminal.fontSize, familyMatches: style.fontFamily === terminal.fontFamily, letterSpacing: style.letterSpacing };
|
||||
});
|
||||
expect(spanTypography).toEqual({ fontSizeMatches: true, familyMatches: true, letterSpacing: 'normal' });
|
||||
const controls = await figure.locator('.ap-control-bar button.ap-button').first().evaluate((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return { borderWidth: style.borderWidth, boxShadow: style.boxShadow };
|
||||
});
|
||||
expect(controls).toEqual({ borderWidth: '0px', boxShadow: 'none' });
|
||||
}
|
||||
const unsafeCaption = figures.nth(3).locator('figcaption');
|
||||
await expect(unsafeCaption).toContainText('Still safe');
|
||||
await expect(unsafeCaption.locator('script, img, iframe, a, strong, [onerror], [onclick]')).toHaveCount(0);
|
||||
expect(await page.evaluate(() => window.__captionXss)).toBeUndefined();
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
await expect.poll(() => figures.nth(index).locator('.ap-term').evaluate((element) => parseFloat(getComputedStyle(element).fontSize))).toBeLessThan(desktopFontSizes[index]);
|
||||
const scaledTypography = await figures.nth(index).locator('.ap-term').evaluate((terminal) => {
|
||||
const expected = getComputedStyle(terminal);
|
||||
return [...terminal.querySelectorAll('.ap-term-text, .ap-line, .ap-line span')].every((element) => {
|
||||
const style = getComputedStyle(element);
|
||||
return style.fontSize === expected.fontSize && style.fontFamily === expected.fontFamily;
|
||||
});
|
||||
});
|
||||
expect(scaledTypography).toBe(true);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile');
|
||||
// Physical left/right placement must remain the same inside RTL content.
|
||||
// This covers direction inheritance at runtime; generated RTL stylesheets
|
||||
// are independently protected by the source's rtlcss ignore directive.
|
||||
await page.evaluate(() => {
|
||||
document.documentElement.dir = 'rtl';
|
||||
for (const figure of document.querySelectorAll('.asciiplayer-figure')) {
|
||||
figure.parentElement.dir = 'rtl';
|
||||
}
|
||||
});
|
||||
for (const [index, displayAlign] of ['left', 'center', 'right'].entries()) {
|
||||
await expectAlignment(figures.nth(index), displayAlign);
|
||||
await expectGrid(figures.nth(index), 64, 12);
|
||||
}
|
||||
await screenshot(page, testInfo, 'layout-theme-css-mobile-rtl');
|
||||
});
|
||||
|
||||
test('the inserter example is a local static preview and makes no recording request', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const example = await page.evaluate((name) => window.wp.blocks.getBlockType(name).example, blockName);
|
||||
expect(example).toMatchObject({ attributes: { isExample: true } });
|
||||
const recordingRequests = [];
|
||||
page.on('request', (request) => {
|
||||
if (/\.cast(?:[?#]|$)|asciinema\.org|jsdelivr\.net/.test(request.url())) recordingRequests.push(request.url());
|
||||
});
|
||||
// A saved URL must never turn an inserter example into a network preview.
|
||||
const { block } = await insertPlayer(page, { ...example.attributes, source: new URL(fixturePath, page.url()).href });
|
||||
await expect(block.locator('.asciiplayer-example')).toContainText('Hello, terminal!');
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveCount(0);
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(0);
|
||||
await page.waitForTimeout(750); // Exceed the automatic URL debounce window.
|
||||
await screenshot(page, testInfo, 'static-inserter-example');
|
||||
expect(recordingRequests).toEqual([]);
|
||||
});
|
||||
|
||||
test('outer editor blocks respect WordPress content gutters and core wide/full boundaries', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const source = new URL(fixturePath, page.url()).href;
|
||||
const cases = await page.evaluate(({ name, sourceUrl }) => {
|
||||
const { createBlock, getBlockType } = window.wp.blocks;
|
||||
const paragraph = (text) => createBlock('core/paragraph', { content: text });
|
||||
const before = paragraph('Paragraph before the player: the standard editor content boundary.');
|
||||
const player = createBlock(name, { source: sourceUrl, width: '100%' });
|
||||
const after = paragraph('Paragraph after the player: the same standard content boundary.');
|
||||
const blocks = [before, player, after];
|
||||
const entries = [{ alignment: 'default', playerId: player.clientId, referenceIds: [before.clientId, after.clientId] }];
|
||||
const supportsAlignment = (block, align) => {
|
||||
const support = getBlockType(block)?.supports?.align;
|
||||
return support === true || Array.isArray(support) && support.includes(align);
|
||||
};
|
||||
for (const align of ['wide', 'full']) {
|
||||
if (!supportsAlignment(name, align) || !supportsAlignment('core/group', align)) continue;
|
||||
// Paragraphs do not support wide/full. A core Group supplies the
|
||||
// native aligned boundary for its paragraph without custom sizing.
|
||||
const reference = createBlock('core/group', { align, layout: { type: 'default' } }, [
|
||||
paragraph(`${align} core Group paragraph: native WordPress alignment reference.`),
|
||||
]);
|
||||
const alignedPlayer = createBlock(name, { source: sourceUrl, width: '100%', align });
|
||||
blocks.push(reference, alignedPlayer);
|
||||
entries.push({ alignment: align, playerId: alignedPlayer.clientId, referenceIds: [reference.clientId] });
|
||||
}
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(blocks);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(player.clientId);
|
||||
return entries;
|
||||
}, { name: blockName, sourceUrl: source });
|
||||
const canvas = page.frameLocator('iframe[name="editor-canvas"]');
|
||||
for (const entry of cases) await readyPreview(canvas.locator(`[data-block="${entry.playerId}"]`));
|
||||
for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }]) {
|
||||
await page.setViewportSize(viewport);
|
||||
for (const entry of cases) {
|
||||
const block = canvas.locator(`[data-block="${entry.playerId}"]`);
|
||||
const measure = () => block.evaluate((element, referenceIds) => {
|
||||
const document = element.ownerDocument;
|
||||
const horizontal = (node) => {
|
||||
const box = node.getBoundingClientRect();
|
||||
return { left: box.left, right: box.right, width: box.width };
|
||||
};
|
||||
const outer = horizontal(element);
|
||||
const references = referenceIds.map((id) => horizontal(document.querySelector(`[data-block="${id}"]`)));
|
||||
const root = element.closest('.is-root-container');
|
||||
if (!root) throw new Error('WordPress editor content root was not found.');
|
||||
const rootBounds = horizontal(root);
|
||||
const rootStyle = getComputedStyle(root);
|
||||
const contentLeft = rootBounds.left + parseFloat(rootStyle.borderLeftWidth) + parseFloat(rootStyle.paddingLeft);
|
||||
const contentRight = rootBounds.right - parseFloat(rootStyle.borderRightWidth) - parseFloat(rootStyle.paddingRight);
|
||||
return {
|
||||
outer, references, contentLeft, contentRight,
|
||||
viewportWidth: document.documentElement.clientWidth,
|
||||
leftError: Math.max(...references.map((reference) => Math.abs(outer.left - reference.left))),
|
||||
rightError: Math.max(...references.map((reference) => Math.abs(outer.right - reference.right))),
|
||||
player: horizontal(element.querySelector('.ap-wrapper')),
|
||||
boxSizing: getComputedStyle(element).boxSizing,
|
||||
};
|
||||
}, entry.referenceIds);
|
||||
// Compare the OUTER border box to independently rendered native
|
||||
// blocks. Inner-figure/parent checks alone miss a 34px padding leak.
|
||||
await expect.poll(async () => (await measure()).leftError).toBeLessThan(2);
|
||||
await expect.poll(async () => (await measure()).rightError).toBeLessThan(2);
|
||||
const geometry = await measure();
|
||||
expect(geometry.boxSizing).toBe('border-box');
|
||||
expect(geometry.outer.left).toBeGreaterThanOrEqual(-2);
|
||||
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.viewportWidth + 2);
|
||||
if (entry.alignment === 'default') {
|
||||
expect(geometry.outer.left).toBeGreaterThanOrEqual(geometry.contentLeft - 2);
|
||||
expect(geometry.outer.right).toBeLessThanOrEqual(geometry.contentRight + 2);
|
||||
expect(geometry.outer.left).toBeGreaterThan(0);
|
||||
expect(geometry.outer.right).toBeLessThan(geometry.viewportWidth);
|
||||
}
|
||||
expect(geometry.player.left).toBeGreaterThanOrEqual(geometry.outer.left);
|
||||
expect(geometry.player.right).toBeLessThanOrEqual(geometry.outer.right + 1);
|
||||
await expectGrid(block, 64, 12);
|
||||
await testInfo.attach(`editor-gutters-${entry.alignment}-${viewport.width}`, {
|
||||
body: Buffer.from(JSON.stringify(geometry, null, 2)), contentType: 'application/json',
|
||||
});
|
||||
}
|
||||
await canvas.locator(`[data-block="${cases[0].playerId}"]`).scrollIntoViewIfNeeded();
|
||||
await screenshot(page, testInfo, `editor-content-gutters-${viewport.width}`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,290 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixtures = '/wp-content/uploads/asciiplayer-fixtures';
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
function playerBlock(page, id) {
|
||||
return page.frameLocator('iframe[name="editor-canvas"]').locator(`[data-block="${id}"]`);
|
||||
}
|
||||
|
||||
async function insertPlayer(page, attributes = {}) {
|
||||
const id = await page.evaluate(({ name, attrs }) => {
|
||||
const block = window.wp.blocks.createBlock(name, attrs);
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, attrs: attributes });
|
||||
return { id, block: playerBlock(page, id) };
|
||||
}
|
||||
|
||||
async function attributes(page, id) {
|
||||
return page.evaluate((clientId) => window.wp.data.select('core/block-editor').getBlockAttributes(clientId), id);
|
||||
}
|
||||
|
||||
async function readyPreview(block) {
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(block.locator('.ap-term')).toBeVisible();
|
||||
}
|
||||
|
||||
async function expectGrid(block, cols, rows) {
|
||||
await expect.poll(() => block.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}))).toEqual({ cols, rows });
|
||||
}
|
||||
|
||||
async function openDimensions(page) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const rows = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toBeVisible();
|
||||
return { columns, rows };
|
||||
}
|
||||
|
||||
async function expectNativeSize(controls, cols, rows) {
|
||||
await expect(controls.columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
|
||||
await expect(controls.rows).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
|
||||
}
|
||||
|
||||
async function openMedia(page, block) {
|
||||
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
async function uploadRecording(page, dialog, name, buffer) {
|
||||
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
|
||||
// Native WP media uses Plupload. Its file input is intentionally hidden and
|
||||
// may live outside the modal; setInputFiles exercises the actual uploader.
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({ name, mimeType: 'application/x-asciicast', buffer });
|
||||
return (await response).json();
|
||||
}
|
||||
|
||||
async function selectAttachment(dialog, id) {
|
||||
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
|
||||
const attachment = dialog.locator(`.attachment[data-id="${id}"]`);
|
||||
await expect(attachment).toBeVisible();
|
||||
// Newly uploaded files are already selected; clicking them again deselects.
|
||||
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
|
||||
const confirm = dialog.locator('.media-button-select');
|
||||
await expect(confirm).toBeEnabled();
|
||||
await confirm.click();
|
||||
await expect(dialog).toBeHidden();
|
||||
}
|
||||
|
||||
test('recording metadata follows URL changes, clears while loading or invalid, and never replaces explicit dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
const original = new URL(`${fixtures}/hello.cast`, page.url()).href;
|
||||
const replacement = new URL(`${fixtures}/replacement.cast?metadata=delayed`, page.url()).href;
|
||||
const unavailable = new URL(`${fixtures}/missing.cast?metadata=error`, page.url()).href;
|
||||
const malformed = new URL(`${fixtures}/malformed.cast?metadata=valid-header`, page.url()).href;
|
||||
const recording = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
let release;
|
||||
let requested = false;
|
||||
const pending = new Promise((resolve) => { release = resolve; });
|
||||
await page.route(replacement, async (route) => {
|
||||
requested = true;
|
||||
await pending;
|
||||
await route.fulfill({ contentType: 'text/plain', body: recording }).catch(() => {});
|
||||
});
|
||||
await page.route(unavailable, (route) => route.fulfill({ status: 503, contentType: 'text/plain', body: 'Unavailable' }));
|
||||
await page.route(malformed, (route) => route.fulfill({
|
||||
contentType: 'text/plain', body: '{"version":2,"width":101,"height":31}\n[invalid event]\n',
|
||||
}));
|
||||
try {
|
||||
const { id, block } = await insertPlayer(page, { source: original });
|
||||
await readyPreview(block);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await dimensions.columns.fill('80');
|
||||
await dimensions.rows.fill('20');
|
||||
await dimensions.rows.press('Tab');
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 80, 20);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await input.fill(replacement);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect.poll(() => requested).toBe(true);
|
||||
await expectNativeSize(dimensions);
|
||||
await expect(dimensions.columns).toHaveValue('80');
|
||||
await expect(dimensions.rows).toHaveValue('20');
|
||||
release();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await expectGrid(block, 80, 20);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
|
||||
await input.fill('javascript:alert(1)');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
await expectNativeSize(dimensions);
|
||||
// Invalid drafts do not overwrite the last valid saved URL or overrides.
|
||||
expect(await attributes(page, id)).toMatchObject({ source: replacement, cols: 80, rows: 20 });
|
||||
await input.fill(original);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await readyPreview(block);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
for (const failingSource of [unavailable, malformed]) {
|
||||
await input.fill(failingSource);
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
// Even a readable header must be discarded if the player fails.
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: failingSource, cols: 80, rows: 20 });
|
||||
}
|
||||
await input.fill('');
|
||||
await expect.poll(async () => (await attributes(page, id)).source).toBe('');
|
||||
await expectNativeSize(dimensions);
|
||||
expect(await attributes(page, id)).toMatchObject({ cols: 80, rows: 20 });
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
});
|
||||
|
||||
test('pretty v1 and commented v3 recordings play with native header dimensions', async ({ page }) => {
|
||||
await openEditor(page);
|
||||
// Fixtures follow the official formats, including v1's multiline JSON and
|
||||
// v3's comments after its single-line header and relative event timestamps:
|
||||
// https://docs.asciinema.org/manual/asciicast/v1/
|
||||
// https://docs.asciinema.org/manual/asciicast/v3/
|
||||
const cases = [
|
||||
{ filename: 'v1-pretty.cast', cols: 72, rows: 18, output: 'Pretty v1 recording' },
|
||||
{ filename: 'v3-comments.cast', cols: 92, rows: 22, output: 'Commented v3 recording' },
|
||||
];
|
||||
for (const entry of cases) {
|
||||
const source = new URL(`${fixtures}/${entry.filename}`, page.url()).href;
|
||||
const { id, block } = await insertPlayer(page, { source });
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, entry.cols, entry.rows);
|
||||
const dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, entry.cols, entry.rows);
|
||||
await expect(dimensions.columns).toHaveValue('');
|
||||
await expect(dimensions.rows).toHaveValue('');
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText(entry.output);
|
||||
}
|
||||
});
|
||||
|
||||
test('native Media Library uploads, selects and replaces a cast while cancel leaves the current recording intact', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const firstCast = await readFile(new URL('../fixtures/hello.cast', import.meta.url));
|
||||
const secondCast = await readFile(new URL('../fixtures/replacement.cast', import.meta.url));
|
||||
const unique = `${Date.now()}-${testInfo.retry}`;
|
||||
let dialog = await openMedia(page, block);
|
||||
const first = await uploadRecording(page, dialog, `asciiplayer-original-${unique}.cast`, firstCast);
|
||||
expect(first.success, JSON.stringify(first)).toBe(true);
|
||||
expect(first.data.mime).toBe('application/x-asciicast');
|
||||
await selectAttachment(dialog, first.data.id);
|
||||
const input = block.getByRole('textbox', { name: 'Recording URL', exact: true });
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
// Selecting in the native media frame applies and autoloads, with no Apply URL click.
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 64, 12);
|
||||
let dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
expect(await attributes(page, id)).toMatchObject({ source: first.data.url });
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
await block.locator('.ap-term').evaluate((element) => { element.dataset.mediaIdentity = 'original'; });
|
||||
|
||||
dialog = await openMedia(page, block);
|
||||
const second = await uploadRecording(page, dialog, `asciiplayer-replacement-${unique}.cast`, secondCast);
|
||||
expect(second.success, JSON.stringify(second)).toBe(true);
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(input).toHaveValue(first.data.url);
|
||||
expect((await attributes(page, id)).source).toBe(first.data.url);
|
||||
await expectNativeSize(dimensions, 64, 12);
|
||||
await expect(block.locator('.ap-term')).toHaveAttribute('data-media-identity', 'original');
|
||||
|
||||
// The upload above is now an existing media item. Reopen the real frame and
|
||||
// select its tile rather than changing block attributes through the store.
|
||||
dialog = await openMedia(page, block);
|
||||
await selectAttachment(dialog, second.data.id);
|
||||
await expect(input).toHaveValue(second.data.url);
|
||||
await readyPreview(block);
|
||||
await expectGrid(block, 100, 30);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
await block.locator('.ap-overlay-start .ap-play-button').click();
|
||||
await expect(block.locator('.ap-term-text')).toContainText('Replacement recording');
|
||||
expect((await attributes(page, id)).source).toBe(second.data.url);
|
||||
expect((await attributes(page, id)).cols).toBeUndefined();
|
||||
expect((await attributes(page, id)).rows).toBeUndefined();
|
||||
const path = testInfo.outputPath('media-library-selected-recording.png');
|
||||
await page.screenshot({ path, fullPage: true });
|
||||
await testInfo.attach('media-library-selected-recording', { path, contentType: 'image/png' });
|
||||
await page.evaluate(async () => {
|
||||
const editor = window.wp.data.dispatch('core/editor');
|
||||
editor.editPost({ title: 'Native media recording selection regression' });
|
||||
await editor.savePost();
|
||||
if (window.wp.data.select('core/editor').didPostSaveRequestFail()) throw new Error('WordPress could not save the test post.');
|
||||
});
|
||||
await page.reload();
|
||||
await page.waitForFunction((name) => window.wp?.data?.select('core/block-editor')?.getBlocks().some((entry) => entry.name === name), blockName);
|
||||
const reloaded = await page.evaluate((name) => {
|
||||
const block = window.wp.data.select('core/block-editor').getBlocks().find((entry) => entry.name === name);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block;
|
||||
}, blockName);
|
||||
expect(reloaded.attributes.source).toBe(second.data.url);
|
||||
expect(reloaded.attributes.cols).toBeUndefined();
|
||||
expect(reloaded.attributes.rows).toBeUndefined();
|
||||
await readyPreview(playerBlock(page, reloaded.clientId));
|
||||
dimensions = await openDimensions(page);
|
||||
await expectNativeSize(dimensions, 100, 30);
|
||||
});
|
||||
|
||||
test('native Media Library rejects an invalid cast upload without applying a source', async ({ page }, testInfo) => {
|
||||
await openEditor(page);
|
||||
const { id, block } = await insertPlayer(page);
|
||||
const dialog = await openMedia(page, block);
|
||||
const malformed = await readFile(new URL('../fixtures/malformed.cast', import.meta.url));
|
||||
const result = await uploadRecording(page, dialog, `asciiplayer-invalid-${Date.now()}-${testInfo.retry}.cast`, malformed);
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).';
|
||||
// A filesystem/permission failure is not evidence of content validation.
|
||||
expect(result.data.message).toBe(validationMessage);
|
||||
await expect(dialog).toContainText(validationMessage);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
expect((await attributes(page, id)).source).toBe('');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { getSecurityCase, securityFixtureBuffer } from '../fixtures/security/generate.mjs';
|
||||
|
||||
const blockName = 'lamgc/asciiplayer';
|
||||
const fixtureRoot = '/wp-content/uploads/asciiplayer-fixtures/security';
|
||||
const messages = {
|
||||
time: 'This recording contains an invalid or unsupported timestamp.',
|
||||
markers: 'This recording contains too many markers.',
|
||||
dimensions: 'This recording requests terminal dimensions that exceed the supported limits.',
|
||||
cells: 'This recording requests too many terminal cells.',
|
||||
};
|
||||
|
||||
async function openEditor(page) {
|
||||
await page.goto('/wp-login.php');
|
||||
await page.locator('#user_login').fill(process.env.WP_USERNAME || 'admin');
|
||||
await page.locator('#user_pass').fill(process.env.WP_PASSWORD || 'password');
|
||||
await page.locator('#wp-submit').click();
|
||||
await expect(page).toHaveURL(/\/wp-admin\//);
|
||||
await page.goto('/wp-admin/post-new.php');
|
||||
await page.waitForFunction((name) => Boolean(
|
||||
window.wp?.apiFetch && window.wp?.blocks?.getBlockType(name) &&
|
||||
window.wp?.data?.select('core/editor')?.getCurrentPostId()
|
||||
), blockName);
|
||||
await page.evaluate(() => {
|
||||
for (const scope of ['core/edit-post', 'core/editor']) {
|
||||
window.wp.data.dispatch('core/preferences').set(scope, 'welcomeGuide', false);
|
||||
}
|
||||
});
|
||||
await expect(page.locator('iframe[name="editor-canvas"]')).toBeVisible();
|
||||
}
|
||||
|
||||
const canvas = (page) => page.frameLocator('iframe[name="editor-canvas"]');
|
||||
|
||||
async function insertPlayer(page, source) {
|
||||
const id = await page.evaluate(({ name, source }) => {
|
||||
const block = window.wp.blocks.createBlock(name, { source, controls: 'always' });
|
||||
window.wp.data.dispatch('core/block-editor').insertBlocks(block);
|
||||
window.wp.data.dispatch('core/block-editor').selectBlock(block.clientId);
|
||||
return block.clientId;
|
||||
}, { name: blockName, source });
|
||||
return { id, block: canvas(page).locator(`[data-block="${id}"]`) };
|
||||
}
|
||||
|
||||
async function routeFixture(context, page, id) {
|
||||
const fixture = getSecurityCase(id);
|
||||
// Full 32 MiB and 100,000-event boundaries belong in Node/PHP, not a browser.
|
||||
expect(fixture.bytes).toBeLessThan(128 * 1024);
|
||||
const source = new URL(`${fixtureRoot}/${id}.cast`, page.url()).href;
|
||||
const body = securityFixtureBuffer(id);
|
||||
let requests = 0;
|
||||
await context.route(source, async (route) => {
|
||||
requests += 1;
|
||||
await route.fulfill({ contentType: 'text/plain; charset=utf-8', body });
|
||||
});
|
||||
return { source, fixture, requests: () => requests };
|
||||
}
|
||||
|
||||
/** Observe real fetch signals and allocation-facing DOM; do not mock the player. */
|
||||
function observeSecurityState() {
|
||||
if (window.__securityFixtureState) return;
|
||||
const state = window.__securityFixtureState = {
|
||||
fetches: [], maxTerms: 0, maxCols: 0, maxRows: 0, maxCells: 0,
|
||||
maxLines: 0, maxSymbolLines: 0, maxMarkers: 0,
|
||||
};
|
||||
const fetch = window.fetch;
|
||||
window.fetch = function (source, options) {
|
||||
if (String(source).includes('/asciiplayer-fixtures/security/')) {
|
||||
const entry = { source: String(source), aborted: Boolean(options?.signal?.aborted) };
|
||||
state.fetches.push(entry);
|
||||
options?.signal?.addEventListener('abort', () => { entry.aborted = true; }, { once: true });
|
||||
}
|
||||
return fetch.call(this, source, options);
|
||||
};
|
||||
const sample = () => {
|
||||
const terminals = document.querySelectorAll('.ap-term');
|
||||
state.maxTerms = Math.max(state.maxTerms, terminals.length);
|
||||
state.maxMarkers = Math.max(state.maxMarkers, document.querySelectorAll('.ap-marker').length);
|
||||
for (const terminal of terminals) {
|
||||
const cols = Number(terminal.style.getPropertyValue('--term-cols'));
|
||||
const rows = Number(terminal.style.getPropertyValue('--term-rows'));
|
||||
state.maxCols = Math.max(state.maxCols, cols);
|
||||
state.maxRows = Math.max(state.maxRows, rows);
|
||||
state.maxCells = Math.max(state.maxCells, cols * rows);
|
||||
state.maxLines = Math.max(state.maxLines, terminal.querySelectorAll('.ap-line').length);
|
||||
state.maxSymbolLines = Math.max(state.maxSymbolLines, terminal.querySelectorAll('.ap-symbol-line').length);
|
||||
}
|
||||
};
|
||||
state.sample = sample;
|
||||
new MutationObserver(sample).observe(document, {
|
||||
childList: true, subtree: true, attributes: true, attributeFilter: ['style'],
|
||||
});
|
||||
sample();
|
||||
}
|
||||
|
||||
async function observedState(scope) {
|
||||
return scope.locator('body').evaluate((body) => {
|
||||
const state = body.ownerDocument.defaultView.__securityFixtureState;
|
||||
state.sample();
|
||||
return { ...state, sample: undefined };
|
||||
});
|
||||
}
|
||||
|
||||
async function expectFetch(scope, source, aborted) {
|
||||
await expect.poll(async () => (await observedState(scope)).fetches.filter((entry) => entry.source === source))
|
||||
.toEqual([{ source, aborted }]);
|
||||
}
|
||||
|
||||
async function expectNativeSize(page, cols, rows) {
|
||||
await page.evaluate(() => window.wp.data.dispatch('core/edit-post').openGeneralSidebar('edit-post/block'));
|
||||
const columns = page.getByRole('spinbutton', { name: 'Columns', exact: true });
|
||||
const height = page.getByRole('spinbutton', { name: 'Rows', exact: true });
|
||||
if (!await columns.isVisible()) {
|
||||
await page.locator('.components-panel__body-toggle').filter({ hasText: /^Terminal size$/ }).click();
|
||||
}
|
||||
await expect(columns).toHaveAttribute('placeholder', cols === undefined ? 'From recording' : String(cols));
|
||||
await expect(height).toHaveAttribute('placeholder', rows === undefined ? 'From recording' : String(rows));
|
||||
await expect(columns).toHaveValue('');
|
||||
await expect(height).toHaveValue('');
|
||||
}
|
||||
|
||||
async function expectPlayable(container, fixture) {
|
||||
const playback = fixture.playback;
|
||||
expect(fixture.safePlayback).toBe(true);
|
||||
expect(playback.seekPercent).toBe(80);
|
||||
await expect(container.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(container.locator('.ap-term')).toBeVisible();
|
||||
await expect.poll(() => container.locator('.ap-term').evaluate((terminal) => ({
|
||||
cols: Number(terminal.style.getPropertyValue('--term-cols')),
|
||||
rows: Number(terminal.style.getPropertyValue('--term-rows')),
|
||||
}))).toEqual({ cols: playback.cols, rows: playback.rows });
|
||||
await expect(container.locator('.ap-line')).toHaveCount(playback.rows);
|
||||
await expect(container.locator('.ap-marker')).toHaveCount(0);
|
||||
await container.locator('.ap-overlay-start .ap-play-button').click();
|
||||
const terminal = container.locator('.ap-term-text');
|
||||
await expect(terminal).toContainText(playback.startText);
|
||||
const button = container.locator('.ap-playback-button');
|
||||
await expect(button).toHaveAttribute('aria-label', 'Pause');
|
||||
await button.click();
|
||||
await expect(button).toHaveAttribute('aria-label', 'Play');
|
||||
await expect(terminal).not.toContainText(playback.seekText);
|
||||
// The real UI seeks to 80% (9.6s), beyond the seeded frame at 8s, then back.
|
||||
await terminal.press(String(playback.seekPercent / 10));
|
||||
await expect(terminal).toContainText(playback.seekText);
|
||||
await terminal.press('0');
|
||||
await expect(terminal).toContainText(playback.startText);
|
||||
await expect(terminal).not.toContainText(playback.seekText);
|
||||
await expect(container.locator('.ap-wrapper')).toHaveCount(1);
|
||||
await expect(container.locator('.ap-line')).toHaveCount(playback.rows);
|
||||
}
|
||||
|
||||
async function expectNoUnsafeAllocation(scope, container) {
|
||||
await expect(container.locator('.ap-marker')).toHaveCount(0);
|
||||
// api.create legitimately creates an 80x24 shell before fetching. The
|
||||
// untrusted header/resizes must never expand it or create marker elements.
|
||||
expect(await container.locator('.ap-wrapper').count()).toBeLessThanOrEqual(1);
|
||||
await expect(container.locator('.ap-term-text')).toHaveText(/^\s*$/);
|
||||
const state = await observedState(scope);
|
||||
expect(state.maxTerms).toBeLessThanOrEqual(1);
|
||||
expect(state.maxCols).toBeLessThanOrEqual(80);
|
||||
expect(state.maxRows).toBeLessThanOrEqual(24);
|
||||
expect(state.maxCells).toBeLessThanOrEqual(80 * 24);
|
||||
expect(state.maxLines).toBeLessThanOrEqual(24);
|
||||
expect(state.maxSymbolLines).toBeLessThanOrEqual(24);
|
||||
expect(state.maxMarkers).toBe(0);
|
||||
}
|
||||
|
||||
/** Real PHP-rendered public post; retain the editor page for guaranteed cleanup. */
|
||||
async function withPublicPlayer(control, context, source, run) {
|
||||
const post = await control.evaluate(async ({ name, source }) => {
|
||||
const content = window.wp.blocks.serialize([
|
||||
window.wp.blocks.createBlock(name, { source, controls: 'always' }),
|
||||
]);
|
||||
return window.wp.apiFetch({
|
||||
path: '/wp/v2/posts', method: 'POST',
|
||||
data: { title: `Security corpus regression ${Date.now()}`, status: 'publish', content },
|
||||
});
|
||||
}, { name: blockName, source });
|
||||
const frontend = await context.newPage();
|
||||
try {
|
||||
await frontend.goto(post.link);
|
||||
const container = frontend.locator('.asciiplayer-container');
|
||||
await expect(container).toHaveCount(1);
|
||||
await run(frontend, container);
|
||||
} finally {
|
||||
await frontend.close();
|
||||
// REST's normal delete moves this isolated test post to recoverable
|
||||
// Trash. It does not force-delete data or touch pre-existing posts.
|
||||
await control.evaluate((id) => window.wp.apiFetch({
|
||||
path: `/wp/v2/posts/${id}`, method: 'DELETE',
|
||||
}), post.id);
|
||||
}
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ page, context }) => {
|
||||
await context.addInitScript(observeSecurityState);
|
||||
await openEditor(page);
|
||||
// Also cover WordPress versions that replace the iframe document in place.
|
||||
await canvas(page).locator('body').evaluate(observeSecurityState);
|
||||
});
|
||||
|
||||
for (const version of [1, 2, 3]) {
|
||||
test(`seeded v${version} corpus plays and seeks in the actual editor and public player`, async ({ page, context }) => {
|
||||
const routed = await routeFixture(context, page, `seeded-v${version}-valid`);
|
||||
const { id, block } = await insertPlayer(page, routed.source);
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expectNativeSize(page, routed.fixture.playback.cols, routed.fixture.playback.rows);
|
||||
await expectPlayable(block, routed.fixture);
|
||||
await expectFetch(canvas(page), routed.source, false);
|
||||
expect(routed.requests()).toBe(1);
|
||||
const attributes = await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id), id);
|
||||
expect(attributes.cols).toBeUndefined();
|
||||
expect(attributes.rows).toBeUndefined();
|
||||
await withPublicPlayer(page, context, routed.source, async (frontend, container) => {
|
||||
await expect(container).toHaveAttribute('data-ap-status', 'ready');
|
||||
await expectPlayable(container, routed.fixture);
|
||||
await expectFetch(frontend, routed.source, false);
|
||||
expect(routed.requests()).toBe(2);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const rejectionIds = [
|
||||
'dimensions-v1-over', 'dimensions-v2-over', 'dimensions-v3-over',
|
||||
'markers-v2-over', 'markers-v3-over',
|
||||
'late-resize-v2-over', 'late-resize-v3-over',
|
||||
'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow',
|
||||
];
|
||||
for (const id of rejectionIds) {
|
||||
test(`shared ${id} is rejected before unsafe DOM allocation on both playback paths`, async ({ page, context }) => {
|
||||
const rejected = await routeFixture(context, page, id);
|
||||
const recovery = await routeFixture(context, page, `seeded-v${rejected.fixture.format}-valid`);
|
||||
const { block } = await insertPlayer(page, rejected.source);
|
||||
const message = messages[rejected.fixture.expected.jsError];
|
||||
expect(message).toBeTruthy();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'error');
|
||||
await expect(block.locator('.components-notice')).toContainText(message);
|
||||
await expectNativeSize(page);
|
||||
await expectFetch(canvas(page), rejected.source, true);
|
||||
await expectNoUnsafeAllocation(canvas(page), block);
|
||||
expect(rejected.requests()).toBe(1);
|
||||
await withPublicPlayer(page, context, rejected.source, async (frontend, container) => {
|
||||
await expect(container).toHaveAttribute('data-ap-status', 'error');
|
||||
await expect(container.locator('.asciiplayer-error')).toHaveText(message);
|
||||
await expectFetch(frontend, rejected.source, true);
|
||||
await expectNoUnsafeAllocation(frontend, container);
|
||||
expect(rejected.requests()).toBe(2);
|
||||
});
|
||||
// A rejected corpus member must not poison the next valid recording.
|
||||
await block.getByRole('textbox', { name: 'Recording URL', exact: true }).fill(recovery.source);
|
||||
await block.getByRole('button', { name: 'Apply URL', exact: true }).click();
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expect(block.locator('.components-notice')).toHaveCount(0);
|
||||
await expectNativeSize(page, recovery.fixture.playback.cols, recovery.fixture.playback.rows);
|
||||
await expectPlayable(block, recovery.fixture);
|
||||
await expectFetch(canvas(page), recovery.source, false);
|
||||
expect(recovery.requests()).toBe(1);
|
||||
});
|
||||
}
|
||||
|
||||
async function openMedia(page, block) {
|
||||
await block.getByRole('button', { name: 'Choose recording', exact: true }).click();
|
||||
const dialog = page.getByRole('dialog', { name: 'Choose an Asciicast recording', exact: true });
|
||||
await expect(dialog).toBeVisible();
|
||||
return dialog;
|
||||
}
|
||||
|
||||
async function uploadCorpusFixture(page, dialog, id, unique) {
|
||||
const fixture = getSecurityCase(id);
|
||||
expect(fixture.bytes).toBeLessThan(32 * 1024);
|
||||
await dialog.getByRole('tab', { name: 'Upload files', exact: true }).click();
|
||||
// The real WordPress Plupload input can live outside the media modal.
|
||||
// Observe the actual upload endpoint rather than substituting its response.
|
||||
const input = page.locator('.moxie-shim input[type="file"]').last();
|
||||
await expect(input).toBeAttached();
|
||||
const response = page.waitForResponse((result) =>
|
||||
/\/wp-admin\/async-upload\.php(?:\?|$)/.test(result.url()) && result.request().method() === 'POST'
|
||||
);
|
||||
await input.setInputFiles({
|
||||
name: `security-${id}-${unique}.cast`, mimeType: 'application/x-asciicast',
|
||||
buffer: securityFixtureBuffer(id),
|
||||
});
|
||||
return (await response).json();
|
||||
}
|
||||
|
||||
test('real WordPress uploads reject shared marker/cell fixtures and accept a seeded recording', async ({ page }, testInfo) => {
|
||||
const { id, block } = await insertPlayer(page, '');
|
||||
const unique = `${Date.now()}-${testInfo.retry}`;
|
||||
const validationMessage = 'Upload a valid Asciicast v2/v3 JSONL or v1 .cast recording (up to 32 MiB; v1 up to 2 MiB, 100,000 events, 256 KiB per JSONL line, 1,000 markers, 1,000 columns or rows, 40,000 terminal cells, and bounded JSON structure).';
|
||||
for (const fixtureId of ['markers-v2-over', 'cells-v1-over', 'time-v1-ms-rounding-over', 'time-v2-output-nonprogress', 'time-v3-ms-sum-overflow']) {
|
||||
const dialog = await openMedia(page, block);
|
||||
const result = await uploadCorpusFixture(page, dialog, fixtureId, unique);
|
||||
expect(result.success, JSON.stringify(result)).toBe(false);
|
||||
// Exact plugin copy distinguishes registered resource validation from
|
||||
// MIME, filesystem, transport, or unrelated WordPress upload failures.
|
||||
expect(result.data.message).toBe(validationMessage);
|
||||
await expect(dialog).toContainText(validationMessage);
|
||||
await expect(dialog.locator('.media-button-select')).toBeDisabled();
|
||||
await dialog.locator('.media-modal-close').click();
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue('');
|
||||
expect(await page.evaluate((id) => window.wp.data.select('core/block-editor').getBlockAttributes(id).source, id)).toBe('');
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveCount(0);
|
||||
}
|
||||
const fixture = getSecurityCase('seeded-v3-valid');
|
||||
const dialog = await openMedia(page, block);
|
||||
const accepted = await uploadCorpusFixture(page, dialog, fixture.id, unique);
|
||||
expect(accepted.success, JSON.stringify(accepted)).toBe(true);
|
||||
expect(accepted.data.mime).toBe('application/x-asciicast');
|
||||
await dialog.getByRole('tab', { name: 'Media Library', exact: true }).click();
|
||||
const attachment = dialog.locator(`.attachment[data-id="${accepted.data.id}"]`);
|
||||
await expect(attachment).toBeVisible();
|
||||
if (!await attachment.evaluate((element) => element.classList.contains('selected'))) await attachment.click();
|
||||
await expect(dialog.locator('.media-button-select')).toBeEnabled();
|
||||
await dialog.locator('.media-button-select').click();
|
||||
await expect(dialog).toBeHidden();
|
||||
await expect(block.getByRole('textbox', { name: 'Recording URL', exact: true })).toHaveValue(accepted.data.url);
|
||||
await expect(block.locator('.asciiplayer-editor__preview')).toHaveAttribute('data-preview-status', 'ready');
|
||||
await expectNativeSize(page, fixture.playback.cols, fixture.playback.rows);
|
||||
// This fetches the file WordPress actually saved, without a route mock.
|
||||
await expectPlayable(block, fixture);
|
||||
});
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
{"version":2,"width":100,"height":30,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Replacement recording with a different native size"}
|
||||
[0.0,"o","$ printf 'Replacement recording'\r\n"]
|
||||
[0.1,"o","Replacement recording\r\n"]
|
||||
[12.0,"o","$ "]
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{"version":2,"width":64,"height":12,"timestamp":1700000000,"env":{"TERM":"xterm-256color","SHELL":"/bin/sh"},"title":"Recording-controlled terminal resize"}
|
||||
[0.0,"o","$ printf 'Original 64 x 12 grid'\r\n"]
|
||||
[0.1,"o","Original 64 x 12 grid\r\n"]
|
||||
[1.0,"r","96x18"]
|
||||
[1.1,"o","\u001b[2J\u001b[HResized recording grid: 96 x 18\r\n"]
|
||||
[30.0,"o","$ "]
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
# Official asciinema fixture provenance
|
||||
|
||||
These three small baselines were recorded by the official, unmodified asciinema CLI. They are genuine recordings, not hand-written files labeled as recorder output. They contain only a controlled synthetic program and are safe for public source control. None includes input capture, credentials, a user name, a host name, or an absolute workspace path.
|
||||
|
||||
## Recorder support and sources
|
||||
|
||||
- asciicast v1: official PyPI `asciinema` **1.4.0** source distribution, executed unchanged using Python **3.12.14** and its `python3 -m asciinema` entrypoint. [Published package and hash](https://pypi.org/project/asciinema/1.4.0/#files).
|
||||
- asciicast v2 and v3: official Linux x86_64 GNU release binary of asciinema **3.0.1**. [Official release](https://github.com/asciinema/asciinema/releases/tag/v3.0.1), [release asset metadata](https://api.github.com/repos/asciinema/asciinema/releases/tags/v3.0.1).
|
||||
- CLI 3.x defaults to v3 and provides `--output-format asciicast-v2`. It does not offer v1 recording output. Using the historical CLI for v1 avoids a custom conversion here. [Official 3.0 release notes](https://github.com/asciinema/asciinema/releases/tag/v3.0.0).
|
||||
|
||||
The source downloads were verified against the publisher-provided SHA-256 values before execution:
|
||||
|
||||
| Download | SHA-256 |
|
||||
| --- | --- |
|
||||
| `asciinema-x86_64-unknown-linux-gnu`, v3.0.1 | `eb3a55e8778f6b86575ad58b47f1ee21d934e4baa8f01abaa5151cad490021f8` |
|
||||
| `asciinema-1.4.0.tar.gz` | `fb31457e7a4689340b872f625658dbaea33bcf6863fb5d696cf3857010432ecb` |
|
||||
|
||||
The binaries and legacy package are not vendored in the test corpus. The official [installation guide](https://docs.asciinema.org/manual/cli/installation/) documents release binaries and the historical PyPI package.
|
||||
|
||||
## Safe, reproducible payload
|
||||
|
||||
`synthetic-output.py` writes a fixed introductory line, four harmless hexadecimal samples, and an ANSI green completion line. It reads no files or user input and uses no network. The seed is `0x41c0ffee` (1103167470), with unsigned 32-bit xorshift operations `<< 13`, `>> 17`, `<< 5`. Terminal line discipline converts its newline characters to CRLF in the captures.
|
||||
|
||||
All recorders receive an environment cleared with `env -i`, a temporary HOME and configuration directory, fixed locale/TERM/SHELL values, and an 80×24 terminal. CLI 1.4.0 requires a token field even for local recording; its isolated config contains the fixed noncredential value `fixture-no-upload`. No real credential is created, loaded or sent. Every `rec` command has an explicit local filename, and no upload, streaming or authentication command is used.
|
||||
|
||||
The recorded command is exactly `python3 synthetic-output.py`. `record-official-baselines.sh` contains the complete shell invocations and refuses to overwrite a previous capture. With the two verified tools available:
|
||||
|
||||
```sh
|
||||
ASCIINEMA3=/path/to/asciinema-3.0.1 \
|
||||
ASCIINEMA1_SRC=/path/to/asciinema-1.4.0 \
|
||||
./record-official-baselines.sh /path/to/new-captures
|
||||
```
|
||||
|
||||
The essential recorder commands are:
|
||||
|
||||
```sh
|
||||
python3 -m asciinema rec --title 'PR41 synthetic baseline' \
|
||||
--command 'python3 synthetic-output.py' official-v1.cast
|
||||
|
||||
asciinema-3.0.1 rec --headless --window-size 80x24 \
|
||||
--output-format asciicast-v2 --title 'PR41 synthetic baseline' \
|
||||
--command 'python3 synthetic-output.py' official-v2.cast
|
||||
|
||||
asciinema-3.0.1 rec --headless --window-size 80x24 \
|
||||
--output-format asciicast-v3 --title 'PR41 synthetic baseline' \
|
||||
--command 'python3 synthetic-output.py' official-v3.cast
|
||||
```
|
||||
|
||||
Use the wrapper to supply the isolation, Python module path and legacy terminal dimensions; the commands alone omit that setup.
|
||||
|
||||
## Baseline identity and validation
|
||||
|
||||
| Raw capture | SHA-256 |
|
||||
| --- | --- |
|
||||
| `official-v1.cast` | `5570c9cdec60a779585db195ecd8dee4756d84706d6b27d3ccd87cf3ba311c97` |
|
||||
| `official-v2.cast` | `6be6f5cd70d4a428692fc7807549b9c1437c1c8b60902220ad5e7e01a201f3ee` |
|
||||
| `official-v3.cast` | `8c07c04edf86605558a9795152fcba32337d72aeaa073bc89adb1c285f06763e` |
|
||||
|
||||
All three captures were successfully read using the official CLI 3.0.1 `convert --output-format raw` command. The resulting 187-byte exports are identical by `cmp` and SHA-256: `c759f03280f9a48ecfafbe7b11d7f2b75a2b418d368bc5fd5d13f1d957ee7d4d`. The official converter prepends the terminal-size escape sequence `ESC[8;24;80t`. Independently concatenating the recorded output events produces the same 177 bytes for all three formats, SHA-256 `390dbc2f2102cc0540c71c6db823622e1869596bd0b71c1d0721125083ca6550`.
|
||||
|
||||
Each has six output events. The v2 and v3 captures also contain the official recorder's trailing `x` exit event. Preserve those raw files exactly; do not silently delete metadata or events and continue calling the result an unmodified capture.
|
||||
|
||||
`provenance.json` records tool/source versions, source hashes, exact command arguments, baseline hashes, header fields, event counts and shared output hash. The repository tests exercise the raw baselines and deterministic derived fixtures against its pinned asciinema-player **3.17.0** parser/core; see the test results separately for what was executed.
|
||||
|
||||
## What is deterministic
|
||||
|
||||
The payload, seed and corpus mutation recipes are deterministic. A fresh terminal recording is **not byte-for-byte deterministic**: wall-clock timestamps, scheduling delays, total duration and PTY read boundaries can differ. The checked-in raw captures are therefore immutable, hash-pinned provenance anchors. Large and boundary fixtures are explicitly generated derivatives, with fixed timing/metadata and documented mutation recipes; they must not be described as untouched CLI output.
|
||||
|
||||
Format semantics are checked against the official specifications: [v1](https://docs.asciinema.org/manual/asciicast/v1/) uses a whole JSON document with per-output delays; [v2](https://docs.asciinema.org/manual/asciicast/v2/) uses JSON lines with elapsed timestamps; [v3](https://docs.asciinema.org/manual/asciicast/v3/) uses JSON lines with relative event intervals and nested terminal dimensions. Format conformance and genuine provenance complement, rather than replace, resource-boundary and real-player regression tests.
|
||||
Vendored
+169
@@ -0,0 +1,169 @@
|
||||
# TEST ONLY: deterministic recording-security corpus
|
||||
|
||||
This corpus exercises PR41's resource gates against ordinary, boundary and
|
||||
intentionally malformed asciicast input. It is **not** a collection to open in an
|
||||
unprotected terminal player. Do not upload generated boundary files to a real
|
||||
WordPress site, serve them publicly, or commit expanded large payloads.
|
||||
|
||||
Only small, readable `.cast` files are checked in. Large cases are compact
|
||||
literal/repeat recipes materialized one at a time in temporary storage. The
|
||||
largest possible file is **32 MiB + 1 byte**. There is no arbitrary size argument,
|
||||
unbounded fuzz loop, network request, remote command, or production-code import
|
||||
in the generator. The ordinary plugin package excludes the `tests` directory.
|
||||
|
||||
## Provenance and reproducibility
|
||||
|
||||
- `official-v1.cast`, `official-v2.cast`, and `official-v3.cast` are unmodified
|
||||
**native recordings** from pinned official CLI versions. Legacy CLI 1.4.0
|
||||
produced v1; CLI 3.0.1 produced v2 and v3. Their actual timestamps and PTY delays
|
||||
remain intact. See [PROVENANCE.md](PROVENANCE.md) and `provenance.json` for
|
||||
official source URLs, verified package hashes, commands and capture hashes.
|
||||
- `seeded-v*-valid.cast` are explicitly **normalized derivatives**, not raw CLI
|
||||
output. They retain the captured output text and the recorded format/dimension
|
||||
envelope, remove nondeterministic metadata, add seeded harmless UTF-8 output,
|
||||
and use fixed visible START/SEEK/END frames across a 12-second timeline. v2
|
||||
stores absolute time; v1/v3 store matching intervals. These are the interactive
|
||||
playback/seek controls.
|
||||
- Resource-boundary derivatives mutate one documented resource purpose. JSONL
|
||||
byte and line fillers are actual output events, not padding comments. Wide
|
||||
metadata, deep metadata and large valid grids are valid-format resource-unsafe
|
||||
cases; they must fail the intended policy rather than generic JSON syntax.
|
||||
- Blank/comment/indented lines, zero header dimensions and duplicate keys are
|
||||
marked `upstream-compatible`, independently of strict format provenance.
|
||||
- `malformed-v*` cases deliberately contain broken JSON and are labeled
|
||||
`intentionally-malformed`.
|
||||
|
||||
`recipes.mjs` uses real unsigned xorshift32 (`<<13`, `>>>17`, `<<5`) with the
|
||||
single allowed seed `0x41c0ffee` (1103167470). Randomized output chunks, text and
|
||||
bounded timings are deterministic. Equivalent purposes use all three formats
|
||||
where their semantics permit it. v1 has a whole-document 2 MiB budget and no
|
||||
marker/resize event types; those JSONL-only purposes apply to v2/v3. A fresh
|
||||
official PTY recording is not byte-identical; the checked-in raw captures are
|
||||
immutable, independently hash-pinned anchors, not regenerated during tests.
|
||||
|
||||
## Commands
|
||||
|
||||
Run from the repository root using the project's supported Node version:
|
||||
|
||||
```sh
|
||||
# List bounded, known case IDs, sizes and expected results.
|
||||
node tests/fixtures/security/generate.mjs --list
|
||||
|
||||
# Compare deterministic recipes to the golden manifest and verify every hash.
|
||||
node tests/fixtures/security/generate.mjs --verify
|
||||
|
||||
# Write exactly one known file to a new OS temporary directory.
|
||||
node tests/fixtures/security/generate.mjs --case markers-v2-over
|
||||
|
||||
# Independent corpus metrics plus actual production loader and player Core.
|
||||
node --test tests/js/security-fixtures.test.js tests/js/security-loader-fixtures.test.js
|
||||
|
||||
# All JavaScript checks, including both corpus suites.
|
||||
npm test
|
||||
|
||||
# Native PHP 7.4+; needs neither Node nor the asciinema CLI.
|
||||
php tests/php/run.php
|
||||
|
||||
# Real isolated WordPress/Chromium integration; see tests/e2e/README.md setup.
|
||||
npx --no-install playwright test tests/e2e/security-fixtures.spec.js
|
||||
```
|
||||
|
||||
The `--case` command prints the temporary path, byte count, SHA-256 and cleanup
|
||||
directory. Delete that directory after inspection. Test consumers clean up their
|
||||
own temporary files in `finally` blocks. Never replace the named case ID with a
|
||||
user-controlled arbitrary size. Large samples must stay outside source control.
|
||||
|
||||
When intentionally changing a recipe, run `--refresh` and review the complete
|
||||
manifest/hash/small-fixture diff, then rerun the checks above. This writes only
|
||||
the manifest and tiny derivative files; it never rewrites official captures or
|
||||
expands large cases into the repository. Provenance checks independently reject
|
||||
a changed raw baseline even if someone refreshes the golden manifest.
|
||||
|
||||
## Shared cross-language contract
|
||||
|
||||
`manifest.json` has `schemaVersion: 1`, an independently pinned `policy`, seed,
|
||||
and a `cases` array. Each case declares:
|
||||
|
||||
- `id`, `format`, `description`, `category`, `validity`, and `provenance`
|
||||
- Exactly one `source.file` relative to this directory, or ordered
|
||||
`source.segments: [{ "text": "literal UTF-8", "repeat": positiveInteger }]`
|
||||
- `bytes` and lowercase SHA-256 of the exact generated bytes
|
||||
- `expected.accepted` and exact `expected.jsError` (null for accepted controls)
|
||||
- Optional `boundary: {metric, limit, value}` and independent `metrics`
|
||||
- `safePlayback: true` only for the six tiny official/seeded accepted controls
|
||||
- Optional `playback` expectations for the normalized interactive controls
|
||||
|
||||
Concatenate the UTF-8 bytes of each literal repeated by its count in order. Do
|
||||
not normalize newlines, strip BOMs, reserialize JSON, execute text, or shell out
|
||||
to Node from PHP. The JavaScript reader verifies size and SHA-256 before use;
|
||||
the PHP reader streams at most 64 KiB at a time to one temporary file and checks
|
||||
the same identity before invoking the actual file/upload/sideload gates.
|
||||
|
||||
`expected.noDecodeAtOrAboveBytes` is a witness threshold for rejected JSON trees:
|
||||
the decoder must not see any tree input that large. Small safe headers or tiny
|
||||
version-discriminator scalar parses may still occur. Byte-over JSONL differs by
|
||||
consumer: PHP rejects from file size before any decode, expressed by the stronger
|
||||
`expected.phpNoDecodeAtOrAboveBytes: 1`; a browser stream must parse safe earlier
|
||||
records before discovering the final byte, then cancel without handing the
|
||||
recording to the player. This is not a claim that all streaming prefix parsing
|
||||
can or should be avoided.
|
||||
|
||||
## Coverage map
|
||||
|
||||
| Purpose | Case IDs | Boundary |
|
||||
| --- | --- | --- |
|
||||
| Official provenance and real playback | `official-v{1,2,3}`, `seeded-v{1,2,3}-valid` | Same native output; normalized equivalent timelines |
|
||||
| Zero/blank/multiline compatibility | `valid-v*-zero`, `valid-v{2,3}-filtered-lines`, `valid-v1-multiline-late-version` | Small actual files |
|
||||
| Format discrimination | `valid-v1-escaped-version`, `valid-v1-duplicate-version`, `valid-v1-long-first-line`, `invalid-v2-duplicate-version-wide` | v1 limits cannot leak into v2 |
|
||||
| Whole body bytes | `bytes-v{2,3}-{at,over}` | 33,554,432 / 33,554,433 bytes |
|
||||
| Legacy v1 bytes | `v1-bytes-{at,over}` | 2,097,152 / 2,097,153 bytes |
|
||||
| JSONL bytes including LF | `line-v{2,3}-{at,over}` | 262,144 / 262,145 bytes |
|
||||
| Events | `events-v{1,2,3}-{at,over}` | 100,000 / 100,001 events |
|
||||
| Physical JSONL work | `ignored-lines-v{2,3}-{at,over}` | 100,000 / 100,001 lines; exactly one output event |
|
||||
| Markers | `markers-v{2,3}-{at,over}` | 1,000 / 1,001 markers |
|
||||
| Header and late-resize axes | `dimensions-v*-{at,over}`, `late-resize-v{2,3}-dimensions-{at,over}` | 1,000 / 1,001 columns, otherwise safe |
|
||||
| Header and late-resize cells | `cells-v*-{at,over}`, `late-resize-v{2,3}-{at,over}` | 200×200 / 201×200; each axis remains valid |
|
||||
| v1 scalar/key allocation | `tokens-v1-{at,over}` | 400,000 / 400,001 tokens |
|
||||
| v1 container allocation | `containers-v1-{at,over}` | 100,016 / 100,017 containers |
|
||||
| JSONL scalar/key allocation | `line-tokens-v{2,3}-{at,over}` | 20,000 / 20,001 tokens |
|
||||
| Nesting | `depth-v{1,2,3}-{at,over}` | 15 / 16 container levels |
|
||||
| Recording timeline | `timeline-v{1,2,3}-{at,over}` | 2,147,483,647 / 2,147,483,648 milliseconds |
|
||||
| Relative timeline sum | `interval-timeline-v{1,3}-{at,over}` | Millisecond-order accumulation at / over the horizon |
|
||||
| Time metadata | `duration-v*-{zero,at,over}`, `idle-limit-v*-{zero,at,over}` | Zero remains valid; inclusive horizon applies |
|
||||
| Floating-point regressions | `time-v{1,3}-ms-rounding-over`, `time-v{1,3}-ms-sum-overflow`, `time-v2-output-nonprogress` | Valid JSON with unsafe upstream millisecond arithmetic |
|
||||
| Intentional bad syntax | `malformed-v1-json`, `malformed-v{2,3}-event` | Stable invalid-result controls |
|
||||
|
||||
The cells-over value is 40,200, not an assertion that every integer cell count
|
||||
has a valid integer grid. Event-only JSONL reaches the physical-line and event
|
||||
caps together; the ignored-line pair independently isolates physical-line work.
|
||||
There is no separate per-line cap on whole-document v1, and no JSONL-wide 400,000
|
||||
token budget: those distinctions are explicit rather than false all-format
|
||||
equivalence.
|
||||
|
||||
The corpus invariant suite independently parses tightly bounded test data to
|
||||
measure structure, verify valid/malformed labels, pin exact boundary values,
|
||||
and prove an unrelated limit is not masking the intended one. Only the six
|
||||
`safePlayback` controls use ordinary real pinned player Core playback. Separate
|
||||
tiny timestamp regressions use captured timers and bounded callbacks to verify
|
||||
upstream numeric behavior without scheduling long waits or an unbounded loop.
|
||||
Hostile/boundary recordings first exercise the production loader guard or PHP
|
||||
upload validator.
|
||||
|
||||
The supported raw timeline is about 24.85 days. Browser playback conservatively
|
||||
requires cumulative time divided by speed to fit the same signed timer ceiling;
|
||||
at 0.01×, this permits about 5.97 hours of source time. Per-event gap checks alone
|
||||
are insufficient because the player batches future output ahead of wall time.
|
||||
The v1/v3 rounding witness specifically distinguishes summing milliseconds from
|
||||
summing seconds before conversion; these two operations are not interchangeable.
|
||||
Browser tests use the existing isolated WordPress setup and check visible errors
|
||||
and recovery. Passing Node/PHP checks does not imply that a browser run occurred.
|
||||
|
||||
## Relationship to existing tests
|
||||
|
||||
Existing `hello.cast`, `replacement.cast`, `resize.cast`, `v1-pretty.cast`, and
|
||||
`v3-comments.cast` remain the ordinary UI regression fixtures. Existing inline
|
||||
small-limit unit tests remain useful for cancellation, option overrides, UTF-8
|
||||
failures and timing edge cases. This corpus adds durable official provenance,
|
||||
actual full-default at/over resource pairs, deterministic cross-language input,
|
||||
decoder-order witnesses and a common source for upload and playback integration;
|
||||
it does not replace those focused tests.
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":1,"width":200,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":1,"width":201,"height":200,"stdout":[[0,"PR41 bounded control\r\n"]]}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":200,"height":200}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":201,"height":200}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":200,"rows":200}}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":201,"rows":200}}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"stdout":[],"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":2,"width":80,"height":24,"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[0]]]]]]]]]]]]]]}
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"metadata":[[[[[[[[[[[[[[[0]]]]]]]]]]]]]]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":1000,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":1001,"height":24,"stdout":[[0,"PR41 bounded control\r\n"]]}
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":1000,"height":24}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":1001,"height":24}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":1000,"rows":24}}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":1001,"rows":24}}
|
||||
[0,"o","PR41 bounded control\r\n"]
|
||||
+1
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"duration":2147483.647,"stdout":[[0,"x"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"duration":2147483.648,"stdout":[[0,"x"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"duration":0,"stdout":[[0,"x"]]}
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"duration":2147483.647}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"duration":2147483.648}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"duration":0}
|
||||
[0,"o","x"]
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.647}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"duration":2147483.648}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"duration":0}
|
||||
[0,"o","x"]
|
||||
Vendored
+88
@@ -0,0 +1,88 @@
|
||||
/** TEST ONLY. Materialize one pinned fixture; never accepts arbitrary sizes. */
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createManifest, createRecipes, MAX_FIXTURE_BYTES } from './recipes.mjs';
|
||||
|
||||
const root = dirname( fileURLToPath( import.meta.url ) );
|
||||
const manifestPath = join( root, 'manifest.json' );
|
||||
const invoked = process.argv[ 1 ] && resolve( process.argv[ 1 ] ) === fileURLToPath( import.meta.url );
|
||||
|
||||
// Maintenance only: deterministic recipes write the small fixtures plus golden
|
||||
// manifest. No large expanded payload is ever written into the repository.
|
||||
if ( invoked && process.argv.slice( 2 ).join( ' ' ) === '--refresh' ) {
|
||||
const recipes = createRecipes();
|
||||
for ( const { entry, parts } of recipes ) {
|
||||
if ( ! entry.source.file ) continue;
|
||||
if ( entry.provenance === 'official-raw-capture' ) continue;
|
||||
if ( entry.bytes > 16384 ) throw new RangeError( 'Checked-in fixtures must stay small.' );
|
||||
writeFileSync( join( root, entry.source.file ), parts.map( ( part ) => part.text.repeat( part.repeat ) ).join( '' ), 'utf8' );
|
||||
}
|
||||
writeFileSync( manifestPath, JSON.stringify( createManifest(), null, 2 ) + '\n', 'utf8' );
|
||||
process.stdout.write( `Refreshed ${ recipes.length } recipes and their small controls.\n` );
|
||||
}
|
||||
|
||||
export const securityManifest = JSON.parse( readFileSync( manifestPath, 'utf8' ) );
|
||||
export const securityCases = securityManifest.cases;
|
||||
|
||||
export function getSecurityCase( id ) {
|
||||
const fixture = securityCases.find( ( item ) => item.id === id );
|
||||
if ( ! fixture ) throw new RangeError( `Unknown security fixture: ${ id }` );
|
||||
return fixture;
|
||||
}
|
||||
|
||||
export function securityFixtureBuffer( id ) {
|
||||
const fixture = getSecurityCase( id );
|
||||
if ( ! Number.isSafeInteger( fixture.bytes ) || fixture.bytes < 1 || fixture.bytes > MAX_FIXTURE_BYTES ) throw new RangeError( 'Fixture byte cap exceeded.' );
|
||||
let buffer;
|
||||
if ( fixture.source.file ) {
|
||||
if ( ! /^[a-z0-9-]+\.cast$/.test( fixture.source.file ) ) throw new Error( 'Fixture file must stay in its own directory.' );
|
||||
buffer = readFileSync( join( root, fixture.source.file ) );
|
||||
} else {
|
||||
let length = 0;
|
||||
for ( const { text, repeat } of fixture.source.segments ) {
|
||||
if ( typeof text !== 'string' || ! text.length || ! Number.isSafeInteger( repeat ) || repeat < 1 ) throw new Error( 'Invalid literal-repeat segment.' );
|
||||
length += Buffer.byteLength( text ) * repeat;
|
||||
if ( ! Number.isSafeInteger( length ) || length > MAX_FIXTURE_BYTES ) throw new RangeError( 'Recipe byte cap exceeded.' );
|
||||
}
|
||||
if ( length !== fixture.bytes ) throw new Error( `Recipe length differs for ${ id }` );
|
||||
buffer = Buffer.allocUnsafe( length );
|
||||
let offset = 0;
|
||||
for ( const { text, repeat } of fixture.source.segments ) {
|
||||
const unit = Buffer.from( text, 'utf8' );
|
||||
const end = offset + unit.length * repeat;
|
||||
buffer.fill( unit, offset, end );
|
||||
offset = end;
|
||||
}
|
||||
}
|
||||
if ( buffer.length !== fixture.bytes || createHash( 'sha256' ).update( buffer ).digest( 'hex' ) !== fixture.sha256 ) throw new Error( `Fixture integrity failure: ${ id }` );
|
||||
return buffer;
|
||||
}
|
||||
|
||||
export function writeSecurityFixture( id, directory ) {
|
||||
const buffer = securityFixtureBuffer( id );
|
||||
const path = join( directory, `${ id }.cast` );
|
||||
writeFileSync( path, buffer, { flag: 'wx' } );
|
||||
return path;
|
||||
}
|
||||
|
||||
if ( invoked ) {
|
||||
const args = process.argv.slice( 2 );
|
||||
if ( args.length === 1 && args[ 0 ] === '--list' ) {
|
||||
for ( const item of securityCases ) process.stdout.write( `${ item.id }\t${ item.bytes } bytes\t${ item.expected.accepted ? 'accept' : item.expected.jsError }\n` );
|
||||
} else if ( args.length === 1 && args[ 0 ] === '--verify' ) {
|
||||
if ( JSON.stringify( securityManifest ) !== JSON.stringify( createManifest() ) ) throw new Error( 'Golden manifest differs; inspect recipes before --refresh.' );
|
||||
for ( const item of securityCases ) securityFixtureBuffer( item.id );
|
||||
process.stdout.write( `Verified ${ securityCases.length } deterministic fixtures.\n` );
|
||||
} else if ( args.length === 2 && args[ 0 ] === '--case' ) {
|
||||
const fixture = getSecurityCase( args[ 1 ] );
|
||||
const directory = mkdtempSync( join( tmpdir(), 'asciiplayer-security-' ) );
|
||||
const path = writeSecurityFixture( fixture.id, directory );
|
||||
process.stdout.write( JSON.stringify( { path, bytes: fixture.bytes, sha256: fixture.sha256, cleanup: `Remove ${ directory } after testing.` }, null, 2 ) + '\n' );
|
||||
} else if ( args.length !== 1 || args[ 0 ] !== '--refresh' ) {
|
||||
process.stderr.write( 'Usage: node tests/fixtures/security/generate.mjs --list | --verify | --case <known-id> | --refresh\n' );
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"idle_time_limit":2147483.647,"stdout":[[0,"x"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"idle_time_limit":2147483.648,"stdout":[[0,"x"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"idle_time_limit":0,"stdout":[[0,"x"]]}
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"idle_time_limit":2147483.647}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"idle_time_limit":2147483.648}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24,"idle_time_limit":0}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.647}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":2147483.648}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24},"idle_time_limit":0}
|
||||
[0,"o","x"]
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.824,"end"]]}
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"stdout":[[1073741.823,"x"],[1073741.825,"end"]]}
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[1073741.823,"o","x"]
|
||||
[1073741.824,"o","end"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[1073741.823,"o","x"]
|
||||
[1073741.825,"o","end"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":2,"width":80,"height":24}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","200x200"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":2,"width":80,"height":24}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","1000x24"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":2,"width":80,"height":24}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","1001x24"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":2,"width":80,"height":24}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","201x200"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","200x200"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","1000x24"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","1001x24"]
|
||||
@@ -0,0 +1,3 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[0,"o","safe prefix\r\n"]
|
||||
[12,"r","201x200"]
|
||||
@@ -0,0 +1 @@
|
||||
{"version":1,"width":80,"height":24,"stdout":[}
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":2,"width":80,"height":24}
|
||||
[0,"o",broken]
|
||||
@@ -0,0 +1,2 @@
|
||||
{"version":3,"term":{"cols":80,"rows":24}}
|
||||
[0,"o",broken]
|
||||
+2925
File diff suppressed because it is too large
Load Diff
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user