@elastic/isomer-sdk 0.1.0 → 0.3.0

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 (288) hide show
  1. package/NOTICE.txt +0 -286
  2. package/README.md +13 -2
  3. package/THIRD_PARTY_LICENSES.md +1 -885
  4. package/dist/author/authored_fields.d.ts +93 -18
  5. package/dist/author/authored_fields.d.ts.map +1 -1
  6. package/dist/author/authored_fields.js +63 -43
  7. package/dist/author/authored_fields.js.map +1 -1
  8. package/dist/author/authoring_input.d.ts +7 -0
  9. package/dist/author/authoring_input.d.ts.map +1 -0
  10. package/dist/author/authoring_input.js +66 -0
  11. package/dist/author/authoring_input.js.map +1 -0
  12. package/dist/author/authoring_model.d.ts +33 -0
  13. package/dist/author/authoring_model.d.ts.map +1 -0
  14. package/dist/author/authoring_model.js +142 -0
  15. package/dist/author/authoring_model.js.map +1 -0
  16. package/dist/author/declarations.d.ts +13 -0
  17. package/dist/author/declarations.d.ts.map +1 -0
  18. package/dist/author/declarations.js +288 -0
  19. package/dist/author/declarations.js.map +1 -0
  20. package/dist/author/index.d.ts +4 -1
  21. package/dist/author/index.d.ts.map +1 -1
  22. package/dist/author/index.js +4 -1
  23. package/dist/author/index.js.map +1 -1
  24. package/dist/author/jsx_shim.d.ts +50 -30
  25. package/dist/author/jsx_shim.d.ts.map +1 -1
  26. package/dist/author/jsx_shim.js +146 -138
  27. package/dist/author/jsx_shim.js.map +1 -1
  28. package/dist/author/print_jsx.d.ts +19 -0
  29. package/dist/author/print_jsx.d.ts.map +1 -0
  30. package/dist/author/print_jsx.js +372 -0
  31. package/dist/author/print_jsx.js.map +1 -0
  32. package/dist/author/prompt.d.ts +2 -2
  33. package/dist/author/prompt.d.ts.map +1 -1
  34. package/dist/author/prompt.js +7 -2
  35. package/dist/author/prompt.js.map +1 -1
  36. package/dist/author/schema_to_typescript.d.ts +37 -0
  37. package/dist/author/schema_to_typescript.d.ts.map +1 -0
  38. package/dist/author/schema_to_typescript.js +289 -0
  39. package/dist/author/schema_to_typescript.js.map +1 -0
  40. package/dist/cjs/author/authored_fields.js +68 -47
  41. package/dist/cjs/author/authored_fields.js.map +1 -1
  42. package/dist/cjs/author/authoring_input.js +70 -0
  43. package/dist/cjs/author/authoring_input.js.map +1 -0
  44. package/dist/cjs/author/authoring_model.js +149 -0
  45. package/dist/cjs/author/authoring_model.js.map +1 -0
  46. package/dist/cjs/author/declarations.js +292 -0
  47. package/dist/cjs/author/declarations.js.map +1 -0
  48. package/dist/cjs/author/index.js +10 -1
  49. package/dist/cjs/author/index.js.map +1 -1
  50. package/dist/cjs/author/jsx_shim.js +148 -140
  51. package/dist/cjs/author/jsx_shim.js.map +1 -1
  52. package/dist/cjs/author/print_jsx.js +378 -0
  53. package/dist/cjs/author/print_jsx.js.map +1 -0
  54. package/dist/cjs/author/prompt.js +7 -2
  55. package/dist/cjs/author/prompt.js.map +1 -1
  56. package/dist/cjs/author/schema_to_typescript.js +298 -0
  57. package/dist/cjs/author/schema_to_typescript.js.map +1 -0
  58. package/dist/cjs/composition/body_node_base.js +11 -4
  59. package/dist/cjs/composition/body_node_base.js.map +1 -1
  60. package/dist/cjs/composition/error.js +2 -0
  61. package/dist/cjs/composition/error.js.map +1 -1
  62. package/dist/cjs/composition/index.js +2 -1
  63. package/dist/cjs/composition/index.js.map +1 -1
  64. package/dist/cjs/composition/structured_value.js.map +1 -1
  65. package/dist/cjs/define/frame.js +2 -3
  66. package/dist/cjs/define/frame.js.map +1 -1
  67. package/dist/cjs/define/index.js +7 -1
  68. package/dist/cjs/define/index.js.map +1 -1
  69. package/dist/cjs/define/primitive_example.js +26 -0
  70. package/dist/cjs/define/primitive_example.js.map +1 -0
  71. package/dist/cjs/define/primitive_icon.js +17 -0
  72. package/dist/cjs/define/primitive_icon.js.map +1 -0
  73. package/dist/cjs/define/primitive_module.js +24 -7
  74. package/dist/cjs/define/primitive_module.js.map +1 -1
  75. package/dist/cjs/define/slack_assets.js.map +1 -1
  76. package/dist/cjs/entries/index.js +8 -2
  77. package/dist/cjs/entries/index.js.map +1 -1
  78. package/dist/cjs/entries/markdown.js +2 -1
  79. package/dist/cjs/entries/markdown.js.map +1 -1
  80. package/dist/cjs/entries/slack.js +1 -2
  81. package/dist/cjs/entries/slack.js.map +1 -1
  82. package/dist/cjs/pack/capabilities.js +17 -11
  83. package/dist/cjs/pack/capabilities.js.map +1 -1
  84. package/dist/cjs/pack/compose.js +4 -1
  85. package/dist/cjs/pack/compose.js.map +1 -1
  86. package/dist/cjs/pack/index.js +2 -1
  87. package/dist/cjs/pack/index.js.map +1 -1
  88. package/dist/cjs/pack/primitive_pack.js +27 -5
  89. package/dist/cjs/pack/primitive_pack.js.map +1 -1
  90. package/dist/cjs/render/anchors.js +1 -1
  91. package/dist/cjs/render/anchors.js.map +1 -1
  92. package/dist/cjs/render/format_number.js +2 -1
  93. package/dist/cjs/render/format_number.js.map +1 -1
  94. package/dist/cjs/render/html/envelope.js +12 -6
  95. package/dist/cjs/render/html/envelope.js.map +1 -1
  96. package/dist/cjs/render/layout_check.js.map +1 -1
  97. package/dist/cjs/render/markdown/builder.js +18 -8
  98. package/dist/cjs/render/markdown/builder.js.map +1 -1
  99. package/dist/cjs/render/markdown/format.js +70 -30
  100. package/dist/cjs/render/markdown/format.js.map +1 -1
  101. package/dist/cjs/render/markdown/host_tags.js +67 -0
  102. package/dist/cjs/render/markdown/host_tags.js.map +1 -0
  103. package/dist/cjs/render/markdown/index.js +3 -1
  104. package/dist/cjs/render/markdown/index.js.map +1 -1
  105. package/dist/cjs/render/markdown/split.js +325 -0
  106. package/dist/cjs/render/markdown/split.js.map +1 -0
  107. package/dist/cjs/render/primitive_dispatch.js +11 -25
  108. package/dist/cjs/render/primitive_dispatch.js.map +1 -1
  109. package/dist/cjs/render/react/content.js +3 -1
  110. package/dist/cjs/render/react/content.js.map +1 -1
  111. package/dist/cjs/render/slack/format.js +1 -601
  112. package/dist/cjs/render/slack/format.js.map +1 -1
  113. package/dist/cjs/render/slack/index.js +1 -2
  114. package/dist/cjs/render/slack/index.js.map +1 -1
  115. package/dist/cjs/render/slack/markdown_content.js +172 -115
  116. package/dist/cjs/render/slack/markdown_content.js.map +1 -1
  117. package/dist/cjs/testing/conformance.js +40 -24
  118. package/dist/cjs/testing/conformance.js.map +1 -1
  119. package/dist/cjs/testing/icon.js +248 -0
  120. package/dist/cjs/testing/icon.js.map +1 -0
  121. package/dist/cjs/testing/index.js +3 -1
  122. package/dist/cjs/testing/index.js.map +1 -1
  123. package/dist/cjs/testing/registration.js +5 -3
  124. package/dist/cjs/testing/registration.js.map +1 -1
  125. package/dist/cjs/validate/authoring_schema.js +17 -1
  126. package/dist/cjs/validate/authoring_schema.js.map +1 -1
  127. package/dist/cjs/validate/index.js +2 -1
  128. package/dist/cjs/validate/index.js.map +1 -1
  129. package/dist/cjs/validate/json_schema.js +10 -3
  130. package/dist/cjs/validate/json_schema.js.map +1 -1
  131. package/dist/cjs/validate/url.js +2 -1
  132. package/dist/cjs/validate/url.js.map +1 -1
  133. package/dist/cjs/validate/validation.js +2 -45
  134. package/dist/cjs/validate/validation.js.map +1 -1
  135. package/dist/composition/body_node_base.d.ts +7 -6
  136. package/dist/composition/body_node_base.d.ts.map +1 -1
  137. package/dist/composition/body_node_base.js +10 -3
  138. package/dist/composition/body_node_base.js.map +1 -1
  139. package/dist/composition/error.d.ts +2 -0
  140. package/dist/composition/error.d.ts.map +1 -1
  141. package/dist/composition/error.js +2 -0
  142. package/dist/composition/error.js.map +1 -1
  143. package/dist/composition/index.d.ts +1 -1
  144. package/dist/composition/index.d.ts.map +1 -1
  145. package/dist/composition/index.js +1 -1
  146. package/dist/composition/index.js.map +1 -1
  147. package/dist/composition/structured_value.d.ts +3 -3
  148. package/dist/composition/structured_value.d.ts.map +1 -1
  149. package/dist/composition/structured_value.js.map +1 -1
  150. package/dist/define/frame.d.ts +9 -20
  151. package/dist/define/frame.d.ts.map +1 -1
  152. package/dist/define/frame.js +2 -3
  153. package/dist/define/frame.js.map +1 -1
  154. package/dist/define/index.d.ts +3 -1
  155. package/dist/define/index.d.ts.map +1 -1
  156. package/dist/define/index.js +3 -1
  157. package/dist/define/index.js.map +1 -1
  158. package/dist/define/primitive_example.d.ts +30 -0
  159. package/dist/define/primitive_example.d.ts.map +1 -0
  160. package/dist/define/primitive_example.js +21 -0
  161. package/dist/define/primitive_example.js.map +1 -0
  162. package/dist/define/primitive_icon.d.ts +11 -0
  163. package/dist/define/primitive_icon.d.ts.map +1 -0
  164. package/dist/define/primitive_icon.js +14 -0
  165. package/dist/define/primitive_icon.js.map +1 -0
  166. package/dist/define/primitive_module.d.ts +45 -24
  167. package/dist/define/primitive_module.d.ts.map +1 -1
  168. package/dist/define/primitive_module.js +24 -7
  169. package/dist/define/primitive_module.js.map +1 -1
  170. package/dist/define/slack_assets.d.ts +1 -1
  171. package/dist/define/slack_assets.d.ts.map +1 -1
  172. package/dist/define/slack_assets.js.map +1 -1
  173. package/dist/entries/index.d.ts +3 -3
  174. package/dist/entries/index.d.ts.map +1 -1
  175. package/dist/entries/index.js +3 -3
  176. package/dist/entries/index.js.map +1 -1
  177. package/dist/entries/markdown.d.ts +1 -1
  178. package/dist/entries/markdown.d.ts.map +1 -1
  179. package/dist/entries/markdown.js +1 -1
  180. package/dist/entries/markdown.js.map +1 -1
  181. package/dist/entries/slack.d.ts +1 -1
  182. package/dist/entries/slack.d.ts.map +1 -1
  183. package/dist/entries/slack.js +1 -1
  184. package/dist/entries/slack.js.map +1 -1
  185. package/dist/pack/capabilities.d.ts +24 -10
  186. package/dist/pack/capabilities.d.ts.map +1 -1
  187. package/dist/pack/capabilities.js +17 -11
  188. package/dist/pack/capabilities.js.map +1 -1
  189. package/dist/pack/compose.d.ts +4 -1
  190. package/dist/pack/compose.d.ts.map +1 -1
  191. package/dist/pack/compose.js +4 -1
  192. package/dist/pack/compose.js.map +1 -1
  193. package/dist/pack/index.d.ts +2 -2
  194. package/dist/pack/index.d.ts.map +1 -1
  195. package/dist/pack/index.js +2 -2
  196. package/dist/pack/index.js.map +1 -1
  197. package/dist/pack/primitive_pack.d.ts +14 -3
  198. package/dist/pack/primitive_pack.d.ts.map +1 -1
  199. package/dist/pack/primitive_pack.js +25 -4
  200. package/dist/pack/primitive_pack.js.map +1 -1
  201. package/dist/render/anchors.d.ts +2 -2
  202. package/dist/render/anchors.d.ts.map +1 -1
  203. package/dist/render/anchors.js +1 -1
  204. package/dist/render/anchors.js.map +1 -1
  205. package/dist/render/format_number.d.ts.map +1 -1
  206. package/dist/render/format_number.js +2 -1
  207. package/dist/render/format_number.js.map +1 -1
  208. package/dist/render/html/envelope.d.ts +3 -3
  209. package/dist/render/html/envelope.js +12 -6
  210. package/dist/render/html/envelope.js.map +1 -1
  211. package/dist/render/layout_check.d.ts +1 -1
  212. package/dist/render/layout_check.d.ts.map +1 -1
  213. package/dist/render/layout_check.js.map +1 -1
  214. package/dist/render/markdown/builder.d.ts +5 -4
  215. package/dist/render/markdown/builder.d.ts.map +1 -1
  216. package/dist/render/markdown/builder.js +16 -7
  217. package/dist/render/markdown/builder.js.map +1 -1
  218. package/dist/render/markdown/format.d.ts +9 -0
  219. package/dist/render/markdown/format.d.ts.map +1 -1
  220. package/dist/render/markdown/format.js +67 -31
  221. package/dist/render/markdown/format.js.map +1 -1
  222. package/dist/render/markdown/host_tags.d.ts +14 -0
  223. package/dist/render/markdown/host_tags.d.ts.map +1 -0
  224. package/dist/render/markdown/host_tags.js +63 -0
  225. package/dist/render/markdown/host_tags.js.map +1 -0
  226. package/dist/render/markdown/index.d.ts +1 -0
  227. package/dist/render/markdown/index.d.ts.map +1 -1
  228. package/dist/render/markdown/index.js +1 -0
  229. package/dist/render/markdown/index.js.map +1 -1
  230. package/dist/render/markdown/split.d.ts +32 -0
  231. package/dist/render/markdown/split.d.ts.map +1 -0
  232. package/dist/render/markdown/split.js +321 -0
  233. package/dist/render/markdown/split.js.map +1 -0
  234. package/dist/render/primitive_dispatch.d.ts +6 -6
  235. package/dist/render/primitive_dispatch.d.ts.map +1 -1
  236. package/dist/render/primitive_dispatch.js +12 -26
  237. package/dist/render/primitive_dispatch.js.map +1 -1
  238. package/dist/render/react/content.d.ts +1 -1
  239. package/dist/render/react/content.d.ts.map +1 -1
  240. package/dist/render/react/content.js +3 -1
  241. package/dist/render/react/content.js.map +1 -1
  242. package/dist/render/slack/format.d.ts +0 -25
  243. package/dist/render/slack/format.d.ts.map +1 -1
  244. package/dist/render/slack/format.js +1 -599
  245. package/dist/render/slack/format.js.map +1 -1
  246. package/dist/render/slack/index.d.ts +1 -1
  247. package/dist/render/slack/index.d.ts.map +1 -1
  248. package/dist/render/slack/index.js +1 -1
  249. package/dist/render/slack/index.js.map +1 -1
  250. package/dist/render/slack/markdown_content.d.ts +10 -4
  251. package/dist/render/slack/markdown_content.d.ts.map +1 -1
  252. package/dist/render/slack/markdown_content.js +169 -113
  253. package/dist/render/slack/markdown_content.js.map +1 -1
  254. package/dist/testing/conformance.d.ts +19 -14
  255. package/dist/testing/conformance.d.ts.map +1 -1
  256. package/dist/testing/conformance.js +40 -24
  257. package/dist/testing/conformance.js.map +1 -1
  258. package/dist/testing/icon.d.ts +11 -0
  259. package/dist/testing/icon.d.ts.map +1 -0
  260. package/dist/testing/icon.js +244 -0
  261. package/dist/testing/icon.js.map +1 -0
  262. package/dist/testing/index.d.ts +2 -1
  263. package/dist/testing/index.d.ts.map +1 -1
  264. package/dist/testing/index.js +1 -0
  265. package/dist/testing/index.js.map +1 -1
  266. package/dist/testing/registration.d.ts +1 -1
  267. package/dist/testing/registration.d.ts.map +1 -1
  268. package/dist/testing/registration.js +6 -4
  269. package/dist/testing/registration.js.map +1 -1
  270. package/dist/validate/authoring_schema.d.ts +6 -0
  271. package/dist/validate/authoring_schema.d.ts.map +1 -1
  272. package/dist/validate/authoring_schema.js +15 -0
  273. package/dist/validate/authoring_schema.js.map +1 -1
  274. package/dist/validate/index.d.ts +1 -1
  275. package/dist/validate/index.d.ts.map +1 -1
  276. package/dist/validate/index.js +1 -1
  277. package/dist/validate/index.js.map +1 -1
  278. package/dist/validate/json_schema.d.ts.map +1 -1
  279. package/dist/validate/json_schema.js +10 -3
  280. package/dist/validate/json_schema.js.map +1 -1
  281. package/dist/validate/url.d.ts.map +1 -1
  282. package/dist/validate/url.js +2 -1
  283. package/dist/validate/url.js.map +1 -1
  284. package/dist/validate/validation.d.ts +1 -11
  285. package/dist/validate/validation.d.ts.map +1 -1
  286. package/dist/validate/validation.js +3 -46
  287. package/dist/validate/validation.js.map +1 -1
  288. package/package.json +3 -2
@@ -6,16 +6,18 @@
6
6
  * 2.0.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.definePrimitivePack = void 0;
9
+ exports.iconsByType = exports.definePrimitivePack = exports.UNCATEGORIZED_GROUP_TITLE = void 0;
10
10
  // A primitive pack as a value: a vocabulary, and the optional surfaces every
11
11
  // primitive in it implements. Additive: a runtime composes any number of packs,
12
12
  // and nothing about a pack decides how a composition is framed.
13
13
  const error_1 = require("../composition/error");
