diff --git a/CHANGELOG.md b/CHANGELOG.md index 5672805..cb50213 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - **`ext/web` C0**:`admin=False` 不再挂载/保留 `/admin*`;可配 `admin_prefix` / `login_redirect` / `logout_redirect`;金样 `web-c0-admin-prefix`。 - **`ext/web` C1**:门禁段边界匹配(不再误伤 `/admin-publish`);`gate` 支持 `match` / `on_deny` / `exclude`;`auth` 默认 `on_deny=redirect` + `login_path`;金样 `web-c1-gates`。 - **`ext/web` C2**:`shell_css=full|minimal|off`;`layout=sidebar|stacked|bare|rail`;full 壳含小屏单列 media;金样 `web-c2-shell-layout`。 +- **`ext/web` C3**:样式装配对数字/布尔值单元格告警,`strict`/`strict_css_cells` 硬错误;`page.css` 作 raw CSS;head 表支持 `defer`/`async`/`version`,`asset_version` 统一 `?v=`;金样 `web-c3-style-head`。 ### Changed - `build_step_context`:call site 提前到 task 之后;开场白强调 code-as-documentation。 diff --git a/doc/design/ext-web-customization/README.md b/doc/design/ext-web-customization/README.md index 4082fb2..d88a731 100644 --- a/doc/design/ext-web-customization/README.md +++ b/doc/design/ext-web-customization/README.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **C0–C2 done · C3–C4 planned** | +| 状态 | **C0–C3 done · C4 planned** | | 日期 | 2026-09-04 | | 问题盘点 | [../../research/ext-web-customization-limits.md](../../research/ext-web-customization-limits.md) | | 相关 | [../ext-web.md](../ext-web.md) · [../ext-web-net.md](../ext-web-net.md) · [../../roadmap/ext-web.md](../../roadmap/ext-web.md) | @@ -35,7 +35,7 @@ | **C0** | 可配置 `admin_prefix`;`admin=False` 时不挂内置路由;`login_redirect` / `logout_redirect` | — | | **C1** | gate:统一未登录策略;精确/前缀匹配;登录页自动放行;默认 gate 不再误伤 `/admin-*` | C0 | | **C2** | `shell_css=off\|minimal\|full`;主题在壳前或隔离层;可选 `layout=bare` | — | -| **C3** | 样式:文档 + 校验警告;可选 raw CSS 块;脚本 `defer`/`type=module` 默认 | — | +| **C3** | 样式:校验警告 / `strict`;`page.css` raw;脚本 `defer`/`async`/`version` + `asset_version` | **done** | | **C4** | 壳:`layout` 预设(sidebar / stacked / bare);条件导航钩子(后续) | C2 | 路线图入口可在 [ext-web.md](../../roadmap/ext-web.md) 增补「定制波次 C0–C4」行,落地后再改状态。 diff --git a/doc/design/web-assets-and-images.md b/doc/design/web-assets-and-images.md index 21368f0..426d806 100644 --- a/doc/design/web-assets-and-images.md +++ b/doc/design/web-assets-and-images.md @@ -121,13 +121,16 @@ url = /favicon.ico | `媒体` | `media` | CSS media | | `作为` | `as` | preload `as` | | `跨域` | `crossorigin` | 空 / `anonymous` / `use-credentials` | +| `推迟` | `defer` | 经典 `script` 为真时输出 `defer`(缺省同步,兼容旧站) | +| `异步` | `async` | 为真时输出 `async` | +| `版本` | `version` / `v` | 非空则自动追加 `?v=`;否则用页面/应用 `asset_version` | **渲染规则** | `rel` | 输出 | |-------|------| -| `script` | ``(`type` 非空则写出) | -| `module` | `` | +| `script` | ``(可选 `defer`/`async`;`type` 非空则写出) | +| `module` | ``(浏览器默认 defer 语义) | | 其他 | ``(按列附加 `type`/`sizes`/`media`/`as`/`crossorigin`) | 空 `地址` 的行跳过。 diff --git a/doc/roadmap/ext-web.md b/doc/roadmap/ext-web.md index 7a02008..b1af4de 100644 --- a/doc/roadmap/ext-web.md +++ b/doc/roadmap/ext-web.md @@ -44,7 +44,7 @@ | **C0** | `admin` 关则不占路径;`admin_prefix` / 登录回跳可配 | **done** | | **C1** | gate 匹配与未登录策略一致;段边界默认 admin gate | **done** | | **C2** | `shell_css` + `layout` 松绑 | **done** | -| **C3** | 样式 strict / 脚本 defer·version | **planned** | +| **C3** | 样式 strict / 脚本 defer·version | **done** | | **C4** | 壳预设收口与条件导航(后续) | **planned** | 验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`tests/ext/web-w7-finish-smoke.mq.md`、`tests/ext/web-p3-smoke.mq.md`、`ext_cli_add_web`。 diff --git a/ext/web/web.mq.md b/ext/web/web.mq.md index 8c35eba..9d9c664 100644 --- a/ext/web/web.mq.md +++ b/ext/web/web.mq.md @@ -21,6 +21,7 @@ Load the ABI v2 `web` plugin once. ## make_style + `name`="" + `table` + + `strict`=False Assemble a GFM style table into a CSS string. Two shapes are accepted: `|选择器|属性|值|` rule rows (arbitrary selectors; rows sharing a selector are @@ -28,11 +29,14 @@ merged, and a leading `|媒体|` column groups rows into `@media` blocks), or `|属性|值|` property rows wrapped as `.name { … }`. Selectors starting with `@keyframes name` emit keyframe blocks (`属性` = stop `from`/`to`/`N%`, `值` = `prop: val` or use `@keyframes name from` + normal 属性/值). Quote CSS -values that contain `/` (e.g. `"16/9"`, `"1/5"`); bare `1/5` is integer division. -Styles stay as data tables, `make_style` turns them into CSS — 样式即数据、装配即函数. +values that contain `/` (e.g. `"16/9"`, `"1 / 5"`); bare `1 / 5` is integer +division and becomes a numeric cell — default mode warns, `strict=True` errors. +For complex themes prefer `page.css` (raw string, no table eval) or an external +`static/*.css` via `page.head`. Styles stay as data tables, `make_style` turns +them into CSS — 样式即数据、装配即函数. > ensure_plugin -**> web_style name=`name` table=`table`** +**> web_style name=`name` table=`table` strict=`strict`** ## make_images + `table` @@ -181,9 +185,10 @@ Build a `render_list` effect: `{ render_list: { sel: { tag, items } } }`. + `intro`="" + `shell_css`=None + `layout`=None + + `asset_version`=None > ensure_plugin -**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout`** +**> web_page_new title=`title` intro=`intro` shell_css=`shell_css` layout=`layout` asset_version=`asset_version`** ## shell_css + `mode`=full @@ -201,6 +206,14 @@ Page chrome layout: `sidebar` (default when a side slot exists), `stacked` (sing *`out` = > table.put in=`self` at="layout" value=layout* **out** +## asset_version + + `version`="" + +Default `?v=` bump for head scripts/styles that omit a per-row `version` column. + +*`out` = > table.put in=`self` at="asset_version" value=version* +**out** + ## compose_components + `components` @@ -241,8 +254,9 @@ an `href`/`链接` field become ``. ## css + `css` -Append a raw CSS string to the page's stylesheet (`styles_css`). Use it to ship -a hand-written theme alongside the assembled shell. +Append a **raw** CSS string to the page's stylesheet (`styles_css`). Skips table-cell +expression evaluation — use for themes with `/`, `@keyframes`, or long media queries. +Hand-written theme alongside the assembled shell; or link `static/theme.css` via `head`. **> web_page_css page=`self` css=`css`** @@ -264,7 +278,7 @@ SEO / OpenGraph metadata as a data table (`|key|value|`). Keys such as `title`, ## head + `table` -Assemble `` resources from a GFM table (`|rel|href|type|sizes|media|as|crossorigin|` or ZH `|关系|地址|类型|…|`). `rel=script` / `module` become `", esc(&l.href))); + tag.push_str(&format!(" src=\"{}\">", esc(&href))); s.push_str(&tag); continue; } - let mut tag = format!(" (Value, Vec, Vec) media: String::new(), as_: String::new(), crossorigin: String::new(), + defer: None, + async_: false, + version: String::new(), }); } @@ -347,6 +431,9 @@ pub fn normalize_icons(table: &Value) -> (Value, Vec, Vec) media: String::new(), as_: String::new(), crossorigin: String::new(), + defer: None, + async_: false, + version: String::new(), }, ); } @@ -369,6 +456,9 @@ pub fn convention_favicon(static_dir: &Path) -> Option<(Vec, Vec")); + assert!(!h.contains(" defer"), "{h}"); + } + + #[test] + fn head_script_defer_async_version() { + let t = json!([ + {"关系": "script", "地址": "/static/a.js", "推迟": true, "版本": "3"}, + {"关系": "module", "地址": "/static/b.js", "版本": "9"}, + {"关系": "stylesheet", "地址": "/static/t.css", "版本": "1"}, + ]); + let h = make_head_html(&t); + assert!(h.contains(""), "{h}"); + assert!(h.contains("type=\"module\""), "{h}"); + assert!(h.contains("src=\"/static/b.js?v=9\""), "{h}"); + assert!(h.contains("href=\"/static/t.css?v=1\""), "{h}"); + } + + #[test] + fn head_asset_version_fallback() { + let links = as_head_links(&json!([ + {"关系": "script", "地址": "/static/a.js", "推迟": "真"}, + ])); + let h = render_head_links_with_version(&links, "2026-09-04"); + assert!( + h.contains(""), + "{h}" + ); } } diff --git a/plugins/web/src/lib.rs b/plugins/web/src/lib.rs index 0cb21ab..2cbec04 100644 --- a/plugins/web/src/lib.rs +++ b/plugins/web/src/lib.rs @@ -22,7 +22,7 @@ mod upload; mod ws; mod ws_hub; -use crate::table::as_css_named; +use crate::table::as_css_named_checked; use std::ffi::{CStr, CString}; use std::os::raw::{c_char, c_int, c_void}; @@ -283,6 +283,13 @@ web_ffi!(web_page_new, |args: &Value| { if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) { out.as_object_mut().unwrap().insert("layout".into(), json!(s)); } + if let Some(s) = arg_str_opt(args, "asset_version") + .or_else(|| arg_str_opt(args, "资源版本")) + { + out.as_object_mut() + .unwrap() + .insert("asset_version".into(), json!(s)); + } Ok(out) }); @@ -355,7 +362,21 @@ web_ffi!(web_page_css, |args: &Value| { web_ffi!(web_style, |args: &Value| { let name = arg_str_opt(args, "name").unwrap_or("").to_string(); let table = args.get("table").cloned().unwrap_or(json!([])); - Ok(Value::String(as_css_named(&name, &table))) + let strict = args + .get("strict") + .or_else(|| args.get("strict_css_cells")) + .or_else(|| args.get("严格")) + .map(|v| match v { + Value::Bool(b) => *b, + Value::Number(n) => n.as_i64().unwrap_or(0) != 0, + Value::String(s) => matches!( + s.trim(), + "1" | "true" | "True" | "yes" | "on" | "真" | "是" + ), + _ => false, + }) + .unwrap_or(false); + as_css_named_checked(&name, &table, strict).map(Value::String) }); web_ffi!(web_page_detail, |args: &Value| { @@ -1066,6 +1087,13 @@ web_ffi!(web_app_new, |args: &Value| { if let Some(s) = arg_str_opt(args, "layout").or_else(|| arg_str_opt(args, "布局")) { out.as_object_mut().unwrap().insert("layout".into(), json!(s)); } + if let Some(s) = arg_str_opt(args, "asset_version") + .or_else(|| arg_str_opt(args, "资源版本")) + { + out.as_object_mut() + .unwrap() + .insert("asset_version".into(), json!(s)); + } Ok(out) }); @@ -1642,7 +1670,12 @@ web_ffi!(web_db_table_info, |args: &Value| { }); -fn stamp_page_shell(page: &mut Value, shell_css: Option<&str>, layout: Option<&str>) { +fn stamp_page_shell( + page: &mut Value, + shell_css: Option<&str>, + layout: Option<&str>, + asset_version: Option<&str>, +) { let Some(obj) = page.as_object_mut() else { return; }; @@ -1666,6 +1699,16 @@ fn stamp_page_shell(page: &mut Value, shell_css: Option<&str>, layout: Option<&s obj.insert("layout".into(), json!(s)); } } + if let Some(s) = asset_version { + let empty = obj + .get("asset_version") + .and_then(|v| v.as_str()) + .unwrap_or("") + .is_empty(); + if empty { + obj.insert("asset_version".into(), json!(s)); + } + } } web_ffi!(web_listen, |args: &Value| { @@ -2057,11 +2100,15 @@ web_ffi!(web_listen, |args: &Value| { .get("layout") .or_else(|| admin_cfg_app.get("布局")) .and_then(|v| v.as_str()); + let app_asset_version = admin_cfg_app + .get("asset_version") + .or_else(|| admin_cfg_app.get("资源版本")) + .and_then(|v| v.as_str()); let mut page = page; let mut routes = routes; - stamp_page_shell(&mut page, app_shell, app_layout); + stamp_page_shell(&mut page, app_shell, app_layout, app_asset_version); for (_k, p) in routes.iter_mut() { - stamp_page_shell(p, app_shell, app_layout); + stamp_page_shell(p, app_shell, app_layout, app_asset_version); } http::listen( &page, @@ -2130,7 +2177,11 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int } let regs = [ - ("web_page_new", "title,intro,shell_css,layout", web_page_new as PluginFn), + ( + "web_page_new", + "title,intro,shell_css,layout,asset_version", + web_page_new as PluginFn, + ), ( "web_compose_components", "page,components", @@ -2239,7 +2290,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int ("web_media_new", "storage", web_media_new as PluginFn), ( "web_style", - "name,table", + "name,table,strict", web_style as PluginFn, ), ( @@ -2302,7 +2353,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int ("web_db_list_tables", "url", web_db_list_tables as PluginFn), ( "web_app_new", - "page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout", + "page,db,admin,host,port,admin_prefix,login_redirect,logout_redirect,shell_css,layout,asset_version", web_app_new as PluginFn, ), ("web_app_route", "app,path,page", web_app_route as PluginFn), diff --git a/plugins/web/src/render.rs b/plugins/web/src/render.rs index 8ff6678..728a4f5 100644 --- a/plugins/web/src/render.rs +++ b/plugins/web/src/render.rs @@ -469,7 +469,15 @@ fn head_html(args: &Value, default_title: &str) -> String { } if let Some(head) = args.get("head") { let links = crate::assets::head_links_from_json(head); - s.push_str(&crate::assets::render_head_links(&links)); + let asset_version = args + .get("asset_version") + .or_else(|| args.get("资源版本")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + s.push_str(&crate::assets::render_head_links_with_version( + &links, + asset_version, + )); } s } diff --git a/plugins/web/src/table.rs b/plugins/web/src/table.rs index 2da74f7..0278aef 100644 --- a/plugins/web/src/table.rs +++ b/plugins/web/src/table.rs @@ -335,20 +335,30 @@ pub fn normalize_slot(name: &str) -> String { /// | @keyframes pulse from | opacity | 0 | /// ``` pub fn as_css_named(name: &str, table: &Value) -> String { + as_css_named_checked(name, table, false).unwrap_or_default() +} + +/// Like [`as_css_named`], but when `strict` is true, reject cells that look like +/// T5 evaluated a bare `/` (numeric/bool CSS values). Default mode warns on stderr. +pub fn as_css_named_checked(name: &str, table: &Value, strict: bool) -> Result { let name = normalize_ref(name); if name.is_empty() { - return String::new(); + return Ok(String::new()); } let mut out = String::new(); match table { Value::Object(m) => { let sels = pick(m, SEL_KEYS).map(as_str_list).unwrap_or_default(); let props = pick(m, PROP_KEYS).map(as_str_list).unwrap_or_default(); - let vals = pick(m, VAL_KEYS).map(as_str_list).unwrap_or_default(); + let vals_raw = pick(m, VAL_KEYS); + let vals = vals_raw.map(as_str_list).unwrap_or_default(); let medias = pick(m, MEDIA_KEYS).map(as_str_list).unwrap_or_default(); let n = props.len().max(sels.len()).max(vals.len()); if n == 0 { - return String::new(); + return Ok(String::new()); + } + if let Some(raw) = vals_raw { + check_css_value_cells(raw, &props, strict)?; } let rows: Vec<(String, String, String, String)> = (0..n) .map(|i| { @@ -363,23 +373,68 @@ pub fn as_css_named(name: &str, table: &Value) -> String { emit_css_rows(&rows, &name, &mut out); } Value::Array(rows) => { - let rows: Vec<(String, String, String, String)> = rows - .iter() - .filter_map(|row| { - let m = row.as_object()?; - Some(( - pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(), - pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(), - pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(), - pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(), - )) - }) - .collect(); - emit_css_rows(&rows, &name, &mut out); + let mut collected = Vec::new(); + for row in rows { + let Some(m) = row.as_object() else { + continue; + }; + let prop = pick(m, PROP_KEYS).map(cell_str).unwrap_or_default(); + if let Some(v) = pick(m, VAL_KEYS) { + note_css_value_cell(&prop, v, strict)?; + } + collected.push(( + pick(m, MEDIA_KEYS).map(cell_str).unwrap_or_default(), + pick(m, SEL_KEYS).map(cell_str).unwrap_or_default(), + prop, + pick(m, VAL_KEYS).map(cell_str).unwrap_or_default(), + )); + } + emit_css_rows(&collected, &name, &mut out); } _ => {} } - out + Ok(out) +} + +fn css_value_suspicious(v: &Value) -> Option<&'static str> { + match v { + Value::Number(_) => Some( + "numeric CSS value (likely bare `/` division such as `1 / 5`; quote the cell, e.g. `\"1 / 5\"`)", + ), + Value::Bool(_) => Some("boolean CSS value (quote the cell if intentional)"), + _ => None, + } +} + +fn note_css_value_cell(prop: &str, val: &Value, strict: bool) -> Result<(), String> { + let Some(why) = css_value_suspicious(val) else { + return Ok(()); + }; + let prop = if prop.trim().is_empty() { + "(value)" + } else { + prop.trim() + }; + let msg = format!("ext/web style: suspicious cell for `{prop}`: {why}"); + if strict { + Err(msg) + } else { + eprintln!("warning: {msg}"); + Ok(()) + } +} + +fn check_css_value_cells(vals: &Value, props: &[String], strict: bool) -> Result<(), String> { + match vals { + Value::Array(a) => { + for (i, v) in a.iter().enumerate() { + let prop = props.get(i).map(|s| s.as_str()).unwrap_or(""); + note_css_value_cell(prop, v, strict)?; + } + } + other => note_css_value_cell(props.first().map(|s| s.as_str()).unwrap_or(""), other, strict)?, + } + Ok(()) } /// Parse `@keyframes name` or `@keyframes name stop` from a selector cell. @@ -742,4 +797,25 @@ mod css_tests { assert!(css.contains(".x {"), "{css}"); assert!(css.contains("color: red;"), "{css}"); } + + #[test] + fn strict_rejects_numeric_css_value() { + let t = json!([ + {"选择器": ".x", "属性": "grid-column", "值": 0}, + ]); + let err = as_css_named_checked("x", &t, true).unwrap_err(); + assert!(err.contains("suspicious"), "{err}"); + // Non-strict still emits (with warning on stderr). + let css = as_css_named_checked("x", &t, false).unwrap(); + assert!(css.contains("grid-column: 0;"), "{css}"); + } + + #[test] + fn quoted_string_ok_in_strict() { + let t = json!([ + {"选择器": ".x", "属性": "grid-column", "值": "1 / 5"}, + ]); + let css = as_css_named_checked("x", &t, true).unwrap(); + assert!(css.contains("grid-column: 1 / 5;"), "{css}"); + } } diff --git a/tests/ext/web-c3-style-head.mq.md b/tests/ext/web-c3-style-head.mq.md new file mode 100644 index 0000000..6f9c84d --- /dev/null +++ b/tests/ext/web-c3-style-head.mq.md @@ -0,0 +1,91 @@ +--- +title: web C3 style strict + head defer/version +description: Offline markers for quoted CSS cells and head script lifecycle. +import web:ext/web/web.mq.md +import sys:lib/sys.mq.md +--- + +# main + +`好` = +| 选择器 | 属性 | 值 | +|--------|------|-----| +| .box | grid-column | "1 / 5" | + +*css = > web.make_style name="t" table=`好` strict=True* +*a = > split value=`css` sep="1 / 5"* +*na = > len value=`a`* +1. `na` > 1 + > print text=quoted-css-ok +2. * + > print text=quoted-css-missing + > sys.exit code=1 + +`头` = +| 关系 | 地址 | 推迟 | 版本 | +|------|------|------|------| +| script | /static/a.js | 真 | 3 | +| stylesheet | /static/t.css | | 1 | + +*页 = > web.page title="c3" asset_version="appv"* +*页 = > `页`.head table=`头`* +*html = > `页`.render* +*b = > split value=`html` sep="a.js?v=3"* +*nb = > len value=`b`* +*c = > split value=`html` sep="t.css?v=1"* +*nc = > len value=`c`* +*d0 = > split value=`html` sep="script defer"* +*nd0 = > len value=`d0`* +1. `nb` > 1 + 1. `nc` > 1 + 1. `nd0` > 1 + > print text=defer-version-ok + 2. * + > print text=defer-attr-missing + > sys.exit code=1 + 2. * + > print text=css-version-missing + > sys.exit code=1 +2. * + > print text=defer-script-missing + > sys.exit code=1 + +`头2` = +| 关系 | 地址 | 推迟 | +|------|------|------| +| script | /static/b.js | 真 | + +*页2 = > web.page title="c3b" asset_version="2026-09-04"* +*页2 = > `页2`.head table=`头2`* +*h2 = > `页2`.render* +*d = > split value=`h2` sep="b.js?v=2026-09-04"* +*nd = > len value=`d`* +1. `nd` > 1 + > print text=asset-version-ok +2. * + > print text=asset-version-missing + > sys.exit code=1 + +`头3` = +| 关系 | 地址 | +|------|------| +| script | /static/sync.js | + +*页3 = > web.page title="c3c"* +*页3 = > `页3`.head table=`头3`* +*h3 = > `页3`.render* +*e = > split value=`h3` sep="sync.js"* +*ne = > len value=`e`* +*f = > split value=`h3` sep="script defer"* +*nf = > len value=`f`* +1. `ne` > 1 + 1. `nf` == 1 + > print text=sync-compat-ok + 2. * + > print text=unexpected-defer + > sys.exit code=1 +2. * + > print text=sync-script-missing + > sys.exit code=1 + +> print text=c3-style-head-ok