reactive-md 0.3.1 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (177) hide show
  1. package/CHANGELOG-ch.md +113 -0
  2. package/CHANGELOG.md +113 -53
  3. package/CONTRIBUTING-ch.md +62 -0
  4. package/CONTRIBUTING.md +64 -65
  5. package/LICENSE +21 -21
  6. package/README-ch.md +123 -0
  7. package/README-en.md +147 -0
  8. package/README.md +96 -38
  9. package/SECURITY-ch.md +80 -0
  10. package/SECURITY.md +58 -49
  11. package/THIRD_PARTY_NOTICES.md +85 -1
  12. package/bin/reactive-md.mjs +40 -0
  13. package/cli/args.mjs +181 -0
  14. package/cli/assets.mjs +390 -0
  15. package/cli/build.mjs +268 -0
  16. package/cli/document.mjs +130 -0
  17. package/cli/errors.mjs +61 -0
  18. package/cli/fs-utils.mjs +133 -0
  19. package/cli/glob.mjs +203 -0
  20. package/cli/help.mjs +138 -0
  21. package/cli/lint.mjs +177 -0
  22. package/cli/main.mjs +55 -0
  23. package/cli/migrate.mjs +368 -0
  24. package/cli/package.mjs +209 -0
  25. package/dist-library/reactive-md-react.js +3525 -1651
  26. package/dist-library/reactive-md.css +1 -1
  27. package/dist-library/reactive-md.js +1798 -4
  28. package/dist-library/runtime-D3QTVYaz.js +15410 -0
  29. package/dist-library/types/index.d.ts +1 -0
  30. package/dist-library/types/local/LocalDocumentView.d.ts +66 -3
  31. package/dist-library/types/local/authoring.d.ts +63 -0
  32. package/dist-library/types/local/collection-functions.d.ts +4 -0
  33. package/dist-library/types/local/colors.d.ts +2 -0
  34. package/dist-library/types/local/computations.d.ts +53 -0
  35. package/dist-library/types/local/data-functions.d.ts +22 -0
  36. package/dist-library/types/local/data-table.d.ts +65 -0
  37. package/dist-library/types/local/dates.d.ts +2 -0
  38. package/dist-library/types/local/dependencies.d.ts +31 -0
  39. package/dist-library/types/local/diagnostics.d.ts +1450 -0
  40. package/dist-library/types/local/expression.d.ts +13 -3
  41. package/dist-library/types/local/formatting.d.ts +41 -0
  42. package/dist-library/types/local/heading-anchors.d.ts +13 -2
  43. package/dist-library/types/local/i18n.d.ts +18 -0
  44. package/dist-library/types/local/index.d.ts +18 -1
  45. package/dist-library/types/local/limits.d.ts +32 -1
  46. package/dist-library/types/local/locale.d.ts +1 -0
  47. package/dist-library/types/local/math.d.ts +6 -1
  48. package/dist-library/types/local/parser.d.ts +10 -4
  49. package/dist-library/types/local/render-types.d.ts +5 -1
  50. package/dist-library/types/local/retention.d.ts +23 -0
  51. package/dist-library/types/local/schema.d.ts +25 -3
  52. package/dist-library/types/local/source-migration.d.ts +35 -0
  53. package/dist-library/types/local/state.d.ts +80 -0
  54. package/dist-library/types/local/text-length.d.ts +13 -0
  55. package/dist-library/types/local/theme.d.ts +30 -0
  56. package/dist-library/types/local/types.d.ts +112 -4
  57. package/dist-library/types/local/validation.d.ts +32 -0
  58. package/dist-library/types/local/version.d.ts +1 -1
  59. package/dist-library/types/local/worker.d.ts +82 -0
  60. package/dist-library/types/react/index.d.ts +4 -1
  61. package/dist-library/types/shareable.d.ts +64 -0
  62. package/dist-standalone/reactive-md-standalone.css +2 -0
  63. package/dist-standalone/reactive-md-standalone.js +57 -0
  64. package/docs/author-tools-ch.md +56 -0
  65. package/docs/author-tools-en.md +56 -0
  66. package/docs/compatibility-ch.md +103 -0
  67. package/docs/compatibility-en.md +103 -0
  68. package/docs/{component-development.md → component-development-ch.md} +210 -206
  69. package/docs/component-development-en.md +210 -0
  70. package/docs/{component-protocol.md → component-protocol-ch.md} +710 -685
  71. package/docs/component-protocol-en.md +710 -0
  72. package/docs/computations-formatting-ch.md +87 -0
  73. package/docs/computations-formatting-en.md +87 -0
  74. package/docs/constraints-collections-ch.md +84 -0
  75. package/docs/constraints-collections-en.md +84 -0
  76. package/docs/diagnostics-counting-ch.md +84 -0
  77. package/docs/diagnostics-counting-en.md +84 -0
  78. package/docs/local-components-v2-ch.md +138 -0
  79. package/docs/local-components-v2-en.md +104 -0
  80. package/docs/{local-guide.md → local-guide-ch.md} +28 -8
  81. package/docs/local-guide-en.md +961 -0
  82. package/docs/local-integration-ch.md +363 -0
  83. package/docs/local-integration-en.md +363 -0
  84. package/docs/{local-interaction-syntax.md → local-interaction-syntax-ch.md} +66 -20
  85. package/docs/local-interaction-syntax-en.md +483 -0
  86. package/docs/{performance.md → performance-ch.md} +12 -3
  87. package/docs/performance-en.md +76 -0
  88. package/docs/release-0.4.0-ch.md +89 -0
  89. package/docs/release-0.4.0-en.md +89 -0
  90. package/docs/release-0.4.1-ch.md +23 -0
  91. package/docs/release-0.4.1-en.md +23 -0
  92. package/docs/releasing-ch.md +101 -0
  93. package/docs/releasing-en.md +101 -0
  94. package/docs/shareable-export-ch.md +205 -0
  95. package/docs/shareable-export-en.md +207 -0
  96. package/docs/source-versioning-ch.md +159 -0
  97. package/docs/source-versioning-en.md +159 -0
  98. package/docs/theme-protocol-ch.md +107 -0
  99. package/docs/theme-protocol-en.md +107 -0
  100. package/examples/conformance/README.md +33 -31
  101. package/examples/conformance/component-protocol-1.json +482 -194
  102. package/examples/conformance/component-protocol-1.schema.json +76 -76
  103. package/examples/conformance/history/v0.3.1/catalog.reactive.md +20 -0
  104. package/examples/conformance/history/v0.3.1/charts.reactive.md +73 -0
  105. package/examples/conformance/history/v0.3.1/checklist.reactive.md +32 -0
  106. package/examples/conformance/history/v0.3.1/comparison.reactive.md +47 -0
  107. package/examples/conformance/history/v0.3.1/components.reactive.md +44 -0
  108. package/examples/conformance/history/v0.3.1/counter.reactive.md +7 -0
  109. package/examples/conformance/history/v0.3.1/diagnostics.reactive.md +54 -0
  110. package/examples/conformance/history/v0.3.1/diagram.reactive.md +44 -0
  111. package/examples/conformance/history/v0.3.1/gallery.reactive.md +61 -0
  112. package/examples/conformance/history/v0.3.1/local-draft-1.json +50 -0
  113. package/examples/conformance/history/v0.3.1/parameters.reactive.md +36 -0
  114. package/examples/conformance/history/v0.3.1/planning.reactive.md +24 -0
  115. package/examples/conformance/history/v0.3.1/pricing.reactive.md +20 -0
  116. package/examples/conformance/history/v0.3.1/provenance.json +72 -0
  117. package/examples/conformance/local-draft-2.json +212 -0
  118. package/examples/integration/README.md +45 -29
  119. package/examples/integration/core/index.mjs +32 -19
  120. package/examples/integration/core/package.json +7 -7
  121. package/examples/integration/react/index.html +12 -12
  122. package/examples/integration/react/main.jsx +21 -21
  123. package/examples/integration/react/package.json +9 -9
  124. package/examples/integration/worker/index.html +19 -0
  125. package/examples/integration/worker/main.js +61 -0
  126. package/examples/integration/worker/package.json +13 -0
  127. package/examples/integration/worker/worker.js +3 -0
  128. package/examples/local/README.md +64 -58
  129. package/examples/local/catalog.reactive.md +20 -20
  130. package/examples/local/charts.reactive.md +34 -34
  131. package/examples/local/checklist.reactive.md +32 -32
  132. package/examples/local/comparison.reactive.md +47 -47
  133. package/examples/local/components.reactive.md +44 -44
  134. package/examples/local/counter.reactive.md +7 -7
  135. package/examples/local/diagnostics.reactive.md +54 -54
  136. package/examples/local/diagram.reactive.md +44 -44
  137. package/examples/local/gallery.reactive.md +61 -61
  138. package/examples/local/parameters.reactive.md +36 -36
  139. package/examples/local/planning.reactive.md +24 -24
  140. package/examples/local/pricing.reactive.md +20 -20
  141. package/examples/local/recipes/invoice-zh.reactive.md +36 -0
  142. package/examples/local/recipes/invoice.reactive.md +36 -0
  143. package/examples/local/recipes/workshop-zh.reactive.md +33 -0
  144. package/examples/local/recipes/workshop.reactive.md +33 -0
  145. package/examples/local/showcase/README.md +25 -0
  146. package/examples/local/showcase/explore.reactive.md +102 -0
  147. package/examples/local/showcase/flow.reactive.md +86 -0
  148. package/examples/local/showcase/forms.reactive.md +126 -0
  149. package/examples/local/showcase/functions.reactive.md +119 -0
  150. package/examples/local/showcase/layout.reactive.md +100 -0
  151. package/examples/local/showcase/statistics.reactive.md +108 -0
  152. package/examples/local/showcase/tasks.reactive.md +89 -0
  153. package/examples/local/showcase/zh/explore.reactive.md +102 -0
  154. package/examples/local/showcase/zh/flow.reactive.md +86 -0
  155. package/examples/local/showcase/zh/forms.reactive.md +126 -0
  156. package/examples/local/showcase/zh/functions.reactive.md +119 -0
  157. package/examples/local/showcase/zh/layout.reactive.md +100 -0
  158. package/examples/local/showcase/zh/statistics.reactive.md +108 -0
  159. package/examples/local/showcase/zh/tasks.reactive.md +89 -0
  160. package/examples/local/zh/catalog.reactive.md +20 -0
  161. package/examples/local/zh/charts.reactive.md +73 -0
  162. package/examples/local/zh/checklist.reactive.md +32 -0
  163. package/examples/local/zh/comparison.reactive.md +47 -0
  164. package/examples/local/zh/components.reactive.md +44 -0
  165. package/examples/local/zh/counter.reactive.md +7 -0
  166. package/examples/local/zh/diagnostics.reactive.md +54 -0
  167. package/examples/local/zh/diagram.reactive.md +44 -0
  168. package/examples/local/zh/gallery.reactive.md +61 -0
  169. package/examples/local/zh/parameters.reactive.md +36 -0
  170. package/examples/local/zh/planning.reactive.md +24 -0
  171. package/examples/local/zh/pricing.reactive.md +20 -0
  172. package/package.json +91 -77
  173. package/README.en.md +0 -76
  174. package/dist-library/runtime-CPzMEMcW.js +0 -11111
  175. package/docs/compatibility.md +0 -68
  176. package/docs/local-integration.md +0 -218
  177. package/docs/releasing.md +0 -92
@@ -0,0 +1,87 @@
1
+ # 复用计算与格式化数值
2
+
3
+ 这些能力属于使用 `local-draft-2` 的 `0.4.0`。完整语法见[语法规范](local-interaction-syntax-ch.md),宿主接口见[集成说明](local-integration-ch.md),可运行文档见[账单示例](../examples/local/recipes/invoice-zh.reactive.md)。
4
+
5
+ ## 命名值
6
+
7
+ ```markdown
8
+ <const name="unitPrice" value="{{ 12.5 }}">
9
+ <computed name="total" value="{{ quantity * unitPrice }}">
10
+ <computed name="invoice" value="{{ formatCurrency(total, 'CNY', 2, 'zh-CN') }}">
11
+
12
+ <number bind="quantity" label="数量" initial="2" min="0" max="100">
13
+
14
+ 账单:**{{ invoice }}**。
15
+
16
+ <if when="{{ total >= 100 }}">
17
+ 达到批量配送门槛。
18
+ </if>
19
+ ```
20
+
21
+ `computed` 和 `const` 是不可见的无结束标签声明。每条声明独占文档顶层的一行,也接受 `/>`。两者都必须提供 `name` 和完整的 `value="{{ 表达式 }}"`。值支持数字、字符串、布尔值、null、字符串数组或数字数组。编译器推断类型,无需类型标注,也不进行隐式转换。数组字面量与聚合见[集合说明](constraints-collections-ch.md)。
22
+
23
+ 名称沿用 `bind` 的标识符和保留字规则。控件、槽位绑定与声明共用命名空间,声明不能覆盖其他声明或控件。容器内声明是编译错误。代码块、行内代码和注释内的声明保持原有的字面显示或惰性行为。
24
+
25
+ 声明在整个文档中可见,可以先引用后声明。`computed` 可以读取控件、常量和其他计算值。`const` 可以读取其他常量和 `pi` 等内置常量,必须独立于控件与计算值。因此,固定单价、阈值等参数无需显示禁用输入框。常量不提供编辑或重置控件。
26
+
27
+ 编译器从表达式 AST 提取全部分支的依赖,按依赖顺序推断类型。未知名称、重名、自引用和间接循环均产生带源码位置的错误;未执行分支里的环也属于编译错误。运算符和函数沿用普通表达式的类型规则。运行时仍可能出现域错误,例如读者把作为分母的控件改为零。
28
+
29
+ 正文、动态属性、条件和图表表格中的数值单元格都可以读取命名值。可计算 LaTeX 公式中的多字母数字名称写为 `\mathrm{total}`,例如 `y = \mathrm{total} x`。格式化字符串用于正文或标签;图表数值单元格和曲线参数使用原始数字。
30
+
31
+ ## 更新与错误
32
+
33
+ 每个运行时独立缓存计算结果。同一修订内复用中间值;控件修改、原子槽位修改或面板重置成功后更新计算。常量在编译时求值,创建运行时时复制。隐藏内容保留其输入与计算;重置范围沿用现有控件子树规则。
34
+
35
+ 消费者读取失败的计算值时,会收到其表达式错误,不会得到零、null 或上次成功值。独立消费者继续工作;有效输入可让失败的消费者恢复。逻辑与条件运算符保留运行时短路语义,未访问的分支不会读取其中的失败值。静态值非法的常量直接产生编译错误。
36
+
37
+ `document.bindings` 与 `document.initialState` 描述可写控件。`document.computations` 保存可序列化的声明元数据。`runtime.snapshot().state` 还包含本次修订成功求出的命名值,失败值缺席;需要保留错误语义时使用 `runtime.evaluate(name)`。`set` 和 `setMany` 不能修改声明。对外数组继续防止外部修改污染运行时。
38
+
39
+ ## 数字格式化
40
+
41
+ 四个函数都返回字符串,可选参数按位置传入。
42
+
43
+ | 函数 | 默认值与示例 |
44
+ | --- | --- |
45
+ | `formatNumber(value, digits, locale, grouping)` | `digits=2`、`locale="en-US"`、`grouping=true`;`formatNumber(1234.5)` 得到 `"1,234.50"` |
46
+ | `formatPercent(value, digits, locale)` | `digits=0`、`locale="en-US"`;`formatPercent(0.125, 1)` 得到 `"12.5%"` |
47
+ | `formatScientific(value, digits, locale)` | `digits=2`、`locale="en-US"`;`formatScientific(1234)` 得到 `"1.23E3"` |
48
+ | `formatCurrency(value, currency, digits, locale)` | `currency="USD"`、`digits=2`、`locale="en-US"`;`formatCurrency(12.5)` 得到 `"$12.50"` |
49
+
50
+ `digits` 必须是 0 至 20 的整数,同时固定最少与最多小数位;JPY 等货币也遵守该规则。`grouping` 必须是布尔值。地区只接受 `en-US`、`zh-CN`、`de-DE`、`fr-FR`、`ja-JP`,省略时固定为 `en-US`,与界面语言、设备设置无关;不支持的地区会报错。货币代码必须是 `Intl.NumberFormat` 接受的三个大写 ASCII 字母。这是代码形式检查,不是流通货币名录验证。
51
+
52
+ 格式化采用十进制 `halfExpand` 舍入,中点向远离零的方向舍入:`formatNumber(1.005)` 为 `"1.01"`,`formatNumber(-1.005)` 为 `"-1.01"`。零不显示负号。表达式运算仍使用有限的 JavaScript 数字;原有 `round(x)` 保留 `Math.round` 的中点向正无穷规则。格式化只改变显示,不改变源数值。
53
+
54
+ null 格式化为空字符串,其余参数严格检查类型,不把字符串自动转为数字。地区对应的标点、货币符号与空格来自宿主的 `Intl` 数据;跨平台需要逐字一致时,宿主应固定运行时及地区数据版本。
55
+
56
+ ## 字符串
57
+
58
+ | 函数 | 规则 |
59
+ | --- | --- |
60
+ | `trim(text)` | 去除首尾 JavaScript Unicode 空白 |
61
+ | `lower(text)`、`upper(text)` | 使用不依赖地区的默认 Unicode 大小写映射 |
62
+ | `startsWith(text, search)`、`endsWith(text, search)` | 区分大小写的字面匹配,空搜索串匹配成功 |
63
+ | `replace(text, search, replacement)` | 替换全部不重叠的字面匹配;空搜索串报错;`$&` 等替换文本保持字面含义 |
64
+ | `slice(text, start, end)` | 按 Unicode 码点索引,终点不包含在结果内,默认到末尾;负索引从末尾计算;索引必须为整数,超界时截到边界 |
65
+
66
+ 这些函数要求字符串,null 也会产生类型错误。函数不接受正则表达式或属性访问。码点不等于字素簇,一个组合表情或带组合重音的字母可能包含多个码点。所有结果沿用 100,000 个 UTF-16 代码单元的字符串预算;替换函数在分配超大结果前检查扩张长度。
67
+
68
+ ## 日期
69
+
70
+ `dateCompare(a, b)` 返回 `-1`、`0` 或 `1`。`dateDiff(a, b, unit)` 返回有符号的 **a 减 b**,默认单位为 `"days"`,还支持 `"hours"`、`"minutes"`、`"seconds"`、`"milliseconds"`。
71
+
72
+ 两项输入必须是有效的 `YYYY-MM-DD` 字符串,年份为 `0001` 至 `9999`,与日期控件一致,按公历校验闰日。每个日期表示 UTC 零点,因此设备时区和夏令时不会改变结果:`dateDiff("2026-03-09", "2026-03-08", "hours")` 为 `24`。时间戳、时区后缀和有歧义的地区日期格式会被拒绝。
73
+
74
+ 空日期控件的值为 `""`,表示未选择日期。空串或非法日期产生域错误,null 产生类型错误。可选日期应先判断:
75
+
76
+ ```markdown
77
+ <computed name="days" value="{{ startDate == '' || endDate == '' ? null : dateDiff(endDate, startDate) }}">
78
+ 天数:{{ days == null ? '请选择两个日期' : formatNumber(days, 0) }}
79
+ ```
80
+
81
+ ## 诊断与预算
82
+
83
+ 声明诊断采用 `local.computation.*`:`placement`、`name`、`reserved`、`duplicate`、`value`、`unknown`、`cycle`、`const`、`expression`、`budget`。表达式类型错误沿用 `local.expression.*`。诊断包含源码范围、行号和列号。计算图采用迭代式依赖排序,长链不依赖递归求值。源码、语法节点、表达式和值继续遵守现有预算,循环诊断数量也受诊断预算限制。
84
+
85
+ ## 兼容性
86
+
87
+ 现有表达式和 `round(x)` 保持原有行为。新增函数名称成为本版本的保留标识符;升级前应重命名使用这些名称的旧绑定,并同步修改引用。[变更记录](../CHANGELOG-ch.md)记载了此次扩展。
@@ -0,0 +1,87 @@
1
+ # Reusing calculations and formatting values
2
+
3
+ These additions belong to `0.4.0`, which uses `local-draft-2`. See the [syntax specification](local-interaction-syntax-en.md), [integration API](local-integration-en.md) and [working example](../examples/local/recipes/invoice.reactive.md).
4
+
5
+ ## Named values
6
+
7
+ ```markdown
8
+ <const name="unitPrice" value="{{ 12.5 }}">
9
+ <computed name="total" value="{{ quantity * unitPrice }}">
10
+ <computed name="invoice" value="{{ formatCurrency(total) }}">
11
+
12
+ <number bind="quantity" label="Quantity" initial="2" min="0" max="100">
13
+
14
+ Invoice: **{{ invoice }}**.
15
+
16
+ <if when="{{ total >= 100 }}">
17
+ Eligible for bulk delivery.
18
+ </if>
19
+ ```
20
+
21
+ `computed` and `const` are invisible, void declarations. Write each on its own line at document top level; `/>` is accepted too. Both require `name` and a complete `value="{{ expression }}"`. Their values use the expression types: number, string, boolean, null, string array or numeric array. The compiler infers the type; there is no type annotation or implicit conversion. See [collections](constraints-collections-en.md) for array literals and aggregates.
22
+
23
+ Names follow the same identifier and reserved-name rules as `bind`. Controls, multi-slot bindings and declarations share one namespace. A declaration cannot replace another declaration or a control. Declarations inside containers are compile errors. Code fences, inline code and comments remain literal or inert.
24
+
25
+ Declarations are visible throughout the document, including before their source position. A `computed` value may read controls, constants and other computations. A `const` may read other constants and built-in constants such as `pi`; it must remain independent of controls and computations. This supports fixed prices and thresholds without displaying a disabled input. Constants have no editing or reset control.
26
+
27
+ The compiler extracts dependencies from the expression AST, including all conditional branches. It orders declarations by dependency before inferring types. Unknown names, duplicate names, self references and indirect cycles produce source-positioned errors. A cycle in an unused branch is still a compile error. Type checking uses the same operator and function rules as ordinary expressions; runtime domain errors remain possible, for example division by a control that becomes zero.
28
+
29
+ Use a named value anywhere an expression is accepted: prose, dynamic attributes, conditions and numeric table cells used by charts. Computable LaTeX formulas read multi-letter numeric names as `\mathrm{total}`, for example `y = \mathrm{total} x`. Formatted strings belong in labels or prose; numeric chart cells and plot parameters need the underlying number.
30
+
31
+ ## Updates and errors
32
+
33
+ Each runtime owns its calculation cache. Computations are reused within a revision and refreshed after a successful control edit, atomic multi-slot edit or panel reset. Constants are evaluated at compilation and copied into each runtime. Hiding a section keeps its inputs and calculations; reset follows the existing control subtree rules.
34
+
35
+ A failed calculation propagates its expression error when a consumer reads it. The runtime never substitutes zero, null or a previous successful value. Independent consumers continue to work, and a valid input edit lets failed consumers recover. Runtime logical and conditional operators keep their usual short-circuit behavior: an unvisited branch does not read its failed value. A constant with an invalid static value is a compile error.
36
+
37
+ `document.bindings` and `document.initialState` describe writable controls. `document.computations` contains serializable declaration metadata. `runtime.snapshot().state` also contains successful named results for the current revision; failed results are absent. Use `runtime.evaluate(name)` to read a result with its error semantics. Declarations cannot be changed through `set` or `setMany`. Returned arrays remain protected from external mutation.
38
+
39
+ ## Number formatting
40
+
41
+ All four functions return strings. Optional arguments are positional.
42
+
43
+ | Function | Defaults and example |
44
+ | --- | --- |
45
+ | `formatNumber(value, digits, locale, grouping)` | `digits=2`, `locale="en-US"`, `grouping=true`; `formatNumber(1234.5)` gives `"1,234.50"` |
46
+ | `formatPercent(value, digits, locale)` | `digits=0`, `locale="en-US"`; `formatPercent(0.125, 1)` gives `"12.5%"` |
47
+ | `formatScientific(value, digits, locale)` | `digits=2`, `locale="en-US"`; `formatScientific(1234)` gives `"1.23E3"` |
48
+ | `formatCurrency(value, currency, digits, locale)` | `currency="USD"`, `digits=2`, `locale="en-US"`; `formatCurrency(12.5)` gives `"$12.50"` |
49
+
50
+ `digits` must be an integer from 0 to 20. It fixes both minimum and maximum fraction digits, including for currencies such as JPY. `grouping` must be a boolean. Supported locales are exactly `en-US`, `zh-CN`, `de-DE`, `fr-FR` and `ja-JP`; omission always uses `en-US`, independently of the renderer's UI language or device settings. Unsupported locales are errors. Currency codes must be three uppercase ASCII letters accepted by `Intl.NumberFormat`; this is a syntax check, not a registry of circulating currencies.
51
+
52
+ Formatting uses decimal `halfExpand` rounding: ties round away from zero, so `formatNumber(1.005)` gives `"1.01"` and `formatNumber(-1.005)` gives `"-1.01"`. Zero displays without a negative sign. Arithmetic still uses finite JavaScript numbers; `round(x)` retains its existing `Math.round` rule, with ties toward positive infinity. Formatting changes presentation, not the source number.
53
+
54
+ A null value formats as an empty string. Other argument types remain strict: strings are not converted into numbers. Explicitly guard optional dates or text before applying their functions. Locale-specific punctuation, currency symbols and spacing follow the host's `Intl` data; hosts that need byte-identical text across platforms should pin their runtime and locale data.
55
+
56
+ ## Strings
57
+
58
+ | Function | Behavior |
59
+ | --- | --- |
60
+ | `trim(text)` | Remove leading and trailing JavaScript Unicode whitespace |
61
+ | `lower(text)`, `upper(text)` | Default Unicode case conversion, independent of locale |
62
+ | `startsWith(text, search)`, `endsWith(text, search)` | Case-sensitive literal checks; empty search matches |
63
+ | `replace(text, search, replacement)` | Replace every non-overlapping literal match; empty search is an error; replacement text such as `$&` stays literal |
64
+ | `slice(text, start, end)` | Unicode code point indices; end is exclusive and defaults to the length; negative indices count from the end; indices are integers and clamp to bounds |
65
+
66
+ These functions require strings, including when the value is null. No regular expressions or property access are available. Code points are distinct from grapheme clusters: a combined emoji or an accented letter can contain several code points. All results keep the existing string budget of 100,000 UTF-16 code units. Replacement expansion is checked before constructing an oversized result.
67
+
68
+ ## Dates
69
+
70
+ `dateCompare(a, b)` returns `-1`, `0` or `1`. `dateDiff(a, b, unit)` returns the signed difference **a minus b**; the default unit is `"days"`. Other units are `"hours"`, `"minutes"`, `"seconds"` and `"milliseconds"`.
71
+
72
+ Both arguments must be valid `YYYY-MM-DD` strings in years `0001` through `9999`, matching date controls. The calendar is Gregorian; leap days are validated. Each date means midnight UTC. Device timezone and daylight saving changes therefore do not change the result: `dateDiff("2026-03-09", "2026-03-08", "hours")` is `24`. Timestamps, timezone suffixes and ambiguous regional date strings are rejected.
73
+
74
+ An empty date control contains `""`; this is an absent date, not epoch zero. Empty or invalid dates produce a domain error; null produces a type error. Guard optional dates explicitly:
75
+
76
+ ```markdown
77
+ <computed name="days" value="{{ startDate == '' || endDate == '' ? null : dateDiff(endDate, startDate) }}">
78
+ Days: {{ days == null ? 'Choose both dates' : formatNumber(days, 0) }}
79
+ ```
80
+
81
+ ## Diagnostics and limits
82
+
83
+ Declaration diagnostics use `local.computation.*`: `placement`, `name`, `reserved`, `duplicate`, `value`, `unknown`, `cycle`, `const`, `expression` and `budget`. Expression type errors keep the existing `local.expression.*` codes. Diagnostics include source ranges, lines and columns. The graph uses an iterative dependency order, so long chains do not require recursive evaluation. Existing source, syntax-node, expression and value budgets still apply; cycle reports are capped by the diagnostic budget.
84
+
85
+ ## Compatibility
86
+
87
+ Existing expressions and `round(x)` keep their behavior. The new function names are reserved identifiers in this release. Rename any pre-existing bindings with these names and update their references before upgrading. The [changelog](../CHANGELOG.md) lists this addition.
@@ -0,0 +1,84 @@
1
+ # 条件、校验与本地集合
2
+
3
+ 这些能力扩展使用 `local-draft-2` 的 `0.4.0`。[工作坊示例](../examples/local/recipes/workshop-zh.reactive.md)把人数预算、日期区间和已选主题表格放在同一份文档里,[命名计算](computations-formatting-ch.md)保存其中间结果。
4
+
5
+ ## 跨字段校验
6
+
7
+ ```markdown
8
+ <number bind="people" label="人数" initial="4" min="1" max="20">
9
+ <number bind="capacity" label="房间容量" initial="3" min="1" max="20">
10
+ <validation when="{{ people <= capacity }}" message="请选择能容纳 {{ people }} 人的房间。" fields="people capacity">
11
+ ```
12
+
13
+ `validation` 是无结束标签的块组件,必须提供 `when`、`message`、`fields`。`when` 包含一个完整的布尔表达式;`message` 是提示文字,可以包含普通插值;`fields` 以空白分隔关联的公开可写绑定名,名称不能重复,也可使用多槽位控件的绑定。规则能读取控件和计算值,允许前向引用。只读声明不能作为关联字段。
14
+
15
+ 约束提示文档当前是否一致。读者可以继续编辑不一致的计划,初始值不满足跨字段规则也能正常显示和修改。例如,人数从四人改为六人后可能暂时超过容量,再换房间即可消除提示。单个控件原有的数字范围、日期合法性等规则继续拒绝非法写入。
16
+
17
+ `runtime.validate()` 按源码顺序返回当前失败规则的诊断。条件为 false 时使用 `local.validation.failed`,表达式无法求值时使用 `local.validation.expression`,错误也视为失败。一条失败规则不会阻断其他规则。结果按运行时修订缓存,对外返回副本;编辑、原子槽位更新及重置会同步刷新计算与校验。
18
+
19
+ 渲染器显示失败提示,并通过 `aria-describedby` 和 `aria-invalid` 把提示关联到字段或其可访问分组。提示 ID 属于各自文档实例;通过校验后清除错误文字。隐藏内容中的规则继续生效,但隐藏提示不会主动播报。每份文档最多有 100 条规则,隐藏区域也计入;诊断文字沿用 2,000 字符上限。
20
+
21
+ ## 受控的条件样式
22
+
23
+ ```markdown
24
+ <badge tone="{{ total <= budget ? 'success' : 'warning' }}">{{ formatCurrency(total) }}</badge>
25
+ <alert tone="{{ total <= budget ? 'info' : 'warning' }}">预订前请核对预算。</alert>
26
+ ```
27
+
28
+ 本版本允许两个现有组件动态设置 `tone`:`badge` 接受 `neutral`、`success`、`warning`,`alert` 接受 `info`、`success`、`warning`。静态值保持原有行为。动态表达式必须是字符串类型,渲染器还会检查结果是否属于组件允许的枚举。表达式错误或非法值会使用默认样式并显示计算提示。这个条件接口不接受作者 CSS 类、样式字符串或动态颜色。
29
+
30
+ 有限枚举可表达警告和成功状态,同时让主题继续控制颜色与对比度。更广泛的条件样式需要另行确定可访问性与主题规则。
31
+
32
+ ## 数组与索引
33
+
34
+ ```markdown
35
+ <const name="fixedFees" value="{{ [100, 20, 5] }}">
36
+ <computed name="fees" value="{{ [people * 80, includeKit ? people * 20 : 0] }}">
37
+
38
+ 第一项:{{ fees[0] }}。合计:{{ sum(fees) }}。
39
+ ```
40
+
41
+ 数组字面量只能包含同一种类型的字符串或有限数字,元素表达式可以读取文档命名值。嵌套数组、混合类型、布尔值和 null 元素会被拒绝。`[]` 默认是空数字数组;条件分支直接写空字面量时,可采用另一分支的字符串数组类型,因此字符串多选值也可使用 `show ? subjects : []`。已有清单与多选控件继续产生字符串数组。公开类型 `LocalValue` 增加 `number[]`,`LocalValueKind` 增加 `number-array`,原来的 `array` 继续表示字符串数组。
42
+
43
+ 索引从零开始,`values[0]` 读取第一项。索引必须是有限的安全整数;超出范围的整数(包括负数)返回 null,非整数报错。字符串和其他标量不能作为数组索引。数组不能直接插值显示,应使用索引、`len`、聚合或数据表格。
44
+
45
+ `len` 支持两种数组;`contains` 在字符串数组中接受字符串,在数字数组中接受数字,原有字符串子串检查不变。每个数组最多 10,000 项;数组字面量还计入既有表达式长度、AST 节点和求值预算。字符串数组内容继续受字符预算限制。运行时返回数组副本,快照数组被冻结。
46
+
47
+ ## 简单数字聚合
48
+
49
+ | 函数 | 结果 |
50
+ | --- | --- |
51
+ | `sum(values)` | 数字数组之和,空数组返回 `0` |
52
+ | `average(values)` | 算术平均值,空数组返回 null |
53
+ | `minOf(values)` | 最小项,空数组返回 null |
54
+ | `maxOf(values)` | 最大项,空数组返回 null |
55
+
56
+ 聚合只接受数字数组,不自动转换看起来像数字的字符串。结果使用有限的 JavaScript 数字,求和或结果溢出会产生表达式错误;`average` 先求和再除以项数,中间求和溢出也会报错。空聚合产生的 null 沿用现有可空表达式规则,需要时先判断再参与数值运算。标量 `min`、`max`、`round` 保持原有签名与行为。
57
+
58
+ ## 从本地值生成表格行
59
+
60
+ ```markdown
61
+ <const name="subjects" value="{{ ['mathematics', 'physics', 'chemistry'] }}">
62
+
63
+ <data-table label="主题准备工作" rows="{{ subjects }}" key="{{ item }}" max-rows="3">
64
+ <column label="主题" value="{{ item }}">
65
+ <column label="序号" value="{{ index + 1 }}">
66
+ <column label="准备工作" value="{{ item == 'chemistry' ? '准备材料' : '准备例题' }}">
67
+ </data-table>
68
+ ```
69
+
70
+ `data-table` 是成对的块组件,必须提供可访问名称 `label`、完整数组表达式 `rows`,以及完整字符串或数字表达式 `key`。子内容只能是 1 至 20 个无结束标签的 `column` 声明。列必须提供静态标题 `label` 和完整的标量 `value` 表达式;单元格只输出文本,null 为空单元格。
71
+
72
+ 每行有两个局部名称:`item` 是当前字符串或数字,`index` 是当前从零开始的位置。列表达式中这两个名称覆盖同名全局值,其他引用仍读取文档环境。`rows` 自身使用普通文档作用域。
73
+
74
+ 键表达式只能依赖 `item`,且至少引用它一次,不能依赖 `index` 或其他文档值。表格检查键是否为非空字符串或有限数字,并确保唯一。数字键和字符串键属于不同标识,数字正负零视为同一标识;条目重排时保留 React 行身份。需要重复显示值时,应以不同的本地 ID 组成 `rows`,再根据 ID 生成显示列。重复键或非法键会使整张表显示错误。
75
+
76
+ `max-rows` 是 1 至 1,000 的静态整数,默认 100。整份文档各表声明的行预算总和最多 2,000,行预算乘列数的总和最多 10,000 个单元格,隐藏表格也计入。每张生成表还有 100,000 个 UTF-16 代码单元的预算,覆盖表头、单元格、错误或空状态占位文字及编码后的行键。渲染器在显示行之前检查预算,超出时显示错误,不截断数据。
77
+
78
+ 空数组显示表头与空状态。数据源或键求值失败时清除表格行并显示错误;单元格表达式失败只影响该单元格,其余内容继续显示。组件只生成原生表格行,不重复任意文档区块或控件。原有 Markdown 表格及其图表输入保持原有行为。
79
+
80
+ ## 集成与兼容性
81
+
82
+ `LocalDocument.validations` 保存可序列化的 `LocalValidation` 元数据,宿主可随时调用 `runtime.validate()`,调用不会修改状态。编译后的文档仍可用 `structuredClone` 传递给 Worker。对象生命周期和持久化规则见[集成说明](local-integration-ch.md)。
83
+
84
+ 新增聚合函数名 `sum`、`average`、`minOf`、`maxOf` 成为保留字,升级前需重命名冲突绑定及其引用。对 `LocalValueKind` 做穷举检查的宿主应加入 `number-array`;可写多选与清单控件仍只接受字符串。预览版发布在 `next` 渠道。
@@ -0,0 +1,84 @@
1
+ # Constraints, conditional tones and local collections
2
+
3
+ These additions extend `0.4.0`, which uses `local-draft-2`. The [workshop example](../examples/local/recipes/workshop.reactive.md) combines a participant budget, a date interval and a selected-subject table. [Named calculations](computations-formatting-en.md) hold its intermediate results.
4
+
5
+ ## Cross-field validation
6
+
7
+ ```markdown
8
+ <number bind="people" label="Participants" initial="4" min="1" max="20">
9
+ <number bind="capacity" label="Room capacity" initial="3" min="1" max="20">
10
+ <validation when="{{ people <= capacity }}" message="Choose a room for at least {{ people }} people." fields="people capacity">
11
+ ```
12
+
13
+ `validation` is a void block component with required `when`, `message` and `fields` attributes. `when` must contain one complete boolean expression. `message` is text with optional ordinary interpolations. `fields` lists distinct public writable binding names, separated by whitespace; names from multi-slot controls are accepted too. A rule can read controls and computed values, including values declared later. Fields identify the controls associated with its hint; read-only declarations cannot be fields.
14
+
15
+ Constraints report the current consistency of a document. Readers can still edit an inconsistent plan, including one whose initial values fail a cross-field rule. For example, changing the participant count from four to six can temporarily exceed room capacity; changing the room then clears the hint. Existing individual control rules, such as numeric bounds and invalid calendar dates, keep their write-rejection behavior.
16
+
17
+ `runtime.validate()` returns diagnostics for all current failed rules in source order. It reports `local.validation.failed` when `when` is false and `local.validation.expression` when an expression cannot be evaluated. Errors count as failures. One failed rule does not stop independent rules. The result is cached for the current runtime revision and returned as defensive copies. Edits, atomic slot updates and resets refresh calculations and validation together.
18
+
19
+ The renderer displays failed-rule hints and associates them with the corresponding controls or their accessible groups using `aria-describedby` and `aria-invalid`. Hint IDs belong to the mounted document instance. Success removes the error text. Rules in hidden content remain active, as do their bindings; hidden hints do not announce themselves. A document supports at most 100 validation rules, including hidden regions. Diagnostic messages retain the existing 2,000-character bound.
20
+
21
+ ## Conditional visual emphasis
22
+
23
+ ```markdown
24
+ <badge tone="{{ total <= budget ? 'success' : 'warning' }}">{{ formatCurrency(total) }}</badge>
25
+ <alert tone="{{ total <= budget ? 'info' : 'warning' }}">Review the estimate before booking.</alert>
26
+ ```
27
+
28
+ This build supports dynamic `tone` on two existing components. `badge` accepts `neutral`, `success` and `warning`; `alert` accepts `info`, `success` and `warning`. Static values retain their existing behavior. Dynamic expressions must have string type, and the renderer checks the returned value against the component's allowed tones. An error or unsupported value uses the default tone and a visible computation hint. CSS classes, author styles and colors remain outside this conditional API.
29
+
30
+ The limited enum covers warning and success emphasis while keeping theme colors and contrast under host control. More general conditional styling would need separate accessibility and theme rules.
31
+
32
+ ## Arrays and indexing
33
+
34
+ ```markdown
35
+ <const name="fixedFees" value="{{ [100, 20, 5] }}">
36
+ <computed name="fees" value="{{ [people * 80, includeKit ? people * 20 : 0] }}">
37
+
38
+ First fee: {{ fees[0] }}. Total: {{ sum(fees) }}.
39
+ ```
40
+
41
+ Array literals contain only strings or only finite numbers. Expressions inside a literal can read the document's named values. Nested arrays, mixed element types, booleans and null elements are rejected. `[]` is an empty numeric array by default; a direct empty literal in a conditional branch adopts a string-array sibling's kind, so `show ? subjects : []` works for string selections. Existing checklist and multi-select values remain string arrays. The public type `LocalValue` gains `number[]`, and `LocalValueKind` gains `number-array`; its existing `array` kind continues to mean a string array.
42
+
43
+ Indexing is zero based: `values[0]` reads the first element. The index must be a finite safe integer. An integer outside the collection, including a negative index, returns null; a non-integer index is an error. Indexing a string or a scalar is a type error. Arrays themselves cannot be interpolated as text; use an index, `len`, an aggregate or a data table.
44
+
45
+ `len` counts both kinds of array. `contains` accepts a string member for a string array and a number for a numeric array. String containment keeps its existing behavior. Every array is bounded by 10,000 elements; array literals also consume the existing expression-length, AST-node and evaluation budgets. The total contents of a string array keep the existing character budget. Returned runtime arrays are copied, and snapshot arrays are frozen.
46
+
47
+ ## Numeric aggregates
48
+
49
+ | Function | Result |
50
+ | --- | --- |
51
+ | `sum(values)` | Sum of a numeric array; empty input gives `0` |
52
+ | `average(values)` | Arithmetic mean; empty input gives null |
53
+ | `minOf(values)` | Smallest numeric member; empty input gives null |
54
+ | `maxOf(values)` | Largest numeric member; empty input gives null |
55
+
56
+ Aggregates accept numeric arrays, with no conversion of numeric-looking strings. Results use finite JavaScript numbers; an overflow in the sum or result is an expression error. `average` divides the sum by the count, so an overflowing intermediate sum is also an error. Null from an empty aggregate follows existing nullable-expression rules, so guard it before numeric operations when needed. Scalar `min`, `max` and `round` keep their existing signatures and behavior.
57
+
58
+ ## Generate table rows from local values
59
+
60
+ ```markdown
61
+ <const name="subjects" value="{{ ['mathematics', 'physics', 'chemistry'] }}">
62
+
63
+ <data-table label="Subject preparation" rows="{{ subjects }}" key="{{ item }}" max-rows="3">
64
+ <column label="Subject" value="{{ item }}">
65
+ <column label="Position" value="{{ index + 1 }}">
66
+ <column label="Preparation" value="{{ item == 'chemistry' ? 'Prepare materials' : 'Prepare examples' }}">
67
+ </data-table>
68
+ ```
69
+
70
+ `data-table` is a paired block component. It requires an accessible `label`, a complete array expression in `rows`, and a complete string or number expression in `key`. Its only children are 1 to 20 void `column` declarations. A column requires a static `label` and a complete scalar `value` expression. Cells output plain text; null gives an empty cell.
71
+
72
+ Each row has two local names: `item` is the current string or number, and `index` is its current zero-based position. These names shadow same-named document values inside column expressions. Other references use the normal document environment. The source `rows` expression uses ordinary document scope.
73
+
74
+ Keys depend only on `item`, including at least one reference to it. They cannot depend on `index` or other document values. The table checks that every evaluated key is a nonempty string or finite number and is unique. Numeric and string keys have distinct identities; signed numeric zeros have the same identity. React rows retain their identities when their items reorder. For records with repeated display values, use a collection of distinct local IDs as `rows` and derive the display cells from those IDs. Duplicate or invalid keys produce a whole-table error.
75
+
76
+ `max-rows` is a static integer from 1 to 1,000, defaulting to 100. Across the document, declared row budgets may total at most 2,000 and row budgets multiplied by their column counts may total at most 10,000 cells. Hidden tables count too. Each generated table also has a budget of 100,000 UTF-16 code units for header text, cell text, error/empty placeholders and encoded row keys. The renderer checks budgets before exposing rows; exceeding them reports an error without truncating the data.
77
+
78
+ An empty array displays the headers and an empty-state message. Failure of the row source or a key clears the table's rows and displays an error. A cell-expression failure is shown in that cell while independent cells remain readable. The component creates native table rows, not arbitrary repeated document sections or controls. Markdown tables and their existing chart inputs keep their original behavior.
79
+
80
+ ## Integration and compatibility
81
+
82
+ `LocalDocument.validations` contains serializable `LocalValidation` metadata. Hosts can call `runtime.validate()` at any time without changing state. The compiled document remains transferable to a Worker with `structuredClone`. The [core integration guide](local-integration-en.md) describes its lifetime and persistence rules.
83
+
84
+ The aggregate names `sum`, `average`, `minOf` and `maxOf` become reserved identifiers. Rename conflicting bindings and their references before using this release. Hosts with exhaustive `LocalValueKind` checks should add `number-array`; writable multi-select and checklist controls still require strings. The preview is published on the `next` channel.
@@ -0,0 +1,84 @@
1
+ # 诊断与计数规则
2
+
3
+ [English](diagnostics-counting-en.md)
4
+
5
+ 本页定义 0.4.x 的诊断契约、字符长度单位与资源预算作用域。
6
+
7
+ ## 诊断契约
8
+
9
+ `Diagnostic` 的机器字段为 `code`、`severity`、`range`、`line` 和 `column`。`message` 是默认英文显示文本。宿主使用 `formatLocalDiagnostic(diagnostic, 'zh')` 或 `'en'` 取得对应语言的消息,编辑器与 CLI 使用同一入口。可选的消息模板标识和参数用于本地化;未知宿主诊断使用原始 `message`,显示时仍执行长度上限。
10
+
11
+ ```ts
12
+ import { compileLocal, formatLocalDiagnostic } from 'reactive-md';
13
+
14
+ const result = compileLocal(source);
15
+ for (const diagnostic of result.diagnostics) {
16
+ console.log(diagnostic.code, formatLocalDiagnostic(diagnostic, 'zh'));
17
+ }
18
+ ```
19
+
20
+ 切换语言保留诊断码、严重程度和源码位置。同一 `0.x` minor 系列内,现有诊断码的含义保持稳定;可以新增诊断码,不能把旧码改用于另一类错误。删除、改名或改变含义须在新的 minor 版本中说明迁移。显示文案可以改进,机器判断应使用 `code` 和结构化字段。
21
+
22
+ `range` 使用从零开始的 UTF-16 索引,表示半开区间 `[start, end)`。`line` 和 `column` 从 1 开始,列按 UTF-16 代码单元计数。LF 换行使行号增加,CRLF 占两个源码代码单元。范围始终指向未经规范化的原始源码。
23
+
24
+ 诊断数量达到上限时,新警告可以被省略;新的错误优先替换已有警告。编译错误使 `ok` 为 `false`。运行时写入被拒绝时,已提交状态与 revision 保持不变。
25
+
26
+ ## 文本长度
27
+
28
+ | 用途 | 计数单位 |
29
+ | --- | --- |
30
+ | 源码偏移、诊断列号、源码与字符串资源预算 | UTF-16 代码单元,即 JavaScript `string.length` |
31
+ | 字符串的 `len()`、文本控件 `min-length` / `max-length` | Unicode 码点 |
32
+ | 数组的 `len()`、数组项数限制 | 元素个数 |
33
+
34
+ 例如,`😀` 占 2 个 UTF-16 代码单元、1 个码点;`e` 加组合重音占 2 个码点;`👩‍💻` 占 5 个 UTF-16 代码单元、3 个码点。长度校验按码点,不合并字素簇,也不执行 Unicode 规范化。未配对的 UTF-16 代理项按一次字符串迭代计为 1。
35
+
36
+ 编译器的初值校验、运行时写入校验和参考渲染器使用相同规则。独立的字符串资源预算先按 UTF-16 检查,邮箱的 254 上限也保持 UTF-16 计数。`countLocalCodePoints(value)` 提供与文本约束相同的计数。
37
+
38
+ 文档预算统计原始源码;属性值在支持的 HTML 实体解码后计数。字符串拼接与插值还会检查结果长度。例如,属性中的 `&amp;` 在源码中占 5 个代码单元,解码后占 1 个。属性引号内的换行仍计入值的长度。
39
+
40
+ ## 资源预算
41
+
42
+ 长度上限均包含边界值,超过上限才拒绝。每次独立编译或求值从对应预算的起点重新累计;缓存命中仍须遵守该操作的输入和状态校验。
43
+
44
+ | 资源 | 上限与单位 | 累计范围 |
45
+ | --- | --- | --- |
46
+ | 文档源码 | 1,000,000 个 UTF-16 代码单元 | 每次编译的原始源码 |
47
+ | 语法节点 | 默认 10,000 个 | 每次解析期间累计构造,包含中间节点;宿主可按次配置 |
48
+ | 组件嵌套 | 100 层 | 当前组件解析调用链 |
49
+ | 标签名、属性名、绑定名 | 128 个 UTF-16 代码单元 | 每个名称 |
50
+ | 主题名称 | 64 个 UTF-16 代码单元 | 每个主题名称 |
51
+ | 字符串值、属性、模板 | 100,000 个 UTF-16 代码单元 | 每个值或模板,拼接输出也受限 |
52
+ | 数组 | 10,000 项 | 每个数组 |
53
+ | 数组成员字符串长度之和 | 100,000 个 UTF-16 代码单元 | 每个数组的所有字符串成员 |
54
+ | 邮箱地址 | 254 个 UTF-16 代码单元 | 每个非空邮箱值 |
55
+ | 编译诊断 | 100 条 | 每次编译,解析和编译阶段共同计数 |
56
+ | 单条诊断消息 | 2,000 个 UTF-16 代码单元 | 每条显示消息;超出部分截断 |
57
+ | 诊断模板参数 | 最多 16 个,单个字符串 256、全部值文本合计 2,000 个 UTF-16 代码单元 | 每条诊断的可序列化参数;超出部分截断或省略 |
58
+ | 表达式源码 | 4,000 个 UTF-16 代码单元 | 每个表达式 |
59
+ | 表达式 AST | 2,000 个节点 | 每个表达式的累计构造 |
60
+ | 表达式解析 / AST 深度 | 100 / 200 层 | 解析调用深度 / 最终 AST 深度 |
61
+ | 表达式求值 | 10,000 次节点访问、250 层深度 | 每次表达式求值;短路分支仅计实际访问 |
62
+ | LaTeX 源码 | 50,000 个 UTF-16 代码单元 | 每个公式 |
63
+ | LaTeX 记号 / AST | 20,000 个记号 / 5,000 个节点 | 每个公式解析,记号数含 EOF |
64
+ | LaTeX 解析 / 求值深度 | 120 / 1,000 层 | 对应调用链 |
65
+ | 独立 LaTeX 求值 | 默认 20,000 次节点访问 | 每次 `evaluate`;显式共享预算按传入预算累计 |
66
+ | 绘图曲线 | 16 条 | 每个 `<plot>` |
67
+ | 每条曲线采样 | 2 至 2,000 点 | 每次采样请求,端点计入 |
68
+ | 文档采样点总量 | 20,000 点 | 所有绘图的曲线数乘以请求采样数,包含隐藏区域 |
69
+ | 校验规则 | 每份文档 100 条 | 包含隐藏区域中的规则 |
70
+ | 每张 `<data-table>` 的生成行 | 最多 1,000,默认 100 | 单表声明的 `max-rows` |
71
+ | 每张 `<data-table>` 的列数 | 20 列 | 单表 |
72
+ | 文档生成行总量 | 2,000 行 | 所有 `data-table` 声明 `max-rows` 之和,含隐藏表格 |
73
+ | 文档生成单元格总量 | 10,000 个 | 所有 `data-table` 的声明行数乘列数之和 |
74
+ | 生成表格文字 | 100,000 个 UTF-16 代码单元 | 单表的表头、单元格、空/错误文字及编码行键 |
75
+ | 单条曲线计算 | `max(1,000,000, samples × 1024)` 次节点访问 | 一次 `samplePlot`,包含间断检测的额外求值 |
76
+ | 文档绘图计算 | 2,000,000 次节点访问 | 同一运行时 revision 内所有绘图采样;新 revision 重置 |
77
+
78
+ 计算步数计 AST 求值节点访问,不是毫秒。独立调用 `samplePlot` 时,跨曲线的共享累计由调用者传入共享预算;参考渲染器为文档维护共享预算和采样缓存。
79
+
80
+ 表达式编译缓存最多 500 项,公式编译缓存最多 512 项,每个运行时的表达式缓存最多 200 项。它们按条目管理内存,不改变输入是否合法;公式缓存满后清空再写入。缓存不会免除每次求值的计算预算。
81
+
82
+ ## 验收
83
+
84
+ 回归用例覆盖 Unicode 长度、UTF-16 定位、CRLF、预算临界值、双语诊断字段一致性,以及警告占满时的错误保留。编辑器和 CLI 的集成检查使用真实诊断对象;业务逻辑不依赖完整消息文本。版本兼容说明见[版本与兼容性](compatibility-ch.md),命令行使用见[作者工具](author-tools-ch.md)。
@@ -0,0 +1,84 @@
1
+ # Diagnostics and counting rules
2
+
3
+ [中文](diagnostics-counting-ch.md)
4
+
5
+ This page defines the 0.4.x diagnostics contract, text-length units and resource-budget scopes.
6
+
7
+ ## Diagnostics contract
8
+
9
+ The machine fields of `Diagnostic` are `code`, `severity`, `range`, `line` and `column`. Its `message` contains default English display text. Hosts call `formatLocalDiagnostic(diagnostic, 'zh')` or `'en'` for localized messages; the editor and CLI use the same function. Optional template identifiers and parameters support localization. Unknown host diagnostics use their original `message`, subject to the display-length limit.
10
+
11
+ ```ts
12
+ import { compileLocal, formatLocalDiagnostic } from 'reactive-md';
13
+
14
+ const result = compileLocal(source);
15
+ for (const diagnostic of result.diagnostics) {
16
+ console.log(diagnostic.code, formatLocalDiagnostic(diagnostic, 'zh'));
17
+ }
18
+ ```
19
+
20
+ Changing language preserves codes, severity and source locations. Existing diagnostic codes keep their meaning within one `0.x` minor series. New codes may be added; an existing code must not be reused for a different error category. Removing, renaming or changing a code's meaning requires a new minor version and migration notes. Display wording may improve; machine consumers should use codes and structured fields.
21
+
22
+ Ranges are zero-based UTF-16 indexes with half-open intervals `[start, end)`. Lines and columns are one-based; columns count UTF-16 code units. LF advances the line, and CRLF occupies two source code units. Positions always refer to the original, unnormalized source.
23
+
24
+ When the diagnostic limit is reached, new warnings may be omitted; a new error takes priority over an existing warning. Compile errors make `ok` false. Rejected runtime writes preserve committed state and revision.
25
+
26
+ ## Text length
27
+
28
+ | Purpose | Unit |
29
+ | --- | --- |
30
+ | Source offsets, diagnostic columns, source and string resource budgets | UTF-16 code units, equivalent to JavaScript `string.length` |
31
+ | String `len()`, text-control `min-length` / `max-length` | Unicode code points |
32
+ | Array `len()` and array limits | Elements |
33
+
34
+ `😀` occupies two UTF-16 code units and one code point. An `e` followed by a combining accent has two code points. `👩‍💻` occupies five UTF-16 code units and three code points. Length validation does not combine grapheme clusters or normalize Unicode. An unpaired UTF-16 surrogate counts as one string-iteration item.
35
+
36
+ Compiler initial-value checks, runtime writes and the reference renderer share these rules. Independent string resource budgets are checked in UTF-16 first; the email limit of 254 also uses UTF-16. `countLocalCodePoints(value)` uses the same unit as text constraints.
37
+
38
+ The document budget counts original source. Attribute values are counted after supported HTML entities are decoded. Concatenation and interpolation also check output length. For example, `&amp;` in an attribute occupies five source code units and one decoded code unit. Line endings inside a quoted attribute still count toward its value length.
39
+
40
+ ## Resource budgets
41
+
42
+ Length limits include the boundary value; larger inputs are rejected. Independent compilation or evaluation starts a fresh corresponding budget. Cache hits still require the operation's input and state validation.
43
+
44
+ | Resource | Limit and unit | Scope |
45
+ | --- | --- | --- |
46
+ | Document source | 1,000,000 UTF-16 code units | Original source for one compilation |
47
+ | Syntax nodes | Default 10,000 nodes | All constructions during one parse, including intermediate nodes; configurable per call |
48
+ | Component nesting | 100 levels | Current component parse call chain |
49
+ | Tag, attribute and binding names | 128 UTF-16 code units | Each name |
50
+ | Theme name | 64 UTF-16 code units | Each theme name |
51
+ | String values, attributes and templates | 100,000 UTF-16 code units | Each value or template, including concatenated output |
52
+ | Array | 10,000 items | Each array |
53
+ | Sum of array member strings | 100,000 UTF-16 code units | All string members of one array |
54
+ | Email | 254 UTF-16 code units | Each nonempty email value |
55
+ | Compile diagnostics | 100 entries | One compilation, shared by parser and compiler |
56
+ | Diagnostic message | 2,000 UTF-16 code units | Each displayed message; excess text is truncated |
57
+ | Diagnostic template parameters | At most 16; string values at most 256 UTF-16 units each, total value text at most 2,000 | Serializable parameters of one diagnostic; excess values are truncated or omitted |
58
+ | Expression source | 4,000 UTF-16 code units | Each expression |
59
+ | Expression AST | 2,000 nodes | Cumulative constructions for one expression |
60
+ | Expression parse / AST depth | 100 / 200 levels | Parser call depth / final AST depth |
61
+ | Expression evaluation | 10,000 node visits, depth 250 | Each evaluation; short-circuited branches count only when visited |
62
+ | LaTeX source | 50,000 UTF-16 code units | Each formula |
63
+ | LaTeX tokens / AST | 20,000 tokens / 5,000 nodes | Parsing one formula; tokens include EOF |
64
+ | LaTeX parse / evaluation depth | 120 / 1,000 levels | Corresponding call chains |
65
+ | Standalone LaTeX evaluation | Default 20,000 node visits | Each `evaluate`; an explicit shared budget accumulates across calls |
66
+ | Plot curves | 16 curves | Each `<plot>` |
67
+ | Samples per curve | 2 to 2,000 points | Each sampling request, including endpoints |
68
+ | Document sample points | 20,000 points | Sum of curve counts times requested samples, including hidden regions |
69
+ | Validation rules | 100 rules per document | Includes rules in hidden regions |
70
+ | Generated rows per `<data-table>` | 1,000 maximum, 100 default | Declared `max-rows` for one table |
71
+ | Columns per `<data-table>` | 20 columns | One table |
72
+ | Document generated rows | 2,000 rows | Sum of declared `max-rows` over every `data-table`, including hidden tables |
73
+ | Document generated cells | 10,000 cells | Sum of declared rows times columns over every `data-table` |
74
+ | Generated table text | 100,000 UTF-16 code units | Header, cell, empty/error text and encoded row keys for one table |
75
+ | Per-curve computation | `max(1,000,000, samples × 1024)` node visits | One `samplePlot`, including extra discontinuity checks |
76
+ | Document plot computation | 2,000,000 node visits | All plot sampling in one runtime revision; a new revision resets it |
77
+
78
+ Evaluation steps count AST node visits, not milliseconds. Standalone `samplePlot` callers pass a shared budget to accumulate across curves. The reference renderer maintains a document budget and sampling cache.
79
+
80
+ Expression compilation caches hold at most 500 entries; formula compilation caches hold 512; each runtime's expression cache holds 200. These entry limits manage memory without changing input validity. A full formula cache is cleared before the next insertion. Caching never bypasses evaluation budgets.
81
+
82
+ ## Validation
83
+
84
+ Regression cases cover Unicode lengths, UTF-16 locations, CRLF, budget boundaries, equivalent machine fields across languages, and error retention after warnings fill the diagnostic limit. Editor and CLI checks use real diagnostic objects. Business logic does not depend on complete message text. See [Versions and compatibility](compatibility-en.md) and [Author tools](author-tools-en.md).