14
+ /** The index heading for primitives in no group. A pack cannot declare a group with this title. */
15
+ exports.UNCATEGORIZED_GROUP_TITLE = 'Uncategorized';
14
16
  /**
15
17
  * Builds a {@link PrimitivePack}.
16
18
  *
17
19
  * `TTheme` is the palette a frame must supply for this pack's nodes to be drawn
18
- * on the `svg` surface: `definePrimitivePack<CoreTokens>(input)`. Omitted, it is
20
+ * on the `snapshot` surface: `definePrimitivePack<CoreTokens>(input)`. Omitted, it is
19
21
  * `unknown`, which requires nothing.
20
22
  */
21
23
  const definePrimitivePack = (input) => {
@@ -25,7 +27,7 @@ const definePrimitivePack = (input) => {
25
27
  assertUniquePrimitiveTypes(input.id, input.primitives);
26
28
  assertUniqueEnhancementIds(input.id, input.enhancements ?? []);
27
29
  const types = new Set(input.primitives.map((definition) => definition.type));
28
- assertGroupedOnce(input.id, input.authoring?.groups ?? [], types);
30
+ assertValidGroups(input.id, input.authoring?.groups ?? [], types);
29
31
  for (const type of input.slackAssetTypes ?? []) {
30
32
  if (!types.has(type)) {
31
33
  throw new error_1.IsomerError('UNKNOWN_PRIMITIVE_TYPE', `primitive pack "${input.id}": slackAssetTypes names primitive type "${type}", which the pack does not register`);
@@ -37,6 +39,7 @@ const definePrimitivePack = (input) => {
37
39
  surfaces: input.surfaces ?? [],
38
40
  primitives: input.primitives,
39
41
  types,
42
+ icons: (0, exports.iconsByType)(input.primitives),
40
43
  enhancements: input.enhancements ?? [],
41
44
  slackAssetTypes: new Set(input.slackAssetTypes ?? []),
42
45
  ...(input.styleAdapter !== undefined
@@ -47,6 +50,17 @@ const definePrimitivePack = (input) => {
47
50
  };
48
51
  };
49
52
  exports.definePrimitivePack = definePrimitivePack;
53
+ /** Each definition's `icon` by type, null-prototype so a type such as `__proto__` is an ordinary key. */
54
+ const iconsByType = (primitives) => {
55
+ const icons = Object.create(null);
56
+ for (const { type, icon } of primitives) {
57
+ if (icon !== undefined) {
58
+ icons[type] = icon;
59
+ }
60
+ }
61
+ return Object.freeze(icons);
62
+ };
63
+ exports.iconsByType = iconsByType;
50
64
  /** Throws if `primitives` repeats a type. */
51
65
  const assertUniquePrimitiveTypes = (id, primitives) => {
52
66
  const seen = new Set();
@@ -57,10 +71,18 @@ const assertUniquePrimitiveTypes = (id, primitives) => {
57
71
  seen.add(type);
58
72
  }
59
73
  };
60
- /** Throws if a group names a type outside `types`, or two groups share a type. */
61
- const assertGroupedOnce = (id, groups, types) => {
74
+ /** Throws if a group repeats or reserves a title, names a type outside `types`, or shares a type with another. */
75
+ const assertValidGroups = (id, groups, types) => {
76
+ const titles = new Set();
62
77
  const grouped = new Set();
63
78
  for (const { title, types: members } of groups) {
79
+ if (title === exports.UNCATEGORIZED_GROUP_TITLE) {
80
+ throw new error_1.IsomerError('INVALID_PACK_GROUPS', `primitive pack "${id}": group title "${title}" is reserved for primitives in no group`);
81
+ }
82
+ if (titles.has(title)) {
83
+ throw new error_1.IsomerError('INVALID_PACK_GROUPS', `primitive pack "${id}": group title "${title}" is used twice`);
84
+ }
85
+ titles.add(title);
64
86
  for (const type of members) {
65
87
  if (!types.has(type)) {
66
88
  throw new error_1.IsomerError('UNKNOWN_PRIMITIVE_TYPE', `primitive pack "${id}": group "${title}" names primitive type "${type}", which the pack does not register`);
@@ -1 +1 @@
1
- {"version":3,"file":"primitive_pack.js","sourceRoot":"","sources":["../../../src/pack/primitive_pack.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,6EAA6E;AAC7E,gFAAgF;AAChF,gEAAgE;AAEhE,gDAAmD;AA+JnD;;;;;;GAMG;AACI,MAAM,mBAAmB,GAAG,CACjC,KAAyB,EACF,EAAE;IACzB,IAAI,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,mBAAW,CACnB,YAAY,EACZ,mBAAmB,KAAK,CAAC,EAAE,uCAAuC,CACnE,CAAC;IACJ,CAAC;IACD,0BAA0B,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACvD,0BAA0B,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7E,iBAAiB,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,SAAS,EAAE,MAAM,IAAI,EAAE,EAAE,KAAK,CAAC,CAAC;IAClE,KAAK,MAAM,IAAI,IAAI,KAAK,CAAC,eAAe,IAAI,EAAE,EAAE,CAAC;QAC/C,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;YACrB,MAAM,IAAI,mBAAW,CACnB,wBAAwB,EACxB,mBAAmB,KAAK,CAAC,EAAE,4CAA4C,IAAI,qCAAqC,CACjH,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elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\n// A primitive pack as a value: a vocabulary, and the optional surfaces every\n// primitive in it implements. Additive: a runtime composes any number of packs,\n// and nothing about a pack decides how a composition is framed.\n\nimport { IsomerError } from '../composition/error';\nimport type {\n AnyPrimitiveDefinition,\n OptionalSurface,\n StyleHandle,\n} from '../define/primitive_module';\n\nimport type { EnhancementDefinition } from './enhancements';\n\n/**\n * The authoring-schema material a pack contributes for its own primitives.\n *\n * A subset of `AuthoringJsonSchemaOptions`: `$id`, `title`, `description`, and\n * `composition` describe the whole authoring schema a runtime builds, which is\n * a host decision, not a pack one. `pack/` does not import `validate/` for\n * this, so the shape is declared here rather than reused by reference.\n */\nexport interface PackAuthoringOptions {\n /** `$def` id to `description`, for this pack's own primitives. */\n describe?: Readonly<Record<string, string>>;\n /** `$defId.property` paths to drop, from this pack's own primitives. */\n omitProperties?: readonly string[];\n /** Headings an index catalog sorts this pack's primitives under, in order. */\n groups?: readonly PrimitiveGroup[];\n}\n\n/** A titled set of primitive types, listed together in an index catalog. */\nexport interface PrimitiveGroup {\n title: string;\n types: readonly string[];\n}\n\n/**\n * The HTML style-adapter hooks a pack may declare. Typed loosely here so `pack/` does not import `render/`.\n */\nexport type PackStyleAdapter = {\n /** See {@link PrimitivePackInput.styleCollector}. */\n styleCollector?: string;\n /** The hooks of `HTMLStyleAdapter` from `./html`, erased: a fresh collector per render, the context renderers receive, and the stylesheet the collector produced. */\n createCollector: (...args: never[]) => object;\n createRenderContext: (...args: never[]) => unknown;\n renderStyles: (...args: never[]) => string;\n /**\n * Whether `handle` belongs to this adapter's stylesheet. Required for a runtime to combine several packs' CSS: without it their handles cannot be routed and the host must pick one adapter.\n */\n ownsHandle?: (handle: StyleHandle) => boolean;\n};\n\n/** What a pack author passes to {@link definePrimitivePack}. */\nexport interface PrimitivePackInput {\n /** Stable identifier, used in capability reports and error messages. */\n id: string;\n /**\n * The optional surfaces this pack's primitives implement.\n *\n * Only `slack`, and it stays optional per primitive: the dispatcher converts\n * the mandatory markdown to Block Kit, so declaring it reports an intent\n * rather than imposing a requirement. Omit it entirely for a pack that\n * renders Slack through that fallback.\n */\n surfaces?: readonly OptionalSurface[];\n /** This pack's vocabulary. Node types must be unique within it, or construction throws. */\n primitives: readonly AnyPrimitiveDefinition[];\n /**\n * Progressive enhancements this pack's primitives can apply, by id.\n *\n * Declared by the pack because an enhancement is a fact about its\n * vocabulary — a sortable table, a copyable code block — and a host\n * composing packs it did not write cannot be expected to know the ids.\n * The runtime flattens these across packs; duplicate ids are rejected.\n */\n enhancements?: readonly EnhancementDefinition[];\n /**\n * Types that render as a self-contained picture rather than as text.\n *\n * A channel that cannot draw them inline uploads an image instead: the Slack\n * dispatcher swaps such a node for an `image` block and an upload request, so\n * a chart arrives as a PNG rather than as a markdown approximation of one.\n *\n * Declared by the pack because it is a fact about the vocabulary, and a host\n * composing packs it did not write cannot be expected to know it.\n */\n slackAssetTypes?: readonly string[];\n /**\n * Default HTML style adapter for this pack. A runtime that omits\n * `styleAdapter` runs the packs' own adapters, combined when more than one\n * pack declares one and each answers `ownsHandle`. Pass `styleAdapter` on\n * the runtime to replace them all.\n */\n styleAdapter?: PackStyleAdapter;\n /**\n * Names the collector shape this pack's `collectStyles` hooks mutate, so a\n * runtime can reject a pack paired with an adapter of a different tag.\n * Defaults to `styleAdapter.styleCollector`; a pack with neither opts out of\n * the check.\n */\n styleCollector?: string;\n /**\n * This pack's own contribution to the runtime's authoring JSON Schema.\n *\n * Merged across every composed pack, so a host does not hand-merge each\n * pack's `describe`/`omitProperties` into one options object itself. The\n * runtime-level `authoring` option is merged in last and wins on conflict.\n */\n authoring?: PackAuthoringOptions;\n}\n\n/**\n * A pack as the runtime sees it.\n *\n * `TTheme` is the palette this pack's `react` renderers read as `env.theme`\n * when drawn through the `svg` surface — a *lower bound* on whatever theme\n * the runtime holding it supplies. It is carried by\n * {@link PrimitivePack.__theme} rather than by any real field, because\n * `primitives` is erased to `AnyPrimitiveDefinition[]` and a heterogeneous\n * inventory has no single node type to be generic over.\n *\n * The bound is declared, not derived: nothing checks it against what the\n * renderers actually read. State it at the definition as\n * `definePrimitivePack<T>(input)`.\n * Bare `PrimitivePack` requires nothing and fits any runtime; a slot that must\n * hold packs of every palette is typed {@link AnyPrimitivePack}.\n */\nexport interface PrimitivePack<TTheme = unknown> {\n /** Unique among the packs a runtime composes, and used in error messages. */\n readonly id: string;\n /** See {@link PrimitivePackInput.surfaces}. */\n readonly surfaces: readonly OptionalSurface[];\n /** See {@link PrimitivePackInput.primitives}. */\n readonly primitives: readonly AnyPrimitiveDefinition[];\n /** Node types this pack owns, for duplicate detection across packs. */\n readonly types: ReadonlySet<string>;\n /** See {@link PrimitivePackInput.enhancements}. */\n readonly enhancements: readonly EnhancementDefinition[];\n /** See {@link PrimitivePackInput.slackAssetTypes}. */\n readonly slackAssetTypes: ReadonlySet<string>;\n /** See {@link PrimitivePackInput.styleAdapter}. */\n readonly styleAdapter?: PackStyleAdapter;\n /** See {@link PrimitivePackInput.styleCollector}. */\n readonly styleCollector?: string;\n /** See {@link PrimitivePackInput.authoring}. */\n readonly authoring?: PackAuthoringOptions;\n /**\n * Phantom: never present at runtime, never read.\n *\n * A property rather than a method so `strictFunctionTypes` checks it\n * contravariantly. A method signature is bivariant, which would let a pack\n * needing richer tokens sit in a slot supplying fewer and then read a field\n * nothing supplies — the exact failure this marker exists to prevent.\n */\n readonly __theme?: (theme: TTheme) => void;\n}\n\n/**\n * A pack of any palette, for storage positions: `never` is assignable to every\n * requirement, so a slot typed this way holds every pack.\n */\nexport type AnyPrimitivePack = PrimitivePack<never>;\n\n/**\n * Builds a {@link PrimitivePack}.\n *\n * `TTheme` is the palette a frame must supply for this pack's nodes to be drawn\n * on the `svg` surface: `definePrimitivePack<CoreTokens>(input)`. Omitted, it is\n * `unknown`, which requires nothing.\n */\nexport const definePrimitivePack = <TTheme = unknown>(\n input: PrimitivePackInput\n): PrimitivePack<TTheme> => {\n if (input.primitives.length === 0) {\n throw new IsomerError(\n 'EMPTY_PACK',\n `primitive pack \"${input.id}\": at least one primitive is required`\n );\n }\n assertUniquePrimitiveTypes(input.id, input.primitives);\n assertUniqueEnhancementIds(input.id, input.enhancements ?? []);\n const types = new Set(input.primitives.map((definition) => definition.type));\n assertGroupedOnce(input.id, input.authoring?.groups ?? [], types);\n for (const type of input.slackAssetTypes ?? []) {\n if (!types.has(type)) {\n throw new IsomerError(\n 'UNKNOWN_PRIMITIVE_TYPE',\n `primitive pack \"${input.id}\": slackAssetTypes names primitive type \"${type}\", which the pack does not register`\n );\n }\n }\n const styleCollector =\n input.styleCollector ?? input.styleAdapter?.styleCollector;\n\n return {\n id: input.id,\n surfaces: input.surfaces ?? [],\n primitives: input.primitives,\n types,\n enhancements: input.enhancements ?? [],\n slackAssetTypes: new Set(input.slackAssetTypes ?? []),\n ...(input.styleAdapter !== undefined\n ? { styleAdapter: input.styleAdapter }\n : {}),\n ...(styleCollector !== undefined ? { styleCollector } : {}),\n ...(input.authoring !== undefined ? { authoring: input.authoring } : {}),\n };\n};\n\n/** Throws if `primitives` repeats a type. */\nconst assertUniquePrimitiveTypes = (\n id: string,\n primitives: readonly AnyPrimitiveDefinition[]\n): void => {\n const seen = new Set<string>();\n for (const { type } of primitives) {\n if (seen.has(type)) {\n throw new IsomerError(\n 'DUPLICATE_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": primitive type \"${type}\" registered twice`\n );\n }\n seen.add(type);\n }\n};\n\n/** Throws if a group names a type outside `types`, or two groups share a type. */\nconst assertGroupedOnce = (\n id: string,\n groups: readonly PrimitiveGroup[],\n types: ReadonlySet<string>\n): void => {\n const grouped = new Set<string>();\n for (const { title, types: members } of groups) {\n for (const type of members) {\n if (!types.has(type)) {\n throw new IsomerError(\n 'UNKNOWN_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": group \"${title}\" names primitive type \"${type}\", which the pack does not register`\n );\n }\n if (grouped.has(type)) {\n throw new IsomerError(\n 'DUPLICATE_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": primitive type \"${type}\" is in two groups`\n );\n }\n grouped.add(type);\n }\n }\n};\n\n/** Throws if this pack registers the same enhancement id twice. */\nconst assertUniqueEnhancementIds = (\n id: string,\n enhancements: readonly EnhancementDefinition[]\n): void => {\n const seen = new Set<string>();\n for (const definition of enhancements) {\n if (seen.has(definition.id)) {\n throw new IsomerError(\n 'DUPLICATE_ENHANCEMENT',\n `primitive pack \"${id}\": enhancement \"${definition.id}\" registered twice`\n );\n }\n seen.add(definition.id);\n }\n};\n"]}
1
+ {"version":3,"file":"primitive_pack.js","sourceRoot":"","sources":["../../../src/pack/primitive_pack.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,6EAA6E;AAC7E,gFAAgF;AAChF,gEAAgE;AAEhE,gDAAmD;AAiCnD,mGAAmG;AACtF,QAAA,yBAAyB,GAAG,eAAe,CAAC;AAuIzD;;;;;;GAMG;AACI,MAAM,mBAAmB,GAAG,CACjC,KAAyB,EACF,EAAE;IACzB,IAAI,KAAK,CAAC,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;QAClC,MAAM,IAAI,mBAAW,CACnB,YAAY,EACZ,mBAAmB,KAAK,CAAC,EAAE,uCAAuC,CACnE,CAAC;IACJ,CAAC;IACD,0BAA0B,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACvD,0BAA0B,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,CAAC;IAC/D,MAAM,KAAK,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC;IAC7E,iBAAiB,CAAC,KAAK,CAAC,EAAE,EAAE,KAAK,CAAC,SAAS,EAAE,MAAM,IAAI,EAAE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AAE,CAAC;YACtB,MAAM,IAAI,mBAAW,CACnB,qBAAqB,EACrB,mBAAmB,EAAE,mBAAmB,KAAK,iBAAiB,CAC/D,CAAC;QACJ,CAAC;QACD,MAAM,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAClB,KAAK,MAAM,IAAI,IAAI,OAAO,EAAE,CAAC;YAC3B,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBACrB,MAAM,IAAI,mBAAW,CACnB,wBAAwB,EACxB,mBAAmB,EAAE,aAAa,KAAK,2BAA2B,IAAI,qCAAqC,CAC5G,CAAC;YACJ,CAAC;YACD,IAAI,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC;gBACtB,MAAM,IAAI,mBAAW,CACnB,0BAA0B,EAC1B,mBAAmB,EAAE,sBAAsB,IAAI,oBAAoB,CACpE,CAAC;YACJ,CAAC;YACD,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;IACH,CAAC;AACH,CAAC,CAAC;AAEF,mEAAmE;AACnE,MAAM,0BAA0B,GAAG,CACjC,EAAU,EACV,YAA8C,EACxC,EAAE;IACR,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,KAAK,MAAM,UAAU,IAAI,YAAY,EAAE,CAAC;QACtC,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC,EAAE,CAAC;YAC5B,MAAM,IAAI,mBAAW,CACnB,uBAAuB,EACvB,mBAAmB,EAAE,mBAAmB,UAAU,CAAC,EAAE,oBAAoB,CAC1E,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,GAAG,CAAC,UAAU,CAAC,EAAE,CAAC,CAAC;IAC1B,CAAC;AACH,CAAC,CAAC","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\n// A primitive pack as a value: a vocabulary, and the optional surfaces every\n// primitive in it implements. Additive: a runtime composes any number of packs,\n// and nothing about a pack decides how a composition is framed.\n\nimport { IsomerError } from '../composition/error';\nimport type { PrimitiveIcon } from '../define/primitive_icon';\nimport type {\n AnyPrimitiveDefinition,\n OptionalSurface,\n StyleHandle,\n} from '../define/primitive_module';\n\nimport type { EnhancementDefinition } from './enhancements';\n\n/**\n * The authoring-schema material a pack contributes for its own primitives.\n *\n * A subset of `AuthoringJsonSchemaOptions`: `$id`, `title`, `description`, and\n * `composition` describe the whole authoring schema a runtime builds, which is\n * a host decision, not a pack one. `pack/` does not import `validate/` for\n * this, so the shape is declared here rather than reused by reference.\n */\nexport interface PackAuthoringOptions {\n /** `$def` id to `description`, for this pack's own primitives. */\n describe?: Readonly<Record<string, string>>;\n /** `$defId.property` paths to drop, from this pack's own primitives. */\n omitProperties?: readonly string[];\n /** Headings an index catalog sorts this pack's primitives under, in order. A type in none is listed under {@link UNCATEGORIZED_GROUP_TITLE}. */\n groups?: readonly PrimitiveGroup[];\n}\n\n/** A titled set of primitive types, listed together in an index catalog. */\nexport interface PrimitiveGroup {\n title: string;\n types: readonly string[];\n}\n\n/** The index heading for primitives in no group. A pack cannot declare a group with this title. */\nexport const UNCATEGORIZED_GROUP_TITLE = 'Uncategorized';\n\n/**\n * The HTML style-adapter hooks a pack may declare. Typed loosely here so `pack/` does not import `render/`.\n */\nexport type PackStyleAdapter = {\n /** See {@link PrimitivePackInput.styleCollector}. */\n styleCollector?: string;\n /** The hooks of `HTMLStyleAdapter` from `./html`, erased: a fresh collector per render, the context renderers receive, and the stylesheet the collector produced. */\n createCollector: (...args: never[]) => object;\n createRenderContext: (...args: never[]) => unknown;\n renderStyles: (...args: never[]) => string;\n /**\n * Whether `handle` belongs to this adapter's stylesheet. Required for a runtime to combine several packs' CSS: without it their handles cannot be routed and the host must pick one adapter.\n */\n ownsHandle?: (handle: StyleHandle) => boolean;\n};\n\n/** What a pack author passes to {@link definePrimitivePack}. */\nexport interface PrimitivePackInput {\n /** Stable identifier, used in capability reports and error messages. */\n id: string;\n /**\n * The optional surfaces this pack's primitives implement.\n *\n * Only `slack`, and it stays optional per primitive: the dispatcher converts\n * the mandatory markdown to Block Kit, so declaring it reports an intent\n * rather than imposing a requirement. Omit it entirely for a pack that\n * renders Slack through that fallback.\n */\n surfaces?: readonly OptionalSurface[];\n /** This pack's vocabulary. Node types must be unique within it, or construction throws. */\n primitives: readonly AnyPrimitiveDefinition[];\n /**\n * Progressive enhancements this pack's primitives can apply, by id.\n *\n * Declared by the pack because an enhancement is a fact about its\n * vocabulary — a sortable table, a copyable code block — and a host\n * composing packs it did not write cannot be expected to know the ids.\n * The runtime flattens these across packs; duplicate ids are rejected.\n */\n enhancements?: readonly EnhancementDefinition[];\n /**\n * Types that render as a self-contained picture rather than as text.\n *\n * A channel that cannot draw them inline uploads an image instead: the Slack\n * dispatcher swaps such a node for an `image` block and an upload request, so\n * a chart arrives as a PNG rather than as a markdown approximation of one.\n *\n * Declared by the pack because it is a fact about the vocabulary, and a host\n * composing packs it did not write cannot be expected to know it.\n */\n slackAssetTypes?: readonly string[];\n /**\n * Default HTML style adapter for this pack. A runtime that omits\n * `styleAdapter` runs the packs' own adapters, combined when more than one\n * pack declares one and each answers `ownsHandle`. Pass `styleAdapter` on\n * the runtime to replace them all.\n */\n styleAdapter?: PackStyleAdapter;\n /**\n * Names the collector shape this pack's `collectStyles` hooks mutate, so a\n * runtime can reject a pack paired with an adapter of a different tag.\n * Defaults to `styleAdapter.styleCollector`; a pack with neither opts out of\n * the check.\n */\n styleCollector?: string;\n /**\n * This pack's own contribution to the runtime's authoring JSON Schema.\n *\n * Merged across every composed pack, so a host does not hand-merge each\n * pack's `describe`/`omitProperties` into one options object itself. The\n * runtime-level `authoring` option is merged in last and wins on conflict.\n */\n authoring?: PackAuthoringOptions;\n}\n\n/**\n * A pack as the runtime sees it.\n *\n * `TTheme` is the palette this pack's `react` renderers read as `env.theme`\n * when drawn through the `snapshot` surface — a *lower bound* on whatever theme\n * the runtime holding it supplies. It is carried by\n * {@link PrimitivePack.__theme} rather than by any real field, because\n * `primitives` is erased to `AnyPrimitiveDefinition[]` and a heterogeneous\n * inventory has no single node type to be generic over.\n *\n * The bound is declared, not derived: nothing checks it against what the\n * renderers actually read. State it at the definition as\n * `definePrimitivePack<T>(input)`.\n * Bare `PrimitivePack` requires nothing and fits any runtime; a slot that must\n * hold packs of every palette is typed {@link AnyPrimitivePack}.\n */\nexport interface PrimitivePack<TTheme = unknown> {\n /** Unique among the packs a runtime composes, and used in error messages. */\n readonly id: string;\n /** See {@link PrimitivePackInput.surfaces}. */\n readonly surfaces: readonly OptionalSurface[];\n /** See {@link PrimitivePackInput.primitives}. */\n readonly primitives: readonly AnyPrimitiveDefinition[];\n /** Node types this pack owns, for duplicate detection across packs. */\n readonly types: ReadonlySet<string>;\n /**\n * Each primitive's `icon` by type, for the primitives that declare one, so a host listing them need not walk `primitives`.\n *\n * A frozen null-prototype dictionary: an absent type reads `undefined`, even `constructor`. Absent on a pack built by an SDK that predates icons; {@link iconsByType} derives it from `primitives`.\n */\n readonly icons?: Readonly<Record<string, PrimitiveIcon>>;\n /** See {@link PrimitivePackInput.enhancements}. */\n readonly enhancements: readonly EnhancementDefinition[];\n /** See {@link PrimitivePackInput.slackAssetTypes}. */\n readonly slackAssetTypes: ReadonlySet<string>;\n /** See {@link PrimitivePackInput.styleAdapter}. */\n readonly styleAdapter?: PackStyleAdapter;\n /** See {@link PrimitivePackInput.styleCollector}. */\n readonly styleCollector?: string;\n /** See {@link PrimitivePackInput.authoring}. */\n readonly authoring?: PackAuthoringOptions;\n /**\n * Phantom: never present at runtime, never read.\n *\n * A property rather than a method so `strictFunctionTypes` checks it\n * contravariantly. A method signature is bivariant, which would let a pack\n * needing richer tokens sit in a slot supplying fewer and then read a field\n * nothing supplies — the exact failure this marker exists to prevent.\n */\n readonly __theme?: (theme: TTheme) => void;\n}\n\n/**\n * A pack of any palette, for storage positions: `never` is assignable to every\n * requirement, so a slot typed this way holds every pack.\n */\nexport type AnyPrimitivePack = PrimitivePack<never>;\n\n/**\n * Builds a {@link PrimitivePack}.\n *\n * `TTheme` is the palette a frame must supply for this pack's nodes to be drawn\n * on the `snapshot` surface: `definePrimitivePack<CoreTokens>(input)`. Omitted, it is\n * `unknown`, which requires nothing.\n */\nexport const definePrimitivePack = <TTheme = unknown>(\n input: PrimitivePackInput\n): PrimitivePack<TTheme> => {\n if (input.primitives.length === 0) {\n throw new IsomerError(\n 'EMPTY_PACK',\n `primitive pack \"${input.id}\": at least one primitive is required`\n );\n }\n assertUniquePrimitiveTypes(input.id, input.primitives);\n assertUniqueEnhancementIds(input.id, input.enhancements ?? []);\n const types = new Set(input.primitives.map((definition) => definition.type));\n assertValidGroups(input.id, input.authoring?.groups ?? [], types);\n for (const type of input.slackAssetTypes ?? []) {\n if (!types.has(type)) {\n throw new IsomerError(\n 'UNKNOWN_PRIMITIVE_TYPE',\n `primitive pack \"${input.id}\": slackAssetTypes names primitive type \"${type}\", which the pack does not register`\n );\n }\n }\n const styleCollector =\n input.styleCollector ?? input.styleAdapter?.styleCollector;\n\n return {\n id: input.id,\n surfaces: input.surfaces ?? [],\n primitives: input.primitives,\n types,\n icons: iconsByType(input.primitives),\n enhancements: input.enhancements ?? [],\n slackAssetTypes: new Set(input.slackAssetTypes ?? []),\n ...(input.styleAdapter !== undefined\n ? { styleAdapter: input.styleAdapter }\n : {}),\n ...(styleCollector !== undefined ? { styleCollector } : {}),\n ...(input.authoring !== undefined ? { authoring: input.authoring } : {}),\n };\n};\n\n/** Each definition's `icon` by type, null-prototype so a type such as `__proto__` is an ordinary key. */\nexport const iconsByType = (\n primitives: readonly AnyPrimitiveDefinition[]\n): Readonly<Record<string, PrimitiveIcon>> => {\n const icons = Object.create(null) as Record<string, PrimitiveIcon>;\n for (const { type, icon } of primitives) {\n if (icon !== undefined) {\n icons[type] = icon;\n }\n }\n return Object.freeze(icons);\n};\n\n/** Throws if `primitives` repeats a type. */\nconst assertUniquePrimitiveTypes = (\n id: string,\n primitives: readonly AnyPrimitiveDefinition[]\n): void => {\n const seen = new Set<string>();\n for (const { type } of primitives) {\n if (seen.has(type)) {\n throw new IsomerError(\n 'DUPLICATE_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": primitive type \"${type}\" registered twice`\n );\n }\n seen.add(type);\n }\n};\n\n/** Throws if a group repeats or reserves a title, names a type outside `types`, or shares a type with another. */\nconst assertValidGroups = (\n id: string,\n groups: readonly PrimitiveGroup[],\n types: ReadonlySet<string>\n): void => {\n const titles = new Set<string>();\n const grouped = new Set<string>();\n for (const { title, types: members } of groups) {\n if (title === UNCATEGORIZED_GROUP_TITLE) {\n throw new IsomerError(\n 'INVALID_PACK_GROUPS',\n `primitive pack \"${id}\": group title \"${title}\" is reserved for primitives in no group`\n );\n }\n if (titles.has(title)) {\n throw new IsomerError(\n 'INVALID_PACK_GROUPS',\n `primitive pack \"${id}\": group title \"${title}\" is used twice`\n );\n }\n titles.add(title);\n for (const type of members) {\n if (!types.has(type)) {\n throw new IsomerError(\n 'UNKNOWN_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": group \"${title}\" names primitive type \"${type}\", which the pack does not register`\n );\n }\n if (grouped.has(type)) {\n throw new IsomerError(\n 'DUPLICATE_PRIMITIVE_TYPE',\n `primitive pack \"${id}\": primitive type \"${type}\" is in two groups`\n );\n }\n grouped.add(type);\n }\n }\n};\n\n/** Throws if this pack registers the same enhancement id twice. */\nconst assertUniqueEnhancementIds = (\n id: string,\n enhancements: readonly EnhancementDefinition[]\n): void => {\n const seen = new Set<string>();\n for (const definition of enhancements) {\n if (seen.has(definition.id)) {\n throw new IsomerError(\n 'DUPLICATE_ENHANCEMENT',\n `primitive pack \"${id}\": enhancement \"${definition.id}\" registered twice`\n );\n }\n seen.add(definition.id);\n }\n};\n"]}
@@ -77,7 +77,7 @@ const anchorsOn = (context) => {
77
77
  /**
78
78
  * Props a `react` renderer spreads on its root element so runtime code can find
79
79
  * the node with {@link findNodeElementPairs}. Inside an HTML surface render the
80
- * surface decides; elsewhere, on the React and `svg` surfaces, `context.anchors`
80
+ * surface decides; elsewhere, on the React and `snapshot` surfaces, `context.anchors`
81
81
  * does. Always empty under {@link withoutAnchors}.
82
82
  */
83
83
  const nodeAnchor = (context, { type }) => anchorsOn(context) ? { [exports.NODE_ANCHOR_ATTRIBUTE]: (0, exports.anchorValue)(type) } : {};
@@ -1 +1 @@
1
- {"version":3,"file":"anchors.js","sourceRoot":"","sources":["../../../src/render/anchors.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,kEAIuC;AAEvC,iDAA2D;AAE3D,2GAA2G;AAC9F,QAAA,qBAAqB,GAAG,kBAAkB,CAAC;AAExD;;;;GAIG;AACI,MAAM,WAAW,GAAG,CAAC,IAAY,EAAU,EAAE,CAClD,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC,CAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;AADlE,QAAA,WAAW,eACuD;AAE/E,oFAAoF;AACpF,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAE5D;;;GAGG;AACH,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;AAI3D,MAAM,aAAa,GAAG,GAAwB,EAAE,CAC7C,UAA0B,CAAC,MAAM,CAAC,CAAC;AAEtC;;;;GAIG;AACI,MAAM,WAAW,GAAG,CACzB,EAAW,EACX,MAAqB,EACZ,EAAE;IACX,MAAM,KAAK,GAAG,UAAyB,CAAC;IACxC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5B,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;IACnB,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAA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SAAS,CAAC;QACnB,CAAC;QACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QAC1B,MAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,IAAA,mBAAW,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QACxD,OAAO,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AA5BW,QAAA,WAAW,eA4BtB;AAEF;;;;;;;;;GASG;AACI,MAAM,oBAAoB,GAAG,CAClC,IAAgB,EAChB,IAAwB,EACxB,IAAqB,EAC8B,EAAE;IACrD,MAAM,KAAK,GAAG,IAAA,qBAAa,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACxC,uEAAuE;IACvE,MAAM,QAAQ,GAAG,IAAA,mBAAW,EAC1B,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,gBAAgB,CAAC,IAAI,6BAAqB,GAAG,CAAC,EACnD,CAAC,OAAO,EAAE,EAAE,CACV,CAAC,OAAO,CAAC,YAAY,CAAC,6BAAqB,CAAC,IAAI,EAAE,EAAE,OAAO,CAAU,CACxE,EACD,KAAK,CACN,CAAC;IACF,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AAC1E,CAAC,CAAC;AAhBW,QAAA,oBAAoB,wBAgB/B","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport {\n childNodePath,\n type ChildNodeWalker,\n isVisibleOnSurface,\n} from '../composition/body_node_base';\n\nimport { contextWith, isObjectLike } from './context_view';\n\n/** The attribute {@link nodeAnchor} sets to a node's type, escaped so HTML parsing leaves it unchanged. */\nexport const NODE_ANCHOR_ATTRIBUTE = 'data-isomer-node';\n\n/**\n * A node type as its anchor carries it. Every character outside `[A-Za-z0-9_-]`\n * becomes `%<hex code point>;`, so the value survives HTML serialization and\n * parsing unchanged and never throws. A plain identifier stays as it is.\n */\nexport const anchorValue = (type: string): string =>\n type.replace(/[^\\w-]/gu, (char) => `%${char.codePointAt(0)!.toString(16)};`);\n\n/** Marks a context whose subtree renders no anchors; see {@link withoutAnchors}. */\nconst NO_ANCHORS = Symbol.for('elastic.isomer.anchors_off');\n\n/**\n * Where an HTML render keeps its anchor decision while it runs. On `globalThis`\n * under a `Symbol.for` key, so an ESM and a CommonJS copy of the SDK share it.\n */\nconst ACTIVE = Symbol.for('elastic.isomer.anchors_active');\n\ntype AnchorScope = { [ACTIVE]?: boolean };\n\nconst activeAnchors = (): boolean | undefined =>\n (globalThis as AnchorScope)[ACTIVE];\n\n/**\n * Runs `render` with anchors on or off for every {@link nodeAnchor} it reaches,\n * whatever each render context says. The render must be synchronous; the\n * previous state comes back afterwards, even if it throws.\n */\nexport const withAnchors = <TResult>(\n on: boolean,\n render: () => TResult\n): TResult => {\n const scope = globalThis as AnchorScope;\n const outer = scope[ACTIVE];\n scope[ACTIVE] = on;\n try {\n return render();\n } finally {\n if (outer === undefined) {\n delete scope[ACTIVE];\n } else {\n scope[ACTIVE] = outer;\n }\n }\n};\n\n/**\n * `context` for content a renderer draws that is not one of its `children`,\n * such as an embedded composition: nothing under it renders an anchor.\n *\n * The result is a view of `context`, not a copy: reads go to `context` itself,\n * with methods bound to it, so getters, methods, private state, and\n * `instanceof` behave as before. The mark survives a context derived from it\n * by spreading. A context that is neither an object nor a function is\n * returned as it is.\n */\nexport const withoutAnchors = <TContext>(context: TContext): TContext =>\n contextWith(context, NO_ANCHORS, true);\n\n/**\n * `context` with node anchors on, as an enhancement declaring `anchors: true`\n * turns them on. A view like {@link withoutAnchors}, which still wins.\n */\nexport const withNodeAnchors = <TContext>(context: TContext): TContext =>\n contextWith(context, 'anchors', true);\n\nconst anchorsOn = (context: unknown): boolean => {\n const carries = isObjectLike(context);\n if (carries && Reflect.get(context, NO_ANCHORS) === true) {\n return false;\n }\n return (\n activeAnchors() ??\n (carries && (context as { anchors?: unknown }).anchors === true)\n );\n};\n\n/**\n * Props a `react` renderer spreads on its root element so runtime code can find\n * the node with {@link findNodeElementPairs}. Inside an HTML surface render the\n * surface decides; elsewhere, on the React and `svg` surfaces, `context.anchors`\n * does. Always empty under {@link withoutAnchors}.\n */\nexport const nodeAnchor = (\n context: unknown,\n { type }: { type: string }\n): Readonly<Record<string, string>> =>\n anchorsOn(context) ? { [NODE_ANCHOR_ATTRIBUTE]: anchorValue(type) } : {};\n\n/** The attribute {@link layoutRoom} sets. */\nexport const LAYOUT_ROOM_ATTRIBUTE = 'data-isomer-room';\n\n/**\n * Props a renderer spreads on an element inside its node that bounds the nodes\n * nested in it, such as a frame's body, so `checkLayout` measures them against\n * it. Rendered when {@link nodeAnchor} would be.\n */\nexport const layoutRoom = (\n context: unknown\n): Readonly<Record<string, string>> =>\n anchorsOn(context) ? { [LAYOUT_ROOM_ATTRIBUTE]: '' } : {};\n\n/**\n * The nodes of `body` a render on `surface` draws, pre-order, each with its\n * path in validation's `body[0].items[1]` form. Nested nodes follow `react`,\n * as a container renders them through `renderReact` on either surface.\n */\nexport const anchoredNodePaths = (\n body: readonly unknown[],\n walk: ChildNodeWalker,\n surface: 'react' | 'svg' = 'react'\n): { node: unknown; path: string }[] => {\n const visit = (\n node: unknown,\n path: string\n ): { node: unknown; path: string }[] => [\n { node, path },\n ...walk(node).flatMap((child) =>\n isVisibleOnSurface(child.node, 'react')\n ? visit(child.node, childNodePath(path, child.path))\n : []\n ),\n ];\n return body.flatMap((node, index) =>\n isVisibleOnSurface(node, surface) ? visit(node, `body[${index}]`) : []\n );\n};\n\n/** The `react`-visible nodes of `body`, pre-order: the order their anchors render in. */\nexport const anchoredNodes = (\n body: readonly unknown[],\n walk: ChildNodeWalker\n): unknown[] => anchoredNodePaths(body, walk).map(({ node }) => node);\n\n/** A node's `type`, when it has one. */\nexport const nodeType = (node: unknown): string | undefined => {\n const { type } = node as { type?: unknown };\n return typeof type === 'string' ? type : undefined;\n};\n\n/**\n * The item each of `nodes` pairs with, from `anchored` in document order: the\n * k-th node of a type pairs with the k-th item whose anchor value is that\n * type's. A type whose node and item counts disagree pairs with nothing.\n */\nexport const pairAnchors = <TItem>(\n anchored: Iterable<readonly [value: string, item: TItem]>,\n nodes: readonly unknown[]\n): (TItem | undefined)[] => {\n const itemsByValue = new Map<string, TItem[]>();\n for (const [value, item] of anchored) {\n const items = itemsByValue.get(value) ?? [];\n items.push(item);\n itemsByValue.set(value, items);\n }\n const counts = new Map<string, number>();\n for (const node of nodes) {\n const type = nodeType(node);\n if (type !== undefined) {\n counts.set(type, (counts.get(type) ?? 0) + 1);\n }\n }\n const seen = new Map<string, number>();\n return nodes.map((node) => {\n const type = nodeType(node);\n if (type === undefined) {\n return undefined;\n }\n const index = seen.get(type) ?? 0;\n seen.set(type, index + 1);\n const items = itemsByValue.get(anchorValue(type)) ?? [];\n return items.length === counts.get(type) ? items[index] : undefined;\n });\n};\n\n/**\n * Every `react`-visible node of `body`, walked pre-order, with the element\n * its anchor marks under `root`, paired by {@link pairAnchors}. `root` holds\n * one render.\n *\n * Pairing holds because every renderer draws its `children` in the order its\n * definition's `children` returns them. A node that rendered nothing leaves\n * its type unpaired. A node object that appears twice appears twice here,\n * each time with its own element.\n */\nexport const findNodeElementPairs = (\n root: ParentNode,\n body: readonly unknown[],\n walk: ChildNodeWalker\n): { node: unknown; element: Element | undefined }[] => {\n const nodes = anchoredNodes(body, walk);\n // Read by attribute value, so a type is never read as selector syntax.\n const elements = pairAnchors(\n Array.from(\n root.querySelectorAll(`[${NODE_ANCHOR_ATTRIBUTE}]`),\n (element) =>\n [element.getAttribute(NODE_ANCHOR_ATTRIBUTE) ?? '', element] as const\n ),\n nodes\n );\n return nodes.map((node, index) => ({ node, element: elements[index] }));\n};\n"]}
1
+ {"version":3,"file":"anchors.js","sourceRoot":"","sources":["../../../src/render/anchors.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,kEAIuC;AAEvC,iDAA2D;AAE3D,2GAA2G;AAC9F,QAAA,qBAAqB,GAAG,kBAAkB,CAAC;AAExD;;;;GAIG;AACI,MAAM,WAAW,GAAG,CAAC,IAAY,EAAU,EAAE,CAClD,IAAI,CAAC,OAAO,CAAC,UAAU,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,IAAI,CAAC,WAAW,CAAC,CAAC,CAAE,CAAC,QAAQ,CAAC,EAAE,CAAC,GAAG,CAAC,CAAC;AADlE,QAAA,WAAW,eACuD;AAE/E,oFAAoF;AACpF,MAAM,UAAU,GAAG,MAAM,CAAC,GAAG,CAAC,4BAA4B,CAAC,CAAC;AAE5D;;;GAGG;AACH,MAAM,MAAM,GAAG,MAAM,CAAC,GAAG,CAAC,+BAA+B,CAAC,CAAC;AAI3D,MAAM,aAAa,GAAG,GAAwB,EAAE,CAC7C,UAA0B,CAAC,MAAM,CAAC,CAAC;AAEtC;;;;GAIG;AACI,MAAM,WAAW,GAAG,CACzB,EAAW,EACX,MAAqB,EACZ,EAAE;IACX,MAAM,KAAK,GAAG,UAAyB,CAAC;IACxC,MAAM,KAAK,GAAG,KAAK,CAAC,MAAM,CAAC,CAAC;IAC5B,KAAK,CAAC,MAAM,CAAC,GAAG,EAAE,CAAC;IACnB,IAAI,CAAC;QACH,OAAO,MAAM,EAAE,CAAC;IAClB,CAAC;YAAS,CAAC;QACT,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACxB,OAAO,KAAK,CAA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,CAAC,CAAC;QAClC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;QAC1B,MAAM,KAAK,GAAG,YAAY,CAAC,GAAG,CAAC,IAAA,mBAAW,EAAC,IAAI,CAAC,CAAC,IAAI,EAAE,CAAC;QACxD,OAAO,KAAK,CAAC,MAAM,KAAK,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;IACtE,CAAC,CAAC,CAAC;AACL,CAAC,CAAC;AA5BW,QAAA,WAAW,eA4BtB;AAEF;;;;;;;;;GASG;AACI,MAAM,oBAAoB,GAAG,CAClC,IAAgB,EAChB,IAAwB,EACxB,IAAqB,EAC8B,EAAE;IACrD,MAAM,KAAK,GAAG,IAAA,qBAAa,EAAC,IAAI,EAAE,IAAI,CAAC,CAAC;IACxC,uEAAuE;IACvE,MAAM,QAAQ,GAAG,IAAA,mBAAW,EAC1B,KAAK,CAAC,IAAI,CACR,IAAI,CAAC,gBAAgB,CAAC,IAAI,6BAAqB,GAAG,CAAC,EACnD,CAAC,OAAO,EAAE,EAAE,CACV,CAAC,OAAO,CAAC,YAAY,CAAC,6BAAqB,CAAC,IAAI,EAAE,EAAE,OAAO,CAAU,CACxE,EACD,KAAK,CACN,CAAC;IACF,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,EAAE,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAC;AAC1E,CAAC,CAAC;AAhBW,QAAA,oBAAoB,wBAgB/B","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport {\n childNodePath,\n type ChildNodeWalker,\n isVisibleOnSurface,\n} from '../composition/body_node_base';\n\nimport { contextWith, isObjectLike } from './context_view';\n\n/** The attribute {@link nodeAnchor} sets to a node's type, escaped so HTML parsing leaves it unchanged. */\nexport const NODE_ANCHOR_ATTRIBUTE = 'data-isomer-node';\n\n/**\n * A node type as its anchor carries it. Every character outside `[A-Za-z0-9_-]`\n * becomes `%<hex code point>;`, so the value survives HTML serialization and\n * parsing unchanged and never throws. A plain identifier stays as it is.\n */\nexport const anchorValue = (type: string): string =>\n type.replace(/[^\\w-]/gu, (char) => `%${char.codePointAt(0)!.toString(16)};`);\n\n/** Marks a context whose subtree renders no anchors; see {@link withoutAnchors}. */\nconst NO_ANCHORS = Symbol.for('elastic.isomer.anchors_off');\n\n/**\n * Where an HTML render keeps its anchor decision while it runs. On `globalThis`\n * under a `Symbol.for` key, so an ESM and a CommonJS copy of the SDK share it.\n */\nconst ACTIVE = Symbol.for('elastic.isomer.anchors_active');\n\ntype AnchorScope = { [ACTIVE]?: boolean };\n\nconst activeAnchors = (): boolean | undefined =>\n (globalThis as AnchorScope)[ACTIVE];\n\n/**\n * Runs `render` with anchors on or off for every {@link nodeAnchor} it reaches,\n * whatever each render context says. The render must be synchronous; the\n * previous state comes back afterwards, even if it throws.\n */\nexport const withAnchors = <TResult>(\n on: boolean,\n render: () => TResult\n): TResult => {\n const scope = globalThis as AnchorScope;\n const outer = scope[ACTIVE];\n scope[ACTIVE] = on;\n try {\n return render();\n } finally {\n if (outer === undefined) {\n delete scope[ACTIVE];\n } else {\n scope[ACTIVE] = outer;\n }\n }\n};\n\n/**\n * `context` for content a renderer draws that is not one of its `children`,\n * such as an embedded composition: nothing under it renders an anchor.\n *\n * The result is a view of `context`, not a copy: reads go to `context` itself,\n * with methods bound to it, so getters, methods, private state, and\n * `instanceof` behave as before. The mark survives a context derived from it\n * by spreading. A context that is neither an object nor a function is\n * returned as it is.\n */\nexport const withoutAnchors = <TContext>(context: TContext): TContext =>\n contextWith(context, NO_ANCHORS, true);\n\n/**\n * `context` with node anchors on, as an enhancement declaring `anchors: true`\n * turns them on. A view like {@link withoutAnchors}, which still wins.\n */\nexport const withNodeAnchors = <TContext>(context: TContext): TContext =>\n contextWith(context, 'anchors', true);\n\nconst anchorsOn = (context: unknown): boolean => {\n const carries = isObjectLike(context);\n if (carries && Reflect.get(context, NO_ANCHORS) === true) {\n return false;\n }\n return (\n activeAnchors() ??\n (carries && (context as { anchors?: unknown }).anchors === true)\n );\n};\n\n/**\n * Props a `react` renderer spreads on its root element so runtime code can find\n * the node with {@link findNodeElementPairs}. Inside an HTML surface render the\n * surface decides; elsewhere, on the React and `snapshot` surfaces, `context.anchors`\n * does. Always empty under {@link withoutAnchors}.\n */\nexport const nodeAnchor = (\n context: unknown,\n { type }: { type: string }\n): Readonly<Record<string, string>> =>\n anchorsOn(context) ? { [NODE_ANCHOR_ATTRIBUTE]: anchorValue(type) } : {};\n\n/** The attribute {@link layoutRoom} sets. */\nexport const LAYOUT_ROOM_ATTRIBUTE = 'data-isomer-room';\n\n/**\n * Props a renderer spreads on an element inside its node that bounds the nodes\n * nested in it, such as a frame's body, so `checkLayout` measures them against\n * it. Rendered when {@link nodeAnchor} would be.\n */\nexport const layoutRoom = (\n context: unknown\n): Readonly<Record<string, string>> =>\n anchorsOn(context) ? { [LAYOUT_ROOM_ATTRIBUTE]: '' } : {};\n\n/**\n * The nodes of `body` a render on `surface` draws, pre-order, each with its\n * path in validation's `body[0].items[1]` form. Nested nodes follow `react`,\n * as a container renders them through `renderReact` on either surface.\n */\nexport const anchoredNodePaths = (\n body: readonly unknown[],\n walk: ChildNodeWalker,\n surface: 'react' | 'snapshot' = 'react'\n): { node: unknown; path: string }[] => {\n const visit = (\n node: unknown,\n path: string\n ): { node: unknown; path: string }[] => [\n { node, path },\n ...walk(node).flatMap((child) =>\n isVisibleOnSurface(child.node, 'react')\n ? visit(child.node, childNodePath(path, child.path))\n : []\n ),\n ];\n return body.flatMap((node, index) =>\n isVisibleOnSurface(node, surface) ? visit(node, `body[${index}]`) : []\n );\n};\n\n/** The `react`-visible nodes of `body`, pre-order: the order their anchors render in. */\nexport const anchoredNodes = (\n body: readonly unknown[],\n walk: ChildNodeWalker\n): unknown[] => anchoredNodePaths(body, walk).map(({ node }) => node);\n\n/** A node's `type`, when it has one. */\nexport const nodeType = (node: unknown): string | undefined => {\n const { type } = node as { type?: unknown };\n return typeof type === 'string' ? type : undefined;\n};\n\n/**\n * The item each of `nodes` pairs with, from `anchored` in document order: the\n * k-th node of a type pairs with the k-th item whose anchor value is that\n * type's. A type whose node and item counts disagree pairs with nothing.\n */\nexport const pairAnchors = <TItem>(\n anchored: Iterable<readonly [value: string, item: TItem]>,\n nodes: readonly unknown[]\n): (TItem | undefined)[] => {\n const itemsByValue = new Map<string, TItem[]>();\n for (const [value, item] of anchored) {\n const items = itemsByValue.get(value) ?? [];\n items.push(item);\n itemsByValue.set(value, items);\n }\n const counts = new Map<string, number>();\n for (const node of nodes) {\n const type = nodeType(node);\n if (type !== undefined) {\n counts.set(type, (counts.get(type) ?? 0) + 1);\n }\n }\n const seen = new Map<string, number>();\n return nodes.map((node) => {\n const type = nodeType(node);\n if (type === undefined) {\n return undefined;\n }\n const index = seen.get(type) ?? 0;\n seen.set(type, index + 1);\n const items = itemsByValue.get(anchorValue(type)) ?? [];\n return items.length === counts.get(type) ? items[index] : undefined;\n });\n};\n\n/**\n * Every `react`-visible node of `body`, walked pre-order, with the element\n * its anchor marks under `root`, paired by {@link pairAnchors}. `root` holds\n * one render.\n *\n * Pairing holds because every renderer draws its `children` in the order its\n * definition's `children` returns them. A node that rendered nothing leaves\n * its type unpaired. A node object that appears twice appears twice here,\n * each time with its own element.\n */\nexport const findNodeElementPairs = (\n root: ParentNode,\n body: readonly unknown[],\n walk: ChildNodeWalker\n): { node: unknown; element: Element | undefined }[] => {\n const nodes = anchoredNodes(body, walk);\n // Read by attribute value, so a type is never read as selector syntax.\n const elements = pairAnchors(\n Array.from(\n root.querySelectorAll(`[${NODE_ANCHOR_ATTRIBUTE}]`),\n (element) =>\n [element.getAttribute(NODE_ANCHOR_ATTRIBUTE) ?? '', element] as const\n ),\n nodes\n );\n return nodes.map((node, index) => ({ node, element: elements[index] }));\n};\n"]}
@@ -31,8 +31,9 @@ const trimDecimal = (value, precision) => Number.isInteger(value)
31
31
  const formatCompactNumber = (value, unit = '', precision = 1) => {
32
32
  const abs = Math.abs(value);
33
33
  let index = TIERS.findIndex(({ size }) => abs >= size);
34
- if (index === -1)
34
+ if (index === -1) {
35
35
  index = TIERS.length - 1;
36
+ }
36
37
  // A value that rounds up to the tier's next power, `999.96k`, reads as `1m`.
37
38
  if (index > 0 &&
38
39
  Math.abs(Number((value / TIERS[index].size).toFixed(precision))) >= 1_000) {
@@ -1 +1 @@
1
- {"version":3,"file":"format_number.js","sourceRoot":"","sources":["../../../src/render/format_number.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,+EAA+E;AAC/E,6EAA6E;AAC7E,2BAA2B;AAE3B,MAAM,KAAK,GAAG;IACZ,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE;IACxC,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE;IACpC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE;IAChC,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE;IAC5B,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE;CACf,CAAC;AAEX,2DAA2D;AAC3D,MAAM,WAAW,GAAG,CAAC,KAAa,EAAE,SAAiB,EAAU,EAAE,CAC/D,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC;IACrB,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;IACf,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC;AAE/C;;;;;;GAMG;AACI,MAAM,mBAAmB,GAAG,CACjC,KAAa,EACb,IAAI,GAAG,EAAE,EACT,SAAS,GAAG,CAAC,EACL,EAAE;IACV,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IAC5B,IAAI,KAAK,GAAG,KAAK,CAAC,SAAS,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,EAAE,CAAC,GAAG,IAAI,IAAI,CAAC,CAAC;IACvD,IAAI,KAAK,KAAK,CAAC,CAAC;QAAE,KAAK,GAAG,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;IAC3C,6EAA6E;IAC7E,IACE,KAAK,GAAG,CAAC;QACT,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,KAAK,GAAG,KAAK,CAAC,KAAK,CAAE,CAAC,IAAI,CAAC,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,KAAK,EAC1E,CAAC;QACD,KAAK,IAAI,CAAC,CAAC;IACb,CAAC;IACD,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC,KAAK,CAAE,CAAC;IACvC,MAAM,MAAM,GAAG,GAAG,WAAW,CAAC,KAAK,GAAG,IAAI,EAAE,SAAS,CAAC,GAAG,MAAM,EAAE,CAAC;IAElE,OAAO,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,MAAM,GAAG,IAAI,KAAK,GAAG,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,EAAE,CAAC;AAC7E,CAAC,CAAC;AAnBW,QAAA,mBAAmB,uBAmB9B","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\n// Compact numeric formatting, shared by anything that has to fit a number into\n// a small space — chart axis labels, a `compact` structured display value, a\n// text-surface trend line.\n\nconst TIERS = [\n { size: 1_000_000_000_000, suffix: 't' },\n { size: 1_000_000_000, suffix: 'b' },\n { size: 1_000_000, suffix: 'm' },\n { size: 1_000, suffix: 'k' },\n { size: 1, suffix: '' },\n] as const;\n\n// Rounded to `precision` decimals, trailing zeros dropped.\nconst trimDecimal = (value: number, precision: number): string =>\n Number.isInteger(value)\n ? String(value)\n : String(Number(value.toFixed(precision)));\n\n/**\n * `1_284` to `1.3k`, `18_200_000` to `18.2m`, through `b` and `t`, with an\n * optional unit appended. `precision` is the decimals kept, `1` by default.\n *\n * `%` joins without a space because \"99.2 %\" reads wrong; every other unit gets\n * one.\n */\nexport const formatCompactNumber = (\n value: number,\n unit = '',\n precision = 1\n): string => {\n const abs = Math.abs(value);\n let index = TIERS.findIndex(({ size }) => abs >= size);\n if (index === -1) index = TIERS.length - 1;\n // A value that rounds up to the tier's next power, `999.96k`, reads as `1m`.\n if (\n index > 0 &&\n Math.abs(Number((value / TIERS[index]!.size).toFixed(precision))) >= 1_000\n ) {\n index -= 1;\n }\n const { size, suffix } = TIERS[index]!;\n const scaled = `${trimDecimal(value / size, precision)}${suffix}`;\n\n return unit === '' ? scaled : `${scaled}${unit === '%' ? '' : ' '}${unit}`;\n};\n"]}
1
+ {"version":3,"file":"format_number.js","sourceRoot":"","sources":["../../../src/render/format_number.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,+EAA+E;AAC/E,6EAA6E;AAC7E,2BAA2B;AAE3B,MAAM,KAAK,GAAG;IACZ,EAAE,IAAI,EAAE,iBAAiB,EAAE,MAAM,EAAE,GAAG,EAAE;IACxC,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE;IACpC,EAAE,IAAI,EAAE,SAAS,EAAE,MAAM,EAAE,GAAG,EAAE;IAChC,EAAE,IAAI,EAAE,KAAK,EAAE,MAAM,EAAE,GAAG,EAAE;IAC5B,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE,EAAE,EAAE;CACf,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AC,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,IAAI,EAAE,CAAC;AAC7E,CAAC,CAAC;AArBW,QAAA,mBAAmB,uBAqB9B","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\n// Compact numeric formatting, shared by anything that has to fit a number into\n// a small space — chart axis labels, a `compact` structured display value, a\n// text-surface trend line.\n\nconst TIERS = [\n { size: 1_000_000_000_000, suffix: 't' },\n { size: 1_000_000_000, suffix: 'b' },\n { size: 1_000_000, suffix: 'm' },\n { size: 1_000, suffix: 'k' },\n { size: 1, suffix: '' },\n] as const;\n\n// Rounded to `precision` decimals, trailing zeros dropped.\nconst trimDecimal = (value: number, precision: number): string =>\n Number.isInteger(value)\n ? String(value)\n : String(Number(value.toFixed(precision)));\n\n/**\n * `1_284` to `1.3k`, `18_200_000` to `18.2m`, through `b` and `t`, with an\n * optional unit appended. `precision` is the decimals kept, `1` by default.\n *\n * `%` joins without a space because \"99.2 %\" reads wrong; every other unit gets\n * one.\n */\nexport const formatCompactNumber = (\n value: number,\n unit = '',\n precision = 1\n): string => {\n const abs = Math.abs(value);\n let index = TIERS.findIndex(({ size }) => abs >= size);\n if (index === -1) {\n index = TIERS.length - 1;\n }\n // A value that rounds up to the tier's next power, `999.96k`, reads as `1m`.\n if (\n index > 0 &&\n Math.abs(Number((value / TIERS[index]!.size).toFixed(precision))) >= 1_000\n ) {\n index -= 1;\n }\n const { size, suffix } = TIERS[index]!;\n const scaled = `${trimDecimal(value / size, precision)}${suffix}`;\n\n return unit === '' ? scaled : `${scaled}${unit === '%' ? '' : ' '}${unit}`;\n};\n"]}
@@ -112,8 +112,9 @@ exports.renderHTMLWithDispatcher = renderHTMLWithDispatcher;
112
112
  const embedCss = (css) => css.replace(/<\/(?=style)/gi, '<\\/');
113
113
  // Tagged templates observe raw spelling and reuse the same frozen object per site.
114
114
  const embedJs = (js) => {
115
- if (!/<\/script|<!--/i.test(js))
115
+ if (!/<\/script|<!--/i.test(js)) {
116
116
  return js;
117
+ }
117
118
  const comments = [];
118
119
  const tree = (0, acorn_1.parse)(js, { ecmaVersion: 'latest', onComment: comments });
119
120
  const sites = [];
@@ -121,11 +122,13 @@ const embedJs = (js) => {
121
122
  const pending = [tree];
122
123
  while (pending.length) {
123
124
  const node = pending.pop();
124
- if (node.type === 'Identifier' && node.name)
125
+ if (node.type === 'Identifier' && node.name) {
125
126
  identifiers.add(node.name);
127
+ }
126
128
  if (node.type === 'TaggedTemplateExpression' &&
127
- node.quasi.quasis.some(({ value: { raw } }) => /<\/script|<!--/i.test(raw)))
129
+ node.quasi.quasis.some(({ value: { raw } }) => /<\/script|<!--/i.test(raw))) {
128
130
  sites.push(node);
131
+ }
129
132
  for (const value of Object.values(node)) {
130
133
  for (const child of Array.isArray(value) ? value : [value]) {
131
134
  if (child &&
@@ -139,8 +142,9 @@ const embedJs = (js) => {
139
142
  }
140
143
  sites.sort((a, b) => a.start - b.start);
141
144
  let prefix = '__isomerTemplate';
142
- while ([...identifiers].some((name) => name.startsWith(prefix)))
145
+ while ([...identifiers].some((name) => name.startsWith(prefix))) {
143
146
  prefix += '_';
147
+ }
144
148
  const literal = (value) => value === null ? 'void 0' : JSON.stringify(value).replace(/</g, '\\u003c');
145
149
  const rewrite = (start, end) => {
146
150
  let cursor = start;
@@ -156,8 +160,9 @@ const embedJs = (js) => {
156
160
  .map((comment) => ({ ...comment, index: -1, comment: comment.value })),
157
161
  ].sort((a, b) => a.start - b.start);
158
162
  for (const edit of edits) {
159
- if (edit.start < cursor || edit.end > end)
163
+ if (edit.start < cursor || edit.end > end) {
160
164
  continue;
165
+ }
161
166
  result += js.slice(cursor, edit.start);
162
167
  if (edit.comment !== undefined) {
163
168
  result += `//${edit.comment}`;
@@ -188,8 +193,9 @@ const embedJs = (js) => {
188
193
  };
189
194
  const escapedBy = (source, at) => {
190
195
  let slashes = 0;
191
- while (source[at - slashes - 1] === '\\')
196
+ while (source[at - slashes - 1] === '\\') {
192
197
  slashes += 1;
198
+ }
193
199
  return slashes % 2 === 1;
194
200
  };
195
201
  const RenderedHtmlView = ({ composition, theme, fluid, framed, styleText, scriptText, defaultAriaLabel, body, }) => (0, content_1.wrapCompositionContent)((0, react_1.createElement)(react_1.Fragment, null, styleText
@@ -1 +1 @@
1
- {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../../src/render/html/envelope.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,iCAAgE;AAChE,6CAAwD;AACxD,iCAIe;AAEf,qEAG0C;AAY1C,0DAIiC;AACjC,0DAMmC;AACnC,wCAAyC;AACzC,kDAA8C;AAC9C,wCAAiE;AACjE,8CAI0B;AAE1B,iDAIwB;AAqNxB;;;;;;;GAOG;AACI,MAAM,wBAAwB,GAAG,CAKtC,KAAyB,EACzB,EACE,UAAU,EACV,QAAQ,GAAG,IAAA,uCAA0B,EAAQ,UAAU,CAAC,WAAW,CAAC,EACpE,OAAO,EAAE,UAAU,GAAG,EAAE,EACxB,gBAAgB,GAAG,MAAM,EACzB,YAAY,EACZ,UAAU,GAAG,EAAE,EACf,sBAAsB,GAAG,EAAE,GAC8B,EACzC,EAAE;IACpB,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IACnC,MAAM,WAAW,GAAG,IAAA,gCAAmB,EAAC,UAAU,CAAC,CAAC;IACpD,wEAAwE;IACxE,uBAAuB;IACvB,MAAM,OAAO,GACX,YAAY,EAAE,cAAc,EAAE,CAAC,WAAW,EAAE,UAAU,CAAC,IAAI,UAAU,CAAC;IACxE,IAAA,kCAAqB,EAAC,UAAU,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;IACtC,MAAM,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC;IACxC,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;IACR,CAAC,CAAC,IAAA,qBAAa,EAAC,QAAQ,EAAE;QACtB,GAAG,EAAE,QAAQ;QACb,CAAC,wCAAyB,CAAC,EAAE,EAAE;QAC/B,uBAAuB,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE;KAChD,CAAC;IACJ,CAAC,CAAC,IAAI,CACT,EACD,WAAW,EACX,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAC3C,CAAC;AAEJ,4EAA4E;AAC5E,yEAAyE;AACzE,6EAA6E;AAC7E,6CAA6C;AAC7C,MAAM,SAAS,GACb,2EAA2E,CAAC;AAE9E,MAAM,UAAU,GAAG,CAAC,KAAa,EAAU,EAAE,CAC3C,KAAK;KACF,OAAO,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,OAA2B,EAAE,EAAE,CACzD,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAC9C;KACA,IAAI,EAAE,CAAC","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport { createElement, Fragment, type ReactNode } from 'react';\nimport { renderToStaticMarkup } from 'react-dom/server';\nimport {\n type Comment as JavaScriptComment,\n type Node as JavaScriptNode,\n parse,\n} from 'acorn';\n\nimport {\n type ChildNodeWalker,\n createChildNodeWalker,\n} from '../../composition/body_node_base';\nimport type { Composition } from '../../composition/composition';\nimport type { RenderTheme } from '../../composition/named_color';\nimport type { ValidationError } from '../../composition/validation_error';\nimport type {\n AnyPrimitiveDefinition,\n PrimitiveNode,\n PrimitiveStyleCollectionContext,\n PrimitiveStyleCollector,\n StyledRenderContext,\n StyleHandle,\n} from '../../define/primitive_module';\nimport {\n EMBEDDED_SCRIPT_ATTRIBUTE,\n resolveEnhancements,\n scopeScript,\n} from '../../pack/enhancements';\nimport {\n type CheckedValidationResult,\n compositionToRender,\n createCompositionValidator,\n enforceValidationMode,\n type ValidationErrorMode,\n} from '../../validate/validation';\nimport { withAnchors } from '../anchors';\nimport { contextWith } from '../context_view';\nimport { byteLength, type PayloadMeasurement } from '../payload';\nimport {\n type ReactContentDispatcher,\n renderCompositionContent,\n wrapCompositionContent,\n} from '../react/content';\n\nimport {\n embedScript,\n type EnhancementDefinition,\n enhancementScript,\n} from './enhancements';\n\n/** Knobs for the HTML surface. Every field defaults, so `{}` is valid. */\nexport interface HTMLRenderOptions {\n /** Overrides {@link Composition.theme}; `auto` when neither is set. */\n theme?: RenderTheme;\n /** Drops whitespace between tags that spans a line break, leaving `<pre>`, `<script>`, `<style>`, and `<textarea>` content intact. Defaults to `true`. */\n minify?: boolean;\n /** Adds the `fluid` wrapper class and reaches the pack as {@link PrimitiveStyleCollectionContext.fluid}; the adapter decides what it changes. */\n fluid?: boolean;\n /** Adds the `framed` wrapper class the adapter styles as a frame. Defaults to `true`. */\n framed?: boolean;\n /**\n * Renders the composition's title and subtitle. Defaults to `true`. Set\n * `false` when the embedding host already shows the title itself — the title\n * still backs the wrapper's `aria-label`.\n */\n heading?: boolean;\n /** Whether the collected CSS is inlined as a `<style>` element. Defaults to `'inline'`. */\n css?: 'inline' | 'separate';\n /**\n * Who runs the enhancement script. Defaults to `'embedded'`: `html` carries\n * a `<script>` that finds its own `.isomer` section when the page parses it.\n *\n * `'embedded'` never runs inside a shadow root, or anywhere the host inserts\n * `html` itself (`innerHTML`, a React tree). Use `'host'` there: `html`\n * carries no `<script>`, and the host calls `runEnhancementScript(js,\n * section)` after inserting it.\n */\n scripts?: 'embedded' | 'host';\n /** Defaults to collecting into {@link HTMLRenderResult.validationErrors}; `'throw'` raises instead. Input the budget refused raises in either mode. */\n onValidationError?: ValidationErrorMode;\n /** Opt-in by {@link EnhancementDefinition.id}. One whose content gate does not match the body is dropped. */\n enhancements?: readonly string[];\n /** `true` renders node anchors whether or not an enhancement asks for them, e.g. for tests. `false` cannot turn off anchors an enhancement needs. */\n anchors?: boolean;\n /**\n * Resolves `light-dark(…)` in the stylesheet to one scheme's value. A browser\n * resolves it itself; an image is one static frame, so the `svg` surface sets\n * it.\n */\n scheme?: 'light' | 'dark';\n}\n\n/**\n * One rendered HTML payload.\n *\n * `body` is the primitive markup alone; `html` adds the wrapper element, on\n * the default `css: 'inline'` a `<style>`, and on the default\n * `scripts: 'embedded'` a `<script>`. `css` and `js` are populated either way.\n * `validationErrors` are the messages that survived\n * {@link HTMLRenderOptions.onValidationError}.\n */\nexport interface HTMLRenderResult {\n html: string;\n css: string;\n /**\n * The enhancement script as a function body over `root`, or `''`. Under\n * `scripts: 'embedded'` the `<script>` in `html` wraps the same body; under\n * `'host'` the host runs it with `runEnhancementScript`. It is never a\n * complete script on its own.\n */\n js: string;\n body: string;\n measurement: PayloadMeasurement;\n validationErrors: ValidationError[];\n}\n\n/**\n * A pack's HTML entry point: the React renderer plus the style pass that runs\n * ahead of it.\n */\nexport interface HTMLRenderDispatcher<\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> extends ReactContentDispatcher<TNode, TContext> {\n /** The whole composition's inventory: a child walker built from one pack's definitions cannot descend into another pack's container. */\n readonly definitions: readonly AnyPrimitiveDefinition[];\n /** One node's style pass, driven by {@link HTMLStyleAdapter.collectViewStyles} rather than called by the sdk. */\n collectStyles(\n node: TNode,\n collector: TCollector,\n context: PrimitiveStyleCollectionContext\n ): void;\n}\n\n/**\n * The composition's child walker and the enhancements every loaded pack\n * declared. Threaded into the style adapter so content-gating can see a\n * table nested inside a container from another package.\n */\nexport interface HTMLEnhancementScope {\n walk: ChildNodeWalker;\n definitions: readonly EnhancementDefinition[];\n}\n\n/**\n * How a pack turns its nodes into CSS. Optional overall — without an adapter\n * the render still produces markup, just with no class names and an empty\n * `TContext`.\n */\nexport interface HTMLStyleAdapter<\n TNode extends PrimitiveNode = PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> {\n /**\n * Names the collector shape {@link HTMLStyleAdapter.createCollector} returns, so a runtime can\n * reject a pack whose `collectStyles` hooks were written against a different one.\n */\n styleCollector?: string;\n /** One collector per render, shared by every other hook here and by both render passes. */\n createCollector(options: HTMLRenderOptions): TCollector;\n /**\n * Settles options that depend on the composition, before anything reads them.\n *\n * Needed by an adapter whose look is chosen per render: deciding `framed`\n * from the body has to happen before the wrapper class is written, not while\n * CSS is collected.\n */\n resolveOptions?(\n composition: Composition<TNode>,\n options: HTMLRenderOptions\n ): HTMLRenderOptions;\n /**\n * The `.isomer` / `.isomer.framed` / `.isomer.fluid` rules around a rendered composition.\n * Named for the wrapper rather than the frame, which the sdk reserves for a\n * pack's svg document surround.\n */\n collectWrapperStyles?(\n collector: TCollector,\n options: HTMLRenderOptions\n ): void;\n /** Walks the body into the collector, usually through {@link HTMLRenderDispatcher.collectStyles}. Runs before any markup exists. */\n collectViewStyles?(\n composition: Composition<TNode>,\n dispatcher: HTMLRenderDispatcher<TNode, TCollector, TContext>,\n collector: TCollector,\n context: PrimitiveStyleCollectionContext,\n options: HTMLRenderOptions,\n scope: HTMLEnhancementScope\n ): void;\n /** Runs once the collection pass has rendered the body, for styles only a renderer can discover. That markup is discarded. */\n collectAfterRender?(\n composition: Composition<TNode>,\n collector: TCollector,\n options: HTMLRenderOptions\n ): void;\n /**\n * Builds the render context handed to every `react` renderer. Called once\n * per pass, so an adapter that behaves differently while collecting returns\n * a different context then. Must be complete, because `TContext` is the\n * pack's own type. The sdk never writes to it: whether renderers anchor\n * is the surface's decision, whatever the context's `anchors` says.\n */\n createRenderContext(\n collector: TCollector,\n options: HTMLRenderOptions\n ): TContext;\n /** The collected CSS as text, with no `<style>` wrapper; the sdk adds one when `css` is `'inline'`. */\n renderStyles(collector: TCollector, options: HTMLRenderOptions): string;\n /**\n * Whether `handle` belongs to this adapter's stylesheet.\n *\n * Unused on a lone adapter. A runtime composing several packs' adapters\n * routes each handle to its owner, so CSS is neither duplicated nor\n * rendered against the wrong theme. An adapter that cannot answer this\n * cannot be combined with another.\n */\n ownsHandle?(handle: StyleHandle): boolean;\n /**\n * Appended after {@link HTMLDispatcherRenderOptions.scriptText} into the\n * render's one script. A function body with `root` in scope, under the same\n * rules as {@link EnhancementDefinition.script}.\n */\n getScriptText?(\n composition: Composition<TNode>,\n options: HTMLRenderOptions,\n scope: HTMLEnhancementScope\n ): string;\n}\n\n/** What {@link renderHTMLWithDispatcher} needs beyond the composition. */\nexport interface HTMLDispatcherRenderOptions<\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> {\n dispatcher: HTMLRenderDispatcher<TNode, TCollector, TContext>;\n /** Runs once before rendering, which draws the composition it returns; {@link HTMLRenderOptions.onValidationError} decides what becomes of its errors. Defaults to `createCompositionValidator(dispatcher.definitions)`. */\n validate?: (\n composition: Composition<TNode>\n ) => CheckedValidationResult<TNode>;\n options?: HTMLRenderOptions;\n /** Used only when the composition has neither `meta.ariaLabel` nor a `title`. Defaults to `'View'`. */\n defaultAriaLabel?: string;\n styleAdapter?: HTMLStyleAdapter<TNode, TCollector, TContext>;\n /**\n * Emitted unescaped ahead of {@link HTMLStyleAdapter.getScriptText}. A\n * function body with `root` in scope, under the same rules as\n * {@link EnhancementDefinition.script}.\n */\n scriptText?: string;\n /**\n * Progressive enhancements declared by the packs this render was composed\n * from. The render resolves {@link HTMLRenderOptions.enhancements} against\n * them once, hands every renderer the set as `context.enhancements`, and\n * emits each resolved one's script.\n */\n enhancementDefinitions?: readonly EnhancementDefinition[];\n}\n\n/**\n * Renders a composition to standalone HTML: the wrapper element, the pack's\n * markup, and its CSS either inlined or returned separately.\n *\n * Runs the pack twice when a style adapter is present — once to collect\n * styles, once with the render context those styles produced — so a\n * `renderReact` implementation must be free of side effects.\n */\nexport const renderHTMLWithDispatcher = <\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n>(\n input: Composition<TNode>,\n {\n dispatcher,\n validate = createCompositionValidator<TNode>(dispatcher.definitions),\n options: rawOptions = {},\n defaultAriaLabel = 'View',\n styleAdapter,\n scriptText = '',\n enhancementDefinitions = [],\n }: HTMLDispatcherRenderOptions<TNode, TCollector, TContext>\n): HTMLRenderResult => {\n const validation = validate(input);\n const composition = compositionToRender(validation);\n // Resolved before the validation mode is read, so an adapter can derive\n // `onValidationError`.\n const options =\n styleAdapter?.resolveOptions?.(composition, rawOptions) ?? rawOptions;\n enforceValidationMode(validation, options.onValidationError);\n const framed = options.framed ?? true;\n const heading = options.heading ?? true;\n const theme = options.theme ?? composition.theme ?? 'auto';\n const cssMode = options.css ?? 'inline';\n const scriptsMode = options.scripts ?? 'embedded';\n const styleState = styleAdapter?.createCollector(options);\n const enhancementScope: HTMLEnhancementScope = {\n walk: createChildNodeWalker(dispatcher.definitions),\n definitions: enhancementDefinitions,\n };\n const applied = resolveEnhancements(\n composition.body,\n enhancementScope.walk,\n enhancementDefinitions,\n options.enhancements ?? []\n );\n const enhancements: ReadonlySet<string> = new Set(\n applied.map(({ id }) => id)\n );\n const anchors =\n options.anchors === true || applied.some(({ anchors }) => anchors);\n const enhanced = (context: TContext): TContext =>\n contextWith(context, 'enhancements', enhancements);\n\n if (styleState) {\n styleAdapter?.collectWrapperStyles?.(styleState, options);\n styleAdapter?.collectViewStyles?.(\n composition,\n dispatcher,\n styleState,\n { fluid: Boolean(options.fluid) },\n options,\n enhancementScope\n );\n const collectionContext = enhanced(\n styleAdapter?.createRenderContext(styleState, options) as TContext\n );\n withAnchors(anchors, () =>\n renderToStaticMarkup(\n createElement(() =>\n renderCompositionContent(composition, dispatcher, collectionContext, {\n heading,\n })\n )\n )\n );\n styleAdapter?.collectAfterRender?.(composition, styleState, options);\n }\n\n const renderContext = enhanced(\n styleState && styleAdapter\n ? styleAdapter.createRenderContext(styleState, options)\n : // No adapter means no class names and no css vars to resolve.\n ({} as TContext)\n );\n const cssText =\n styleState && styleAdapter\n ? styleAdapter.renderStyles(styleState, options)\n : '';\n const adapterScriptText =\n styleAdapter?.getScriptText?.(composition, options, enhancementScope) ?? '';\n const js = [\n ...[scriptText, adapterScriptText].filter(Boolean).map(scopeScript),\n enhancementScript(applied),\n ]\n .filter(Boolean)\n .join('\\n');\n const embeddedScript =\n js && scriptsMode === 'embedded' ? embedScript(js) : '';\n const body = withAnchors(anchors, () =>\n renderToStaticMarkup(\n createElement(() =>\n renderCompositionContent(composition, dispatcher, renderContext, {\n heading,\n })\n )\n )\n );\n const inlineCss = cssMode === 'inline' ? embedCss(cssText) : '';\n const inlineJs = embeddedScript ? embedJs(embeddedScript) : '';\n const raw = renderToStaticMarkup(\n createElement(RenderedHtmlView<TNode>, {\n composition,\n theme,\n fluid: Boolean(options.fluid),\n framed,\n styleText: inlineCss || undefined,\n scriptText: inlineJs || undefined,\n defaultAriaLabel,\n body,\n })\n );\n const html = options.minify === false ? raw : minifyHtml(raw);\n\n // Inline payloads are measured as emitted, escapes included.\n const inlineCssBytes = byteLength(inlineCss);\n const inlineJsBytes = byteLength(inlineJs);\n const separateCssBytes = cssMode === 'inline' ? 0 : byteLength(cssText);\n const separateJsBytes = embeddedScript ? 0 : byteLength(js);\n\n return {\n html,\n css: cssText,\n js,\n body,\n measurement: {\n html: byteLength(html) - inlineCssBytes - inlineJsBytes,\n css: inlineCssBytes + separateCssBytes,\n js: inlineJsBytes + separateJsBytes,\n total: byteLength(html) + separateCssBytes + separateJsBytes,\n },\n validationErrors: validation.errors,\n };\n};\n\ninterface RenderedHtmlViewProps<TNode extends PrimitiveNode> {\n composition: Composition<TNode>;\n theme: RenderTheme;\n fluid: boolean;\n framed: boolean;\n styleText?: string | undefined;\n scriptText?: string | undefined;\n defaultAriaLabel: string;\n body: string;\n}\n\n// Only `</style` ends a `<style>`. `\\/` is a CSS escape for `/`, so a string\n// holding it keeps its value.\nconst embedCss = (css: string): string => css.replace(/<\\/(?=style)/gi, '<\\\\/');\n\ninterface ScriptNode extends JavaScriptNode {\n tag: ScriptNode;\n quasi: ScriptNode;\n quasis: ScriptNode[];\n expressions: ScriptNode[];\n value: { raw: string; cooked: string | null };\n name?: string;\n}\n\n// Tagged templates observe raw spelling and reuse the same frozen object per site.\nconst embedJs = (js: string): string => {\n if (!/<\\/script|<!--/i.test(js)) return js;\n const comments: JavaScriptComment[] = [];\n const tree = parse(js, { ecmaVersion: 'latest', onComment: comments });\n const sites: ScriptNode[] = [];\n const identifiers = new Set<string>();\n const pending: JavaScriptNode[] = [tree];\n while (pending.length) {\n const node = pending.pop()! as ScriptNode;\n if (node.type === 'Identifier' && node.name) identifiers.add(node.name);\n if (\n node.type === 'TaggedTemplateExpression' &&\n node.quasi.quasis.some(({ value: { raw } }) =>\n /<\\/script|<!--/i.test(raw)\n )\n )\n sites.push(node);\n for (const value of Object.values(node)) {\n for (const child of Array.isArray(value) ? value : [value]) {\n if (\n child &&\n typeof child === 'object' &&\n 'type' in child &&\n 'start' in child\n ) {\n pending.push(child as JavaScriptNode);\n }\n }\n }\n }\n sites.sort((a, b) => a.start - b.start);\n let prefix = '__isomerTemplate';\n while ([...identifiers].some((name) => name.startsWith(prefix)))\n prefix += '_';\n const literal = (value: string | null): string =>\n value === null ? 'void 0' : JSON.stringify(value).replace(/</g, '\\\\u003c');\n const rewrite = (start: number, end: number): string => {\n let cursor = start;\n let result = '';\n const edits = [\n ...sites.map((site, index) => ({\n ...site,\n index,\n comment: undefined as string | undefined,\n })),\n ...comments\n .filter(({ start }) => /^(?:<!--|-->)/.test(js.slice(start, start + 4)))\n .map((comment) => ({ ...comment, index: -1, comment: comment.value })),\n ].sort((a, b) => a.start - b.start);\n for (const edit of edits) {\n if (edit.start < cursor || edit.end > end) continue;\n result += js.slice(cursor, edit.start);\n if (edit.comment !== undefined) {\n result += `//${edit.comment}`;\n } else {\n const site = sites[edit.index]!;\n const {\n tag,\n quasi: { quasis, expressions },\n } = site;\n const cooked = quasis\n .map(({ value }) => literal(value.cooked))\n .join(',');\n const raw = quasis.map(({ value }) => literal(value.raw)).join(',');\n const cache = `${prefix}${edit.index}`;\n const template = `${cache} ??= ${prefix}Freeze(${prefix}Define([${cooked}], 'raw', {value:${prefix}Freeze([${raw}])}))`;\n const args = expressions.map((expression) =>\n rewrite(expression.start, expression.end)\n );\n result += `(${rewrite(tag.start, tag.end)})(${template}${args.map((arg) => `,(${arg})`).join('')})`;\n }\n cursor = edit.end;\n }\n return result + js.slice(cursor, end);\n };\n const rewritten = rewrite(0, js.length);\n const scoped = sites.length\n ? `(function(){const ${prefix}Freeze=Object.freeze,${prefix}Define=Object.defineProperty;let ${sites.map((_site, index) => `${prefix}${index}`).join(',')};\\n${rewritten}\\n})();`\n : rewritten;\n return scoped\n .replace(/<\\/(?=script)/gi, '<\\\\/')\n .replace(/<!--/g, (_match, at: number, source: string) =>\n escapedBy(source, at) ? 'x3C!--' : '\\\\x3C!--'\n );\n};\n\nconst escapedBy = (source: string, at: number): boolean => {\n let slashes = 0;\n while (source[at - slashes - 1] === '\\\\') slashes += 1;\n return slashes % 2 === 1;\n};\n\nconst RenderedHtmlView = <TNode extends PrimitiveNode>({\n composition,\n theme,\n fluid,\n framed,\n styleText,\n scriptText,\n defaultAriaLabel,\n body,\n}: RenderedHtmlViewProps<TNode>): ReactNode =>\n wrapCompositionContent(\n createElement(\n Fragment,\n null,\n styleText\n ? createElement('style', {\n key: 'style',\n dangerouslySetInnerHTML: { __html: styleText },\n })\n : null,\n createElement('div', {\n key: 'body',\n dangerouslySetInnerHTML: { __html: body },\n }),\n scriptText\n ? createElement('script', {\n key: 'script',\n [EMBEDDED_SCRIPT_ATTRIBUTE]: '',\n dangerouslySetInnerHTML: { __html: scriptText },\n })\n : null\n ),\n composition,\n { framed, fluid, theme, defaultAriaLabel }\n );\n\n// Whitespace inside `pre`, `script`, `style`, and `textarea` is content, so\n// those elements match whole and pass through. Elsewhere only whitespace\n// spanning a line break is collapsed: a single space between inline elements\n// (`<b>a</b> <i>b</i>`) is authored content.\nconst MINIFY_RE =\n /<(pre|script|style|textarea)[\\s>][\\s\\S]*?(?:<\\/\\1\\s*>|$)|(?<=>)\\s+(?=<)/gi;\n\nconst minifyHtml = (value: string): string =>\n value\n .replace(MINIFY_RE, (match, element: string | undefined) =>\n element || !match.includes('\\n') ? match : ''\n )\n .trim();\n"]}
1
+ {"version":3,"file":"envelope.js","sourceRoot":"","sources":["../../../../src/render/html/envelope.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAEH,iCAAgE;AAChE,6CAAwD;AACxD,iCAIe;AAEf,qEAG0C;AAY1C,0DAIiC;AACjC,0DAMmC;AACnC,wCAAyC;AACzC,kDAA8C;AAC9C,wCAAiE;AACjE,8CAI0B;AAE1B,iDAIwB;AAqNxB;;;;;;;GAOG;AACI,MAAM,wBAAwB,GAAG,CAKtC,KAAyB,EACzB,EACE,UAAU,EACV,QAAQ,GAAG,IAAA,uCAA0B,EAAQ,UAAU,CAAC,WAAW,CAAC,EACpE,OAAO,EAAE,UAAU,GAAG,EAAE,EACxB,gBAAgB,GAAG,MAAM,EACzB,YAAY,EACZ,UAAU,GAAG,EAAE,EACf,sBAAsB,GAAG,EAAE,GAC8B,EACzC,EAAE;IACpB,MAAM,UAAU,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IACnC,MAAM,WAAW,GAAG,IAAA,gCAAmB,EAAC,UAAU,CAAC,CAAC;IACpD,wEAAwE;IACxE,uBAAuB;IACvB,MAAM,OAAO,GACX,YAAY,EAAE,cAAc,EAAE,CAAC,WAAW,EAAE,UAAU,CAAC,IAAI,UAAU,CAAC;IACxE,IAAA,kCAAqB,EAAC,UAAU,EAAE,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAC7D,MAAM,MAAM,GAAG,OAAO,CAAC,MAAM,IAAI,IAAI,CAAC;IACtC,MAAM,OAAO,GAAG,OAAO,C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KAC/C,CAAC;IACJ,CAAC,CAAC,IAAI,EACR,IAAA,qBAAa,EAAC,KAAK,EAAE;IACnB,GAAG,EAAE,MAAM;IACX,uBAAuB,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE;CAC1C,CAAC,EACF,UAAU;IACR,CAAC,CAAC,IAAA,qBAAa,EAAC,QAAQ,EAAE;QACtB,GAAG,EAAE,QAAQ;QACb,CAAC,wCAAyB,CAAC,EAAE,EAAE;QAC/B,uBAAuB,EAAE,EAAE,MAAM,EAAE,UAAU,EAAE;KAChD,CAAC;IACJ,CAAC,CAAC,IAAI,CACT,EACD,WAAW,EACX,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,gBAAgB,EAAE,CAC3C,CAAC;AAEJ,4EAA4E;AAC5E,yEAAyE;AACzE,6EAA6E;AAC7E,6CAA6C;AAC7C,MAAM,SAAS,GACb,2EAA2E,CAAC;AAE9E,MAAM,UAAU,GAAG,CAAC,KAAa,EAAU,EAAE,CAC3C,KAAK;KACF,OAAO,CAAC,SAAS,EAAE,CAAC,KAAK,EAAE,OAA2B,EAAE,EAAE,CACzD,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,CAC9C;KACA,IAAI,EAAE,CAAC","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport { createElement, Fragment, type ReactNode } from 'react';\nimport { renderToStaticMarkup } from 'react-dom/server';\nimport {\n type Comment as JavaScriptComment,\n type Node as JavaScriptNode,\n parse,\n} from 'acorn';\n\nimport {\n type ChildNodeWalker,\n createChildNodeWalker,\n} from '../../composition/body_node_base';\nimport type { Composition } from '../../composition/composition';\nimport type { RenderTheme } from '../../composition/named_color';\nimport type { ValidationError } from '../../composition/validation_error';\nimport type {\n AnyPrimitiveDefinition,\n PrimitiveNode,\n PrimitiveStyleCollectionContext,\n PrimitiveStyleCollector,\n StyledRenderContext,\n StyleHandle,\n} from '../../define/primitive_module';\nimport {\n EMBEDDED_SCRIPT_ATTRIBUTE,\n resolveEnhancements,\n scopeScript,\n} from '../../pack/enhancements';\nimport {\n type CheckedValidationResult,\n compositionToRender,\n createCompositionValidator,\n enforceValidationMode,\n type ValidationErrorMode,\n} from '../../validate/validation';\nimport { withAnchors } from '../anchors';\nimport { contextWith } from '../context_view';\nimport { byteLength, type PayloadMeasurement } from '../payload';\nimport {\n type ReactContentDispatcher,\n renderCompositionContent,\n wrapCompositionContent,\n} from '../react/content';\n\nimport {\n embedScript,\n type EnhancementDefinition,\n enhancementScript,\n} from './enhancements';\n\n/** Knobs for the HTML surface. Every field defaults, so `{}` is valid. */\nexport interface HTMLRenderOptions {\n /** Overrides {@link Composition.theme}; `auto` when neither is set. */\n theme?: RenderTheme;\n /** Drops whitespace between tags that spans a line break, leaving `<pre>`, `<script>`, `<style>`, and `<textarea>` content intact. Defaults to `true`. */\n minify?: boolean;\n /** Adds the `fluid` wrapper class and reaches the pack as {@link PrimitiveStyleCollectionContext.fluid}; the adapter decides what it changes. */\n fluid?: boolean;\n /** Adds the `framed` wrapper class the adapter styles as a frame. Defaults to `true`. */\n framed?: boolean;\n /**\n * Renders the composition's title and subtitle. Defaults to `true`. Set\n * `false` when the embedding host already shows the title itself — the title\n * still backs the wrapper's `aria-label`.\n */\n heading?: boolean;\n /** Whether the collected CSS is inlined as a `<style>` element. Defaults to `'inline'`. */\n css?: 'inline' | 'separate';\n /**\n * Who runs the enhancement script. Defaults to `'embedded'`: `html` carries\n * a `<script>` that finds its own `.isomer` section when the page parses it.\n *\n * `'embedded'` never runs inside a shadow root, or anywhere the host inserts\n * `html` itself (`innerHTML`, a React tree). Use `'host'` there: `html`\n * carries no `<script>`, and the host calls `runEnhancementScript(js,\n * section)` after inserting it.\n */\n scripts?: 'embedded' | 'host';\n /** Defaults to collecting into {@link HTMLRenderResult.validationErrors}; `'throw'` raises instead. Input the budget refused raises in either mode. */\n onValidationError?: ValidationErrorMode;\n /** Opt-in by {@link EnhancementDefinition.id}. One whose content gate does not match the body is dropped. */\n enhancements?: readonly string[];\n /** `true` renders node anchors whether or not an enhancement asks for them, e.g. for tests. `false` cannot turn off anchors an enhancement needs. */\n anchors?: boolean;\n /**\n * Resolves `light-dark(…)` in the stylesheet to one scheme's value. A browser\n * resolves it itself; an image is one static frame, so the `snapshot` surface sets\n * it.\n */\n scheme?: 'light' | 'dark';\n}\n\n/**\n * One rendered HTML payload.\n *\n * `body` is the primitive markup alone; `html` adds the wrapper element, on\n * the default `css: 'inline'` a `<style>`, and on the default\n * `scripts: 'embedded'` a `<script>`. `css` and `js` are populated either way.\n * `validationErrors` are the messages that survived\n * {@link HTMLRenderOptions.onValidationError}.\n */\nexport interface HTMLRenderResult {\n html: string;\n css: string;\n /**\n * The enhancement script as a function body over `root`, or `''`. Under\n * `scripts: 'embedded'` the `<script>` in `html` wraps the same body; under\n * `'host'` the host runs it with `runEnhancementScript`. It is never a\n * complete script on its own.\n */\n js: string;\n body: string;\n measurement: PayloadMeasurement;\n validationErrors: ValidationError[];\n}\n\n/**\n * A pack's HTML entry point: the React renderer plus the style pass that runs\n * ahead of it.\n */\nexport interface HTMLRenderDispatcher<\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> extends ReactContentDispatcher<TNode, TContext> {\n /** The whole composition's inventory: a child walker built from one pack's definitions cannot descend into another pack's container. */\n readonly definitions: readonly AnyPrimitiveDefinition[];\n /** One node's style pass, driven by {@link HTMLStyleAdapter.collectViewStyles} rather than called by the sdk. */\n collectStyles(\n node: TNode,\n collector: TCollector,\n context: PrimitiveStyleCollectionContext\n ): void;\n}\n\n/**\n * The composition's child walker and the enhancements every loaded pack\n * declared. Threaded into the style adapter so content-gating can see a\n * table nested inside a container from another package.\n */\nexport interface HTMLEnhancementScope {\n walk: ChildNodeWalker;\n definitions: readonly EnhancementDefinition[];\n}\n\n/**\n * How a pack turns its nodes into CSS. Optional overall — without an adapter\n * the render still produces markup, just with no class names and an empty\n * `TContext`.\n */\nexport interface HTMLStyleAdapter<\n TNode extends PrimitiveNode = PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> {\n /**\n * Names the collector shape {@link HTMLStyleAdapter.createCollector} returns, so a runtime can\n * reject a pack whose `collectStyles` hooks were written against a different one.\n */\n styleCollector?: string;\n /** One collector per render, shared by every other hook here and by both render passes. */\n createCollector(options: HTMLRenderOptions): TCollector;\n /**\n * Settles options that depend on the composition, before anything reads them.\n *\n * Needed by an adapter whose look is chosen per render: deciding `framed`\n * from the body has to happen before the wrapper class is written, not while\n * CSS is collected.\n */\n resolveOptions?(\n composition: Composition<TNode>,\n options: HTMLRenderOptions\n ): HTMLRenderOptions;\n /**\n * The `.isomer` / `.isomer.framed` / `.isomer.fluid` rules around a rendered composition.\n * Named for the wrapper rather than the frame, which the sdk reserves for the\n * document a snapshot is drawn inside.\n */\n collectWrapperStyles?(\n collector: TCollector,\n options: HTMLRenderOptions\n ): void;\n /** Walks the body into the collector, usually through {@link HTMLRenderDispatcher.collectStyles}. Runs before any markup exists. */\n collectViewStyles?(\n composition: Composition<TNode>,\n dispatcher: HTMLRenderDispatcher<TNode, TCollector, TContext>,\n collector: TCollector,\n context: PrimitiveStyleCollectionContext,\n options: HTMLRenderOptions,\n scope: HTMLEnhancementScope\n ): void;\n /** Runs once the collection pass has rendered the body, for styles only a renderer can discover. That markup is discarded. */\n collectAfterRender?(\n composition: Composition<TNode>,\n collector: TCollector,\n options: HTMLRenderOptions\n ): void;\n /**\n * Builds the render context handed to every `react` renderer. Called once\n * per pass, so an adapter that behaves differently while collecting returns\n * a different context then. Must be complete, because `TContext` is the\n * pack's own type. The sdk never writes to it: whether renderers anchor\n * is the surface's decision, whatever the context's `anchors` says.\n */\n createRenderContext(\n collector: TCollector,\n options: HTMLRenderOptions\n ): TContext;\n /** The collected CSS as text, with no `<style>` wrapper; the sdk adds one when `css` is `'inline'`. */\n renderStyles(collector: TCollector, options: HTMLRenderOptions): string;\n /**\n * Whether `handle` belongs to this adapter's stylesheet.\n *\n * Unused on a lone adapter. A runtime composing several packs' adapters\n * routes each handle to its owner, so CSS is neither duplicated nor\n * rendered against the wrong theme. An adapter that cannot answer this\n * cannot be combined with another.\n */\n ownsHandle?(handle: StyleHandle): boolean;\n /**\n * Appended after {@link HTMLDispatcherRenderOptions.scriptText} into the\n * render's one script. A function body with `root` in scope, under the same\n * rules as {@link EnhancementDefinition.script}.\n */\n getScriptText?(\n composition: Composition<TNode>,\n options: HTMLRenderOptions,\n scope: HTMLEnhancementScope\n ): string;\n}\n\n/** What {@link renderHTMLWithDispatcher} needs beyond the composition. */\nexport interface HTMLDispatcherRenderOptions<\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n> {\n dispatcher: HTMLRenderDispatcher<TNode, TCollector, TContext>;\n /** Runs once before rendering, which draws the composition it returns; {@link HTMLRenderOptions.onValidationError} decides what becomes of its errors. Defaults to `createCompositionValidator(dispatcher.definitions)`. */\n validate?: (\n composition: Composition<TNode>\n ) => CheckedValidationResult<TNode>;\n options?: HTMLRenderOptions;\n /** Used only when the composition has neither `meta.ariaLabel` nor a `title`. Defaults to `'View'`. */\n defaultAriaLabel?: string;\n styleAdapter?: HTMLStyleAdapter<TNode, TCollector, TContext>;\n /**\n * Emitted unescaped ahead of {@link HTMLStyleAdapter.getScriptText}. A\n * function body with `root` in scope, under the same rules as\n * {@link EnhancementDefinition.script}.\n */\n scriptText?: string;\n /**\n * Progressive enhancements declared by the packs this render was composed\n * from. The render resolves {@link HTMLRenderOptions.enhancements} against\n * them once, hands every renderer the set as `context.enhancements`, and\n * emits each resolved one's script.\n */\n enhancementDefinitions?: readonly EnhancementDefinition[];\n}\n\n/**\n * Renders a composition to standalone HTML: the wrapper element, the pack's\n * markup, and its CSS either inlined or returned separately.\n *\n * Runs the pack twice when a style adapter is present — once to collect\n * styles, once with the render context those styles produced — so a\n * `renderReact` implementation must be free of side effects.\n */\nexport const renderHTMLWithDispatcher = <\n TNode extends PrimitiveNode,\n TCollector extends PrimitiveStyleCollector = PrimitiveStyleCollector,\n TContext = StyledRenderContext,\n>(\n input: Composition<TNode>,\n {\n dispatcher,\n validate = createCompositionValidator<TNode>(dispatcher.definitions),\n options: rawOptions = {},\n defaultAriaLabel = 'View',\n styleAdapter,\n scriptText = '',\n enhancementDefinitions = [],\n }: HTMLDispatcherRenderOptions<TNode, TCollector, TContext>\n): HTMLRenderResult => {\n const validation = validate(input);\n const composition = compositionToRender(validation);\n // Resolved before the validation mode is read, so an adapter can derive\n // `onValidationError`.\n const options =\n styleAdapter?.resolveOptions?.(composition, rawOptions) ?? rawOptions;\n enforceValidationMode(validation, options.onValidationError);\n const framed = options.framed ?? true;\n const heading = options.heading ?? true;\n const theme = options.theme ?? composition.theme ?? 'auto';\n const cssMode = options.css ?? 'inline';\n const scriptsMode = options.scripts ?? 'embedded';\n const styleState = styleAdapter?.createCollector(options);\n const enhancementScope: HTMLEnhancementScope = {\n walk: createChildNodeWalker(dispatcher.definitions),\n definitions: enhancementDefinitions,\n };\n const applied = resolveEnhancements(\n composition.body,\n enhancementScope.walk,\n enhancementDefinitions,\n options.enhancements ?? []\n );\n const enhancements: ReadonlySet<string> = new Set(\n applied.map(({ id }) => id)\n );\n const anchors =\n options.anchors === true || applied.some(({ anchors }) => anchors);\n const enhanced = (context: TContext): TContext =>\n contextWith(context, 'enhancements', enhancements);\n\n if (styleState) {\n styleAdapter?.collectWrapperStyles?.(styleState, options);\n styleAdapter?.collectViewStyles?.(\n composition,\n dispatcher,\n styleState,\n { fluid: Boolean(options.fluid) },\n options,\n enhancementScope\n );\n const collectionContext = enhanced(\n styleAdapter?.createRenderContext(styleState, options) as TContext\n );\n withAnchors(anchors, () =>\n renderToStaticMarkup(\n createElement(() =>\n renderCompositionContent(composition, dispatcher, collectionContext, {\n heading,\n })\n )\n )\n );\n styleAdapter?.collectAfterRender?.(composition, styleState, options);\n }\n\n const renderContext = enhanced(\n styleState && styleAdapter\n ? styleAdapter.createRenderContext(styleState, options)\n : // No adapter means no class names and no css vars to resolve.\n ({} as TContext)\n );\n const cssText =\n styleState && styleAdapter\n ? styleAdapter.renderStyles(styleState, options)\n : '';\n const adapterScriptText =\n styleAdapter?.getScriptText?.(composition, options, enhancementScope) ?? '';\n const js = [\n ...[scriptText, adapterScriptText].filter(Boolean).map(scopeScript),\n enhancementScript(applied),\n ]\n .filter(Boolean)\n .join('\\n');\n const embeddedScript =\n js && scriptsMode === 'embedded' ? embedScript(js) : '';\n const body = withAnchors(anchors, () =>\n renderToStaticMarkup(\n createElement(() =>\n renderCompositionContent(composition, dispatcher, renderContext, {\n heading,\n })\n )\n )\n );\n const inlineCss = cssMode === 'inline' ? embedCss(cssText) : '';\n const inlineJs = embeddedScript ? embedJs(embeddedScript) : '';\n const raw = renderToStaticMarkup(\n createElement(RenderedHtmlView<TNode>, {\n composition,\n theme,\n fluid: Boolean(options.fluid),\n framed,\n styleText: inlineCss || undefined,\n scriptText: inlineJs || undefined,\n defaultAriaLabel,\n body,\n })\n );\n const html = options.minify === false ? raw : minifyHtml(raw);\n\n // Inline payloads are measured as emitted, escapes included.\n const inlineCssBytes = byteLength(inlineCss);\n const inlineJsBytes = byteLength(inlineJs);\n const separateCssBytes = cssMode === 'inline' ? 0 : byteLength(cssText);\n const separateJsBytes = embeddedScript ? 0 : byteLength(js);\n\n return {\n html,\n css: cssText,\n js,\n body,\n measurement: {\n html: byteLength(html) - inlineCssBytes - inlineJsBytes,\n css: inlineCssBytes + separateCssBytes,\n js: inlineJsBytes + separateJsBytes,\n total: byteLength(html) + separateCssBytes + separateJsBytes,\n },\n validationErrors: validation.errors,\n };\n};\n\ninterface RenderedHtmlViewProps<TNode extends PrimitiveNode> {\n composition: Composition<TNode>;\n theme: RenderTheme;\n fluid: boolean;\n framed: boolean;\n styleText?: string | undefined;\n scriptText?: string | undefined;\n defaultAriaLabel: string;\n body: string;\n}\n\n// Only `</style` ends a `<style>`. `\\/` is a CSS escape for `/`, so a string\n// holding it keeps its value.\nconst embedCss = (css: string): string => css.replace(/<\\/(?=style)/gi, '<\\\\/');\n\ninterface ScriptNode extends JavaScriptNode {\n tag: ScriptNode;\n quasi: ScriptNode;\n quasis: ScriptNode[];\n expressions: ScriptNode[];\n value: { raw: string; cooked: string | null };\n name?: string;\n}\n\n// Tagged templates observe raw spelling and reuse the same frozen object per site.\nconst embedJs = (js: string): string => {\n if (!/<\\/script|<!--/i.test(js)) {\n return js;\n }\n const comments: JavaScriptComment[] = [];\n const tree = parse(js, { ecmaVersion: 'latest', onComment: comments });\n const sites: ScriptNode[] = [];\n const identifiers = new Set<string>();\n const pending: JavaScriptNode[] = [tree];\n while (pending.length) {\n const node = pending.pop()! as ScriptNode;\n if (node.type === 'Identifier' && node.name) {\n identifiers.add(node.name);\n }\n if (\n node.type === 'TaggedTemplateExpression' &&\n node.quasi.quasis.some(({ value: { raw } }) =>\n /<\\/script|<!--/i.test(raw)\n )\n ) {\n sites.push(node);\n }\n for (const value of Object.values(node)) {\n for (const child of Array.isArray(value) ? value : [value]) {\n if (\n child &&\n typeof child === 'object' &&\n 'type' in child &&\n 'start' in child\n ) {\n pending.push(child as JavaScriptNode);\n }\n }\n }\n }\n sites.sort((a, b) => a.start - b.start);\n let prefix = '__isomerTemplate';\n while ([...identifiers].some((name) => name.startsWith(prefix))) {\n prefix += '_';\n }\n const literal = (value: string | null): string =>\n value === null ? 'void 0' : JSON.stringify(value).replace(/</g, '\\\\u003c');\n const rewrite = (start: number, end: number): string => {\n let cursor = start;\n let result = '';\n const edits = [\n ...sites.map((site, index) => ({\n ...site,\n index,\n comment: undefined as string | undefined,\n })),\n ...comments\n .filter(({ start }) => /^(?:<!--|-->)/.test(js.slice(start, start + 4)))\n .map((comment) => ({ ...comment, index: -1, comment: comment.value })),\n ].sort((a, b) => a.start - b.start);\n for (const edit of edits) {\n if (edit.start < cursor || edit.end > end) {\n continue;\n }\n result += js.slice(cursor, edit.start);\n if (edit.comment !== undefined) {\n result += `//${edit.comment}`;\n } else {\n const site = sites[edit.index]!;\n const {\n tag,\n quasi: { quasis, expressions },\n } = site;\n const cooked = quasis\n .map(({ value }) => literal(value.cooked))\n .join(',');\n const raw = quasis.map(({ value }) => literal(value.raw)).join(',');\n const cache = `${prefix}${edit.index}`;\n const template = `${cache} ??= ${prefix}Freeze(${prefix}Define([${cooked}], 'raw', {value:${prefix}Freeze([${raw}])}))`;\n const args = expressions.map((expression) =>\n rewrite(expression.start, expression.end)\n );\n result += `(${rewrite(tag.start, tag.end)})(${template}${args.map((arg) => `,(${arg})`).join('')})`;\n }\n cursor = edit.end;\n }\n return result + js.slice(cursor, end);\n };\n const rewritten = rewrite(0, js.length);\n const scoped = sites.length\n ? `(function(){const ${prefix}Freeze=Object.freeze,${prefix}Define=Object.defineProperty;let ${sites.map((_site, index) => `${prefix}${index}`).join(',')};\\n${rewritten}\\n})();`\n : rewritten;\n return scoped\n .replace(/<\\/(?=script)/gi, '<\\\\/')\n .replace(/<!--/g, (_match, at: number, source: string) =>\n escapedBy(source, at) ? 'x3C!--' : '\\\\x3C!--'\n );\n};\n\nconst escapedBy = (source: string, at: number): boolean => {\n let slashes = 0;\n while (source[at - slashes - 1] === '\\\\') {\n slashes += 1;\n }\n return slashes % 2 === 1;\n};\n\nconst RenderedHtmlView = <TNode extends PrimitiveNode>({\n composition,\n theme,\n fluid,\n framed,\n styleText,\n scriptText,\n defaultAriaLabel,\n body,\n}: RenderedHtmlViewProps<TNode>): ReactNode =>\n wrapCompositionContent(\n createElement(\n Fragment,\n null,\n styleText\n ? createElement('style', {\n key: 'style',\n dangerouslySetInnerHTML: { __html: styleText },\n })\n : null,\n createElement('div', {\n key: 'body',\n dangerouslySetInnerHTML: { __html: body },\n }),\n scriptText\n ? createElement('script', {\n key: 'script',\n [EMBEDDED_SCRIPT_ATTRIBUTE]: '',\n dangerouslySetInnerHTML: { __html: scriptText },\n })\n : null\n ),\n composition,\n { framed, fluid, theme, defaultAriaLabel }\n );\n\n// Whitespace inside `pre`, `script`, `style`, and `textarea` is content, so\n// those elements match whole and pass through. Elsewhere only whitespace\n// spanning a line break is collapsed: a single space between inline elements\n// (`<b>a</b> <i>b</i>`) is authored content.\nconst MINIFY_RE =\n /<(pre|script|style|textarea)[\\s>][\\s\\S]*?(?:<\\/\\1\\s*>|$)|(?<=>)\\s+(?=<)/gi;\n\nconst minifyHtml = (value: string): string =>\n value\n .replace(MINIFY_RE, (match, element: string | undefined) =>\n element || !match.includes('\\n') ? match : ''\n )\n .trim();\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"layout_check.js","sourceRoot":"","sources":["../../../src/render/layout_check.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAIH,uCAMmB;AAsCnB,mDAAmD;AACnD,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,MAAM,QAAQ,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAa,EAAW,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;AAE9B,MAAM,OAAO,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,EAAc,EAAW,EAAE,CACzD,KAAK,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;AAE1B,+GAA+G;AAC/G,MAAM,aAAa,GAAG,CAAC,GAAc,EAAyB,EAAE;IAC9D,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC,+BAAqB,CAAC,CAAC;IACtD,OAAO;QACL,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,CAAwB,CAAC,CAAC;Q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EAAE,MAAM,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,IAAI,EAAE;wBAC9C,EAAE,EAAE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;qBACnB;iBACF;gBACH,CAAC,CAAC,EAAE,CAAC;QACT,CAAC,CAAC,CACH,CAAC;IACJ,CAAC,CAAC,CAAC;IAEH,OAAO,CAAC,GAAG,SAAS,EAAE,GAAG,QAAQ,CAAC,CAAC;AACrC,CAAC,CAAC;AArFW,QAAA,WAAW,eAqFtB","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport type { ChildNodeWalker } from '../composition/body_node_base';\n\nimport {\n anchoredNodePaths,\n LAYOUT_ROOM_ATTRIBUTE,\n NODE_ANCHOR_ATTRIBUTE,\n nodeType,\n pairAnchors,\n} from './anchors';\n\n/** A rectangle on the canvas, in pixels. */\nexport interface LayoutRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** A laid-out element and the elements nested in it, as a layout engine measures them. */\nexport interface LayoutBox extends LayoutRect {\n /** Absent means unscaled. */\n readonly scale?: number;\n /** Text laid out in the box. */\n readonly runs?: readonly LayoutRect[];\n /** Where a {@link NODE_ANCHOR_ATTRIBUTE} is read from. */\n readonly attributes?: Readonly<Record<string, string>>;\n readonly children: readonly LayoutBox[];\n}\n\n/** A node drawn past the room its container gives it, or onto a sibling, by `by` pixels. */\nexport interface LayoutFinding {\n kind: 'overflow' | 'overlap';\n /** In validation's form, e.g. `body[1].items[0]`. */\n path: string;\n type: string;\n /** The sibling an `overlap` lands on. */\n with?: { path: string; type: string };\n by: number;\n}\n\ninterface PlacedNode {\n box: LayoutBox;\n path: string;\n type: string;\n}\n\n// Sub-pixel rounding reads as overflow without it.\nconst tolerance = 1;\n\nconst isScaled = ({ scale = 1 }: LayoutBox): boolean =>\n Math.abs(scale - 1) > 0.001;\n\nconst hasArea = ({ width, height }: LayoutRect): boolean =>\n width > 0 && height > 0;\n\n/** Every anchored box, pre-order, including those inside a scaled box, so a type's count matches its nodes. */\nconst anchoredBoxes = (box: LayoutBox): [string, LayoutBox][] => {\n const value = box.attributes?.[NODE_ANCHOR_ATTRIBUTE];\n return [\n ...(value === undefined ? [] : [[value, box] as [string, LayoutBox]]),\n ...box.children.flatMap(anchoredBoxes),\n ];\n};\n\nconst roomBoxes = (box: LayoutBox): LayoutBox[] => [\n ...(box.attributes?.[LAYOUT_ROOM_ATTRIBUTE] === undefined ? [] : [box]),\n ...box.children.flatMap(roomBoxes),\n];\n\n/**\n * The element boxes a node's own content fills: its box and those under it,\n * down to the nodes nested in it. Text runs are left out because glyphs\n * overhang a tight line height; a scaled box counts as itself alone.\n */\nconst ownBoxes = (\n box: LayoutBox,\n nested: ReadonlySet<LayoutBox>\n): LayoutBox[] => [\n box,\n ...(isScaled(box)\n ? []\n : box.children.flatMap((child) =>\n nested.has(child) ? [] : ownBoxes(child, nested)\n )),\n];\n\n/** What a box paints: its text, or itself when it holds nothing else, like a dot or a rule. */\nconst painted = (box: LayoutBox): LayoutRect[] => {\n if (isScaled(box)) {\n return [box];\n }\n const own =\n box.runs && box.runs.length > 0\n ? box.runs\n : box.children.length === 0\n ? [box]\n : [];\n return [...own.filter(hasArea), ...box.children.flatMap(painted)];\n};\n\nconst pastRoom = (room: LayoutRect, { x, y, width, height }: LayoutRect) =>\n Math.max(\n room.x - x,\n room.y - y,\n x + width - (room.x + room.width),\n y + height - (room.y + room.height)\n );\n\n/** How far `a` and `b` would have to move apart, along one axis, to clear each other. */\nconst overlapOf = (a: LayoutRect, b: LayoutRect): number => {\n const width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);\n const height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);\n if (width <= tolerance || height <= tolerance) {\n return 0;\n }\n return Math.min(\n a.x + a.width - b.x,\n b.x + b.width - a.x,\n a.y + a.height - b.y,\n b.y + b.height - a.y\n );\n};\n\n/**\n * Where the nodes of `body` run past their room or onto each other in\n * `layout`, a measured render on `surface` with node anchors on. Empty when\n * nothing does.\n *\n * A node's room is the box of its nearest anchored or `layoutRoom` ancestor,\n * or `layout` at the top level, and only siblings under one room are\n * compared. Nothing inside a scaled box is checked. A finding is advice, not an error:\n * an overlap may be intended.\n */\nexport const checkLayout = (\n layout: LayoutBox,\n body: readonly unknown[],\n walk: ChildNodeWalker,\n surface: 'react' | 'svg'\n): LayoutFinding[] => {\n const nodes = anchoredNodePaths(body, walk, surface);\n const anchored = anchoredBoxes(layout);\n const boxes = pairAnchors(\n anchored,\n nodes.map(({ node }) => node)\n );\n const placed = new Map<LayoutBox, PlacedNode>();\n boxes.forEach((box, index) => {\n const { node, path } = nodes[index]!;\n const type = nodeType(node);\n if (box !== undefined && type !== undefined) {\n placed.set(box, { box, path, type });\n }\n });\n\n // Every anchored box bounds its ancestors' content, paired or not.\n const nested = new Set(anchored.map(([, box]) => box));\n const bounding = new Set([...nested, ...roomBoxes(layout)]);\n const rooms = new Map<PlacedNode, LayoutBox>();\n const siblings = new Map<LayoutBox | undefined, PlacedNode[]>();\n const visit = (box: LayoutBox, parent: LayoutBox | undefined): void => {\n const node = placed.get(box);\n if (node !== undefined) {\n rooms.set(node, parent ?? layout);\n siblings.set(parent, [...(siblings.get(parent) ?? []), node]);\n }\n if (!isScaled(box)) {\n box.children.forEach((child) =>\n visit(child, bounding.has(box) ? box : parent)\n );\n }\n };\n visit(layout, undefined);\n\n const overflows = [...rooms].flatMap(([node, room]): LayoutFinding[] => {\n const by = Math.max(\n 0,\n ...ownBoxes(node.box, nested)\n .filter(hasArea)\n .map((box) => pastRoom(room, box))\n );\n return by > tolerance\n ? [\n {\n kind: 'overflow',\n path: node.path,\n type: node.type,\n by: Math.round(by),\n },\n ]\n : [];\n });\n\n const overlaps = [...siblings.values()].flatMap((group) => {\n const paints = group.map(({ box }) => painted(box));\n return group.flatMap((first, i) =>\n group.slice(i + 1).flatMap((second, offset): LayoutFinding[] => {\n const by = Math.max(\n 0,\n ...paints[i]!.flatMap((a) =>\n paints[i + 1 + offset]!.map((b) => overlapOf(a, b))\n )\n );\n return by > 0\n ? [\n {\n kind: 'overlap',\n path: first.path,\n type: first.type,\n with: { path: second.path, type: second.type },\n by: Math.round(by),\n },\n ]\n : [];\n })\n );\n });\n\n return [...overflows, ...overlaps];\n};\n"]}
1
+ {"version":3,"file":"layout_check.js","sourceRoot":"","sources":["../../../src/render/layout_check.ts"],"names":[],"mappings":";AAAA;;;;;GAKG;;;AAIH,uCAMmB;AAsCnB,mDAAmD;AACnD,MAAM,SAAS,GAAG,CAAC,CAAC;AAEpB,MAAM,QAAQ,GAAG,CAAC,EAAE,KAAK,GAAG,CAAC,EAAa,EAAW,EAAE,CACrD,IAAI,CAAC,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,KAAK,CAAC;AAE9B,MAAM,OAAO,GAAG,CAAC,EAAE,KAAK,EAAE,MAAM,EAAc,EAAW,EAAE,CACzD,KAAK,GAAG,CAAC,IAAI,MAAM,GAAG,CAAC,CAAC;AAE1B,+GAA+G;AAC/G,MAAM,aAAa,GAAG,CAAC,GAAc,EAAyB,EAAE;IAC9D,MAAM,KAAK,GAAG,GAAG,CAAC,UAAU,EAAE,CAAC,+BAAqB,CAAC,CAAC;IACtD,OAAO;QACL,GAAG,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,GAAG,CAAwB,CAAC,CAAC;QACrE,GAAG,GAAG,CAAC,QAAQ,CAAC,OAAO,CAAC,aAAa,CAAC;KACvC,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,SAAS,GAAG,CAAC,GAAc,EAAe,EAAE,CAAC;IACjD,GAAG,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC,+BAAqB,CAAC,KAAK,SAAS,CAAC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,OAAO,CAAC,GAAG,SAAS,EAAE,GAAG,QAAQ,CAAC,CAAC;AACrC,CAAC,CAAC;AArFW,QAAA,WAAW,eAqFtB","sourcesContent":["/*\n * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one\n * or more contributor license agreements. Licensed under the Elastic License\n * 2.0; you may not use this file except in compliance with the Elastic License\n * 2.0.\n */\n\nimport type { ChildNodeWalker } from '../composition/body_node_base';\n\nimport {\n anchoredNodePaths,\n LAYOUT_ROOM_ATTRIBUTE,\n NODE_ANCHOR_ATTRIBUTE,\n nodeType,\n pairAnchors,\n} from './anchors';\n\n/** A rectangle on the canvas, in pixels. */\nexport interface LayoutRect {\n readonly x: number;\n readonly y: number;\n readonly width: number;\n readonly height: number;\n}\n\n/** A laid-out element and the elements nested in it, as a layout engine measures them. */\nexport interface LayoutBox extends LayoutRect {\n /** Absent means unscaled. */\n readonly scale?: number;\n /** Text laid out in the box. */\n readonly runs?: readonly LayoutRect[];\n /** Where a {@link NODE_ANCHOR_ATTRIBUTE} is read from. */\n readonly attributes?: Readonly<Record<string, string>>;\n readonly children: readonly LayoutBox[];\n}\n\n/** A node drawn past the room its container gives it, or onto a sibling, by `by` pixels. */\nexport interface LayoutFinding {\n kind: 'overflow' | 'overlap';\n /** In validation's form, e.g. `body[1].items[0]`. */\n path: string;\n type: string;\n /** The sibling an `overlap` lands on. */\n with?: { path: string; type: string };\n by: number;\n}\n\ninterface PlacedNode {\n box: LayoutBox;\n path: string;\n type: string;\n}\n\n// Sub-pixel rounding reads as overflow without it.\nconst tolerance = 1;\n\nconst isScaled = ({ scale = 1 }: LayoutBox): boolean =>\n Math.abs(scale - 1) > 0.001;\n\nconst hasArea = ({ width, height }: LayoutRect): boolean =>\n width > 0 && height > 0;\n\n/** Every anchored box, pre-order, including those inside a scaled box, so a type's count matches its nodes. */\nconst anchoredBoxes = (box: LayoutBox): [string, LayoutBox][] => {\n const value = box.attributes?.[NODE_ANCHOR_ATTRIBUTE];\n return [\n ...(value === undefined ? [] : [[value, box] as [string, LayoutBox]]),\n ...box.children.flatMap(anchoredBoxes),\n ];\n};\n\nconst roomBoxes = (box: LayoutBox): LayoutBox[] => [\n ...(box.attributes?.[LAYOUT_ROOM_ATTRIBUTE] === undefined ? [] : [box]),\n ...box.children.flatMap(roomBoxes),\n];\n\n/**\n * The element boxes a node's own content fills: its box and those under it,\n * down to the nodes nested in it. Text runs are left out because glyphs\n * overhang a tight line height; a scaled box counts as itself alone.\n */\nconst ownBoxes = (\n box: LayoutBox,\n nested: ReadonlySet<LayoutBox>\n): LayoutBox[] => [\n box,\n ...(isScaled(box)\n ? []\n : box.children.flatMap((child) =>\n nested.has(child) ? [] : ownBoxes(child, nested)\n )),\n];\n\n/** What a box paints: its text, or itself when it holds nothing else, like a dot or a rule. */\nconst painted = (box: LayoutBox): LayoutRect[] => {\n if (isScaled(box)) {\n return [box];\n }\n const own =\n box.runs && box.runs.length > 0\n ? box.runs\n : box.children.length === 0\n ? [box]\n : [];\n return [...own.filter(hasArea), ...box.children.flatMap(painted)];\n};\n\nconst pastRoom = (room: LayoutRect, { x, y, width, height }: LayoutRect) =>\n Math.max(\n room.x - x,\n room.y - y,\n x + width - (room.x + room.width),\n y + height - (room.y + room.height)\n );\n\n/** How far `a` and `b` would have to move apart, along one axis, to clear each other. */\nconst overlapOf = (a: LayoutRect, b: LayoutRect): number => {\n const width = Math.min(a.x + a.width, b.x + b.width) - Math.max(a.x, b.x);\n const height = Math.min(a.y + a.height, b.y + b.height) - Math.max(a.y, b.y);\n if (width <= tolerance || height <= tolerance) {\n return 0;\n }\n return Math.min(\n a.x + a.width - b.x,\n b.x + b.width - a.x,\n a.y + a.height - b.y,\n b.y + b.height - a.y\n );\n};\n\n/**\n * Where the nodes of `body` run past their room or onto each other in\n * `layout`, a measured render on `surface` with node anchors on. Empty when\n * nothing does.\n *\n * A node's room is the box of its nearest anchored or `layoutRoom` ancestor,\n * or `layout` at the top level, and only siblings under one room are\n * compared. Nothing inside a scaled box is checked. A finding is advice, not an error:\n * an overlap may be intended.\n */\nexport const checkLayout = (\n layout: LayoutBox,\n body: readonly unknown[],\n walk: ChildNodeWalker,\n surface: 'react' | 'snapshot'\n): LayoutFinding[] => {\n const nodes = anchoredNodePaths(body, walk, surface);\n const anchored = anchoredBoxes(layout);\n const boxes = pairAnchors(\n anchored,\n nodes.map(({ node }) => node)\n );\n const placed = new Map<LayoutBox, PlacedNode>();\n boxes.forEach((box, index) => {\n const { node, path } = nodes[index]!;\n const type = nodeType(node);\n if (box !== undefined && type !== undefined) {\n placed.set(box, { box, path, type });\n }\n });\n\n // Every anchored box bounds its ancestors' content, paired or not.\n const nested = new Set(anchored.map(([, box]) => box));\n const bounding = new Set([...nested, ...roomBoxes(layout)]);\n const rooms = new Map<PlacedNode, LayoutBox>();\n const siblings = new Map<LayoutBox | undefined, PlacedNode[]>();\n const visit = (box: LayoutBox, parent: LayoutBox | undefined): void => {\n const node = placed.get(box);\n if (node !== undefined) {\n rooms.set(node, parent ?? layout);\n siblings.set(parent, [...(siblings.get(parent) ?? []), node]);\n }\n if (!isScaled(box)) {\n box.children.forEach((child) =>\n visit(child, bounding.has(box) ? box : parent)\n );\n }\n };\n visit(layout, undefined);\n\n const overflows = [...rooms].flatMap(([node, room]): LayoutFinding[] => {\n const by = Math.max(\n 0,\n ...ownBoxes(node.box, nested)\n .filter(hasArea)\n .map((box) => pastRoom(room, box))\n );\n return by > tolerance\n ? [\n {\n kind: 'overflow',\n path: node.path,\n type: node.type,\n by: Math.round(by),\n },\n ]\n : [];\n });\n\n const overlaps = [...siblings.values()].flatMap((group) => {\n const paints = group.map(({ box }) => painted(box));\n return group.flatMap((first, i) =>\n group.slice(i + 1).flatMap((second, offset): LayoutFinding[] => {\n const by = Math.max(\n 0,\n ...paints[i]!.flatMap((a) =>\n paints[i + 1 + offset]!.map((b) => overlapOf(a, b))\n )\n );\n return by > 0\n ? [\n {\n kind: 'overlap',\n path: first.path,\n type: first.type,\n with: { path: second.path, type: second.type },\n by: Math.round(by),\n },\n ]\n : [];\n })\n );\n });\n\n return [...overflows, ...overlaps];\n};\n"]}
@@ -6,7 +6,7 @@
6
6
  * 2.0.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.serializeMarkdown = exports.markdownBlocks = exports.markdownFromString = exports.md = exports.VERBATIM_TYPE = void 0;
9
+ exports.serializeMarkdown = exports.markdownBlocks = exports.printParsed = exports.md = exports.verbatim = exports.VERBATIM_TYPE = void 0;
10
10
  const mdast_util_gfm_1 = require("mdast-util-gfm");
11
11
  const mdast_util_to_markdown_1 = require("mdast-util-to-markdown");
12
12
  const one_line_1 = require("../../composition/one_line");
@@ -58,11 +58,15 @@ const isListStart = (start, count) => start !== undefined &&
58
58
  start >= 0 &&
59
59
  start + Math.max(count - 1, 0) <= MAX_LIST_NUMBER;
60
60
  // Printed as written, for Markdown that is already safe. Trailing whitespace
61
- // would add blank lines between blocks.
62
- const verbatim = (markdown) => block({
61
+ // would add blank lines between blocks. `source` is the authored text when
62
+ // sanitizing degraded it to inert text, whose escapes only Markdown resolves;
63
+ // surfaces that print literal text read it instead.
64
+ const verbatim = (markdown, source) => block({
63
65
  type: exports.VERBATIM_TYPE,
64
66
  value: markdown.trimEnd(),
67
+ ...(source === undefined ? {} : { source }),
65
68
  });
69
+ exports.verbatim = verbatim;
66
70
  // An empty wrapper prints its markers alone: `****` reads as a thematic break.
67
71
  const wrapper = (type, inputs) => {
68
72
  const children = inlineChildren(inputs);
@@ -147,12 +151,15 @@ exports.md = {
147
151
  : null,
148
152
  value,
149
153
  }),
150
- /** Authored Markdown source, after {@link sanitizeMarkdownSource}. */
151
- authored: (source) => verbatim((0, format_1.sanitizeMarkdownSource)(source)),
154
+ /** Authored Markdown source, after {@link sanitizeAuthoredSource}; whitespace-only source is dropped. */
155
+ authored: (source) => {
156
+ if (source.trim() === '') {
157
+ return [];
158
+ }
159
+ const { markdown, inert } = (0, format_1.sanitizeAuthoredSource)(source);
160
+ return (0, exports.verbatim)(markdown, inert ? source : undefined);
161
+ },
152
162
  };
153
- /** A renderer's string output as content, printed as written. */
154
- const markdownFromString = (markdown) => markdown.trim() === '' ? [] : verbatim(markdown);
155
- exports.markdownFromString = markdownFromString;
156
163
  const asText = (node, ...rest) => mdast_util_to_markdown_1.defaultHandlers.text({ type: 'text', value: node.value ?? node.alt ?? '' }, ...rest);
157
164
  // The URL policy again at serialization, for content built outside `md`.
158
165
  const handlers = {
@@ -180,6 +187,9 @@ const OPTIONS = {
180
187
  extensions: [(0, mdast_util_gfm_1.gfmToMarkdown)({ tablePipeAlign: false })],
181
188
  handlers: handlers,
182
189
  };
190
+ /** Parsed mdast blocks as GFM, unsanitized, for `md.authored` to sanitize as it sanitizes source. */
191
+ const printParsed = (nodes) => (0, mdast_util_to_markdown_1.toMarkdown)({ type: 'root', children: nodes }, { ...OPTIONS, handlers: {} }).replace(/\n$/, '');
192
+ exports.printParsed = printParsed;
183
193
  /** `content` as flat mdast blocks, typed `unknown` so no declaration names mdast. */
184
194
  const markdownBlocks = (content) => rootContent(content);
185
195
  exports.markdownBlocks = markdownBlocks;