@teleporthq/teleport-plugin-common 0.44.0-alpha.0 → 0.44.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (190) hide show
  1. package/__tests__/builders/html-builders.ts +9 -2
  2. package/__tests__/builders/style-builders.ts +23 -0
  3. package/__tests__/node-handlers/node-to-html/index.ts +2 -0
  4. package/__tests__/node-handlers/node-to-jsx/attribute-value-mapper.ts +77 -0
  5. package/__tests__/node-handlers/node-to-jsx/calendar-events-reviver.ts +176 -0
  6. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-ecommerce-source.ts +79 -0
  7. package/__tests__/node-handlers/node-to-jsx/cms-list-repeater-loading.ts +122 -0
  8. package/__tests__/node-handlers/node-to-jsx/index.ts +719 -3
  9. package/__tests__/node-handlers/node-to-jsx/url-search-params-expression.ts +59 -0
  10. package/__tests__/node-handlers/node-to-jsx/utils.ts +602 -3
  11. package/__tests__/utils/ast-utils.ts +188 -0
  12. package/__tests__/utils/content-property-sanitiser.ts +156 -0
  13. package/__tests__/utils/page-seeds-state-from-data-source.ts +70 -0
  14. package/__tests__/utils/parse-string-with-template-expressions.ts +82 -0
  15. package/__tests__/utils/resource-auth-scheme.ts +55 -0
  16. package/__tests__/utils/route-utils.ts +118 -0
  17. package/__tests__/utils/style-utils.ts +59 -0
  18. package/__tests__/utils/template-expression-balance.ts +83 -0
  19. package/__tests__/utils/url-query-writer.ts +239 -0
  20. package/__tests__/utils/url-search-param-sync.ts +138 -0
  21. package/__tests__/utils/url-search-params.ts +48 -0
  22. package/dist/cjs/builders/ast-builders.d.ts +2 -0
  23. package/dist/cjs/builders/ast-builders.d.ts.map +1 -1
  24. package/dist/cjs/builders/ast-builders.js +41 -3
  25. package/dist/cjs/builders/ast-builders.js.map +1 -1
  26. package/dist/cjs/builders/hast-builders.d.ts +1 -0
  27. package/dist/cjs/builders/hast-builders.d.ts.map +1 -1
  28. package/dist/cjs/builders/hast-builders.js +11 -1
  29. package/dist/cjs/builders/hast-builders.js.map +1 -1
  30. package/dist/cjs/builders/style-builders.d.ts +8 -2
  31. package/dist/cjs/builders/style-builders.d.ts.map +1 -1
  32. package/dist/cjs/builders/style-builders.js +65 -19
  33. package/dist/cjs/builders/style-builders.js.map +1 -1
  34. package/dist/cjs/index.d.ts +5 -1
  35. package/dist/cjs/index.d.ts.map +1 -1
  36. package/dist/cjs/index.js +9 -1
  37. package/dist/cjs/index.js.map +1 -1
  38. package/dist/cjs/node-handlers/node-to-html/constants.d.ts.map +1 -1
  39. package/dist/cjs/node-handlers/node-to-html/constants.js +2 -0
  40. package/dist/cjs/node-handlers/node-to-html/constants.js.map +1 -1
  41. package/dist/cjs/node-handlers/node-to-html/index.d.ts.map +1 -1
  42. package/dist/cjs/node-handlers/node-to-html/index.js +69 -1
  43. package/dist/cjs/node-handlers/node-to-html/index.js.map +1 -1
  44. package/dist/cjs/node-handlers/node-to-html/types.d.ts +5 -1
  45. package/dist/cjs/node-handlers/node-to-html/types.d.ts.map +1 -1
  46. package/dist/cjs/node-handlers/node-to-html/utils.d.ts +2 -1
  47. package/dist/cjs/node-handlers/node-to-html/utils.d.ts.map +1 -1
  48. package/dist/cjs/node-handlers/node-to-html/utils.js +174 -13
  49. package/dist/cjs/node-handlers/node-to-html/utils.js.map +1 -1
  50. package/dist/cjs/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  51. package/dist/cjs/node-handlers/node-to-jsx/index.js +1461 -66
  52. package/dist/cjs/node-handlers/node-to-jsx/index.js.map +1 -1
  53. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts +60 -6
  54. package/dist/cjs/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  55. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts +73 -7
  56. package/dist/cjs/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  57. package/dist/cjs/node-handlers/node-to-jsx/utils.js +864 -71
  58. package/dist/cjs/node-handlers/node-to-jsx/utils.js.map +1 -1
  59. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  60. package/dist/cjs/utils/ast-utils.d.ts +142 -11
  61. package/dist/cjs/utils/ast-utils.d.ts.map +1 -1
  62. package/dist/cjs/utils/ast-utils.js +931 -75
  63. package/dist/cjs/utils/ast-utils.js.map +1 -1
  64. package/dist/cjs/utils/hast-utils.d.ts +8 -6
  65. package/dist/cjs/utils/hast-utils.d.ts.map +1 -1
  66. package/dist/cjs/utils/hast-utils.js +28 -4
  67. package/dist/cjs/utils/hast-utils.js.map +1 -1
  68. package/dist/cjs/utils/route-utils.d.ts +117 -0
  69. package/dist/cjs/utils/route-utils.d.ts.map +1 -0
  70. package/dist/cjs/utils/route-utils.js +212 -0
  71. package/dist/cjs/utils/route-utils.js.map +1 -0
  72. package/dist/cjs/utils/style-utils.d.ts +1 -0
  73. package/dist/cjs/utils/style-utils.d.ts.map +1 -1
  74. package/dist/cjs/utils/style-utils.js +181 -2
  75. package/dist/cjs/utils/style-utils.js.map +1 -1
  76. package/dist/cjs/utils/template-expression-balance.d.ts +58 -0
  77. package/dist/cjs/utils/template-expression-balance.d.ts.map +1 -0
  78. package/dist/cjs/utils/template-expression-balance.js +181 -0
  79. package/dist/cjs/utils/template-expression-balance.js.map +1 -0
  80. package/dist/cjs/utils/types.d.ts +3 -0
  81. package/dist/cjs/utils/types.d.ts.map +1 -0
  82. package/dist/cjs/utils/types.js +3 -0
  83. package/dist/cjs/utils/types.js.map +1 -0
  84. package/dist/cjs/utils/url-query-writer.d.ts +123 -0
  85. package/dist/cjs/utils/url-query-writer.d.ts.map +1 -0
  86. package/dist/cjs/utils/url-query-writer.js +260 -0
  87. package/dist/cjs/utils/url-query-writer.js.map +1 -0
  88. package/dist/cjs/utils/url-search-param-sync.d.ts +4 -0
  89. package/dist/cjs/utils/url-search-param-sync.d.ts.map +1 -0
  90. package/dist/cjs/utils/url-search-param-sync.js +241 -0
  91. package/dist/cjs/utils/url-search-param-sync.js.map +1 -0
  92. package/dist/cjs/utils/url-search-params.d.ts +48 -0
  93. package/dist/cjs/utils/url-search-params.d.ts.map +1 -0
  94. package/dist/cjs/utils/url-search-params.js +109 -0
  95. package/dist/cjs/utils/url-search-params.js.map +1 -0
  96. package/dist/esm/builders/ast-builders.d.ts +2 -0
  97. package/dist/esm/builders/ast-builders.d.ts.map +1 -1
  98. package/dist/esm/builders/ast-builders.js +40 -4
  99. package/dist/esm/builders/ast-builders.js.map +1 -1
  100. package/dist/esm/builders/hast-builders.d.ts +1 -0
  101. package/dist/esm/builders/hast-builders.d.ts.map +1 -1
  102. package/dist/esm/builders/hast-builders.js +9 -0
  103. package/dist/esm/builders/hast-builders.js.map +1 -1
  104. package/dist/esm/builders/style-builders.d.ts +8 -2
  105. package/dist/esm/builders/style-builders.d.ts.map +1 -1
  106. package/dist/esm/builders/style-builders.js +63 -18
  107. package/dist/esm/builders/style-builders.js.map +1 -1
  108. package/dist/esm/index.d.ts +5 -1
  109. package/dist/esm/index.d.ts.map +1 -1
  110. package/dist/esm/index.js +5 -1
  111. package/dist/esm/index.js.map +1 -1
  112. package/dist/esm/node-handlers/node-to-html/constants.d.ts.map +1 -1
  113. package/dist/esm/node-handlers/node-to-html/constants.js +2 -0
  114. package/dist/esm/node-handlers/node-to-html/constants.js.map +1 -1
  115. package/dist/esm/node-handlers/node-to-html/index.d.ts.map +1 -1
  116. package/dist/esm/node-handlers/node-to-html/index.js +71 -3
  117. package/dist/esm/node-handlers/node-to-html/index.js.map +1 -1
  118. package/dist/esm/node-handlers/node-to-html/types.d.ts +5 -1
  119. package/dist/esm/node-handlers/node-to-html/types.d.ts.map +1 -1
  120. package/dist/esm/node-handlers/node-to-html/utils.d.ts +2 -1
  121. package/dist/esm/node-handlers/node-to-html/utils.d.ts.map +1 -1
  122. package/dist/esm/node-handlers/node-to-html/utils.js +170 -13
  123. package/dist/esm/node-handlers/node-to-html/utils.js.map +1 -1
  124. package/dist/esm/node-handlers/node-to-jsx/index.d.ts.map +1 -1
  125. package/dist/esm/node-handlers/node-to-jsx/index.js +1460 -68
  126. package/dist/esm/node-handlers/node-to-jsx/index.js.map +1 -1
  127. package/dist/esm/node-handlers/node-to-jsx/types.d.ts +60 -6
  128. package/dist/esm/node-handlers/node-to-jsx/types.d.ts.map +1 -1
  129. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts +73 -7
  130. package/dist/esm/node-handlers/node-to-jsx/utils.d.ts.map +1 -1
  131. package/dist/esm/node-handlers/node-to-jsx/utils.js +857 -69
  132. package/dist/esm/node-handlers/node-to-jsx/utils.js.map +1 -1
  133. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  134. package/dist/esm/utils/ast-utils.d.ts +142 -11
  135. package/dist/esm/utils/ast-utils.d.ts.map +1 -1
  136. package/dist/esm/utils/ast-utils.js +911 -75
  137. package/dist/esm/utils/ast-utils.js.map +1 -1
  138. package/dist/esm/utils/hast-utils.d.ts +8 -6
  139. package/dist/esm/utils/hast-utils.d.ts.map +1 -1
  140. package/dist/esm/utils/hast-utils.js +26 -3
  141. package/dist/esm/utils/hast-utils.js.map +1 -1
  142. package/dist/esm/utils/route-utils.d.ts +117 -0
  143. package/dist/esm/utils/route-utils.d.ts.map +1 -0
  144. package/dist/esm/utils/route-utils.js +179 -0
  145. package/dist/esm/utils/route-utils.js.map +1 -0
  146. package/dist/esm/utils/style-utils.d.ts +1 -0
  147. package/dist/esm/utils/style-utils.d.ts.map +1 -1
  148. package/dist/esm/utils/style-utils.js +179 -1
  149. package/dist/esm/utils/style-utils.js.map +1 -1
  150. package/dist/esm/utils/template-expression-balance.d.ts +58 -0
  151. package/dist/esm/utils/template-expression-balance.d.ts.map +1 -0
  152. package/dist/esm/utils/template-expression-balance.js +174 -0
  153. package/dist/esm/utils/template-expression-balance.js.map +1 -0
  154. package/dist/esm/utils/types.d.ts +3 -0
  155. package/dist/esm/utils/types.d.ts.map +1 -0
  156. package/dist/esm/utils/types.js +2 -0
  157. package/dist/esm/utils/types.js.map +1 -0
  158. package/dist/esm/utils/url-query-writer.d.ts +123 -0
  159. package/dist/esm/utils/url-query-writer.d.ts.map +1 -0
  160. package/dist/esm/utils/url-query-writer.js +229 -0
  161. package/dist/esm/utils/url-query-writer.js.map +1 -0
  162. package/dist/esm/utils/url-search-param-sync.d.ts +4 -0
  163. package/dist/esm/utils/url-search-param-sync.d.ts.map +1 -0
  164. package/dist/esm/utils/url-search-param-sync.js +213 -0
  165. package/dist/esm/utils/url-search-param-sync.js.map +1 -0
  166. package/dist/esm/utils/url-search-params.d.ts +48 -0
  167. package/dist/esm/utils/url-search-params.d.ts.map +1 -0
  168. package/dist/esm/utils/url-search-params.js +81 -0
  169. package/dist/esm/utils/url-search-params.js.map +1 -0
  170. package/package.json +4 -4
  171. package/src/builders/ast-builders.ts +80 -3
  172. package/src/builders/hast-builders.ts +11 -0
  173. package/src/builders/style-builders.ts +107 -27
  174. package/src/index.ts +18 -1
  175. package/src/node-handlers/node-to-html/constants.ts +2 -0
  176. package/src/node-handlers/node-to-html/index.ts +126 -6
  177. package/src/node-handlers/node-to-html/types.ts +6 -0
  178. package/src/node-handlers/node-to-html/utils.ts +228 -14
  179. package/src/node-handlers/node-to-jsx/index.ts +2219 -111
  180. package/src/node-handlers/node-to-jsx/types.ts +75 -32
  181. package/src/node-handlers/node-to-jsx/utils.ts +1142 -84
  182. package/src/utils/ast-utils.ts +1223 -127
  183. package/src/utils/hast-utils.ts +37 -9
  184. package/src/utils/route-utils.ts +214 -0
  185. package/src/utils/style-utils.ts +183 -1
  186. package/src/utils/template-expression-balance.ts +196 -0
  187. package/src/utils/types.ts +25 -0
  188. package/src/utils/url-query-writer.ts +318 -0
  189. package/src/utils/url-search-param-sync.ts +303 -0
  190. package/src/utils/url-search-params.ts +122 -0
@@ -1,25 +1,53 @@
1
- import { HastNode } from '@teleporthq/teleport-types'
1
+ import { HastNode, HastText } from '@teleporthq/teleport-types'
2
2
  import { createTextNode } from '../builders/hast-builders'
3
+ import type { JSXElement } from '@babel/types'
4
+ import { isJSXElement } from './ast-utils'
3
5
 
4
- export const addBooleanAttributeToNode = (node: HastNode, key: string, value: boolean = true) => {
6
+ export const addBooleanAttributeToNode = (
7
+ node: HastNode | HastNode[],
8
+ key: string,
9
+ value: boolean = true
10
+ ) => {
11
+ if (Array.isArray(node)) {
12
+ node.forEach((subnode) => (subnode.properties[key] = value === true ? '' : false))
13
+ return
14
+ }
5
15
  node.properties[key] = value === true ? '' : false
6
- /* adding empty string as @starptech/prettyhtml-hast-to-html which we are currently
7
- using for generating HTML supports boolean way of adding attributes only for HTML
8
- attributes but not for Vue*/
16
+ // Adding boolean attributes is currently onyl supported for template generators
9
17
  }
10
18
 
11
- export const addAttributeToNode = (node: HastNode, key: string, value: string) => {
19
+ export const addAttributeToNode = (node: HastNode | HastNode[], key: string, value: string) => {
20
+ if (Array.isArray(node)) {
21
+ node.forEach((subnode) => (subnode.properties[key] = value))
22
+ return
23
+ }
12
24
  node.properties[key] = value
13
25
  }
14
26
 
15
- export const addClassToNode = (node: HastNode, className: string) => {
27
+ export const addClassToNode = (node: HastNode | HastNode[], className: string) => {
28
+ if (Array.isArray(node)) {
29
+ node.forEach((subnode) => (subnode.properties.class = className))
30
+ return
31
+ }
16
32
  node.properties.class = className
17
33
  }
18
34
 
19
- export const addChildNode = (node: HastNode, child: HastNode) => {
35
+ export const addChildNode = (node: HastNode | HastNode[], child: HastNode | HastText) => {
36
+ if (Array.isArray(node)) {
37
+ node.forEach((subnode) => subnode.children.push(child))
38
+ return
39
+ }
20
40
  node.children.push(child)
21
41
  }
22
42
 
23
- export const addTextNode = (node: HastNode, text: string) => {
43
+ export const addTextNode = (node: HastNode | HastNode[], text: string) => {
44
+ if (Array.isArray(node)) {
45
+ node.forEach((subnode) => subnode.children.push(createTextNode(text)))
46
+ return
47
+ }
24
48
  node.children.push(createTextNode(text))
25
49
  }
50
+
51
+ export const isHastElement = (value: JSXElement | HastNode): value is HastNode =>
52
+ isJSXElement(value) === false &&
53
+ ('properties' in value || 'children' in value || 'tagName' in value)
@@ -0,0 +1,214 @@
1
+ import * as types from '@babel/types'
2
+ import { UIDLAuthentication, UIDLStateDefinition, UIDLWorkflows } from '@teleporthq/teleport-types'
3
+ import { RoutePaths, TableAccess } from '@teleporthq/teleport-shared'
4
+
5
+ /**
6
+ * True when this UIDL component's output route contains a Next.js dynamic
7
+ * segment (`[id]`, `[slug]`, ...) anywhere in its folder path or file name.
8
+ */
9
+ export const isDynamicRoute = (uidl: {
10
+ outputOptions?: { folderPath?: string[]; fileName?: string }
11
+ }): boolean => {
12
+ const { folderPath = [], fileName = '' } = uidl.outputOptions || {}
13
+ return [...folderPath, fileName].some(
14
+ (segment) => segment.startsWith('[') && segment.endsWith(']')
15
+ )
16
+ }
17
+
18
+ /**
19
+ * Reading a route TEMPLATE (`/event-details/[id]`) rather than a URL. Defined in
20
+ * teleport-shared because the navlink resolver needs the same two functions and
21
+ * lives in a package that does not depend on this one; re-exported here so
22
+ * `RouteUtils` stays the single import for route questions in the plugins.
23
+ */
24
+ export const { pathHasDynamicSegment, parseDynamicPathSegments } = RoutePaths
25
+
26
+ const MUTATION_NODE_TYPES = new Set(['data-create-item', 'data-update-item'])
27
+
28
+ /**
29
+ * True when this page both reads one specific database row via its own
30
+ * getStaticProps (`detailsPageInfo.tableName` — present on every details
31
+ * page, feature/admin/generic alike, regardless of the project's visual nav
32
+ * layout) AND has a workflow scoped to this page/an element on it that
33
+ * writes to that SAME table. That combination is the actual ISR hazard: a
34
+ * form on this page can just have written the exact row this page's own
35
+ * getStaticProps reads, and ISR would keep serving the pre-write snapshot
36
+ * for up to `cache.revalidate` seconds — a real, successful save silently
37
+ * looking "unsaved" on reload (the "Edit Press Item" bug). This is a
38
+ * data-correctness signal tied to what the page actually does, not a proxy
39
+ * for it — unlike a project-wide "dashboard vs standard" nav-layout choice,
40
+ * which has no bearing on whether any single page both reads and writes the
41
+ * same row (a `standard`-layout marketplace's "Edit Listing" page carries
42
+ * the identical risk; a `dashboard`-layout read-only report page carries
43
+ * none of it).
44
+ *
45
+ * Shared by `teleport-plugin-next-static-props` (decides getStaticProps vs
46
+ * getServerSideProps) and `teleport-plugin-next-static-paths` (decides
47
+ * whether to skip getStaticPaths) — both plugins must reach the exact same
48
+ * verdict for a given page, so the check lives here once instead of as two
49
+ * independently-maintained copies.
50
+ */
51
+ export const pageHasSameTableMutationWorkflow = (
52
+ uidl: {
53
+ name?: string
54
+ outputOptions?: {
55
+ pageId?: string
56
+ fileName?: string
57
+ detailsPageInfo?: { tableName?: string }
58
+ }
59
+ },
60
+ workflows?: UIDLWorkflows
61
+ ): boolean => {
62
+ const tableName = uidl.outputOptions?.detailsPageInfo?.tableName
63
+ if (!tableName || !workflows?.workflows) {
64
+ return false
65
+ }
66
+
67
+ const pageId = uidl.outputOptions?.pageId || uidl.outputOptions?.fileName || uidl.name || ''
68
+
69
+ return Object.values(workflows.workflows).some((wf) => {
70
+ const trigger = wf.trigger
71
+ if (!trigger || (trigger.scope !== 'page' && trigger.scope !== 'element')) {
72
+ return false
73
+ }
74
+
75
+ // Same page-matching semantics the runtime workflow plugin already uses
76
+ // (workflow-component-plugin.ts's getRelevantWorkflows): an empty/absent
77
+ // `selectedPages` means the trigger fires on every page it's attached to,
78
+ // a non-empty one restricts it to those pages.
79
+ const triggerPageId = trigger.config?.pageId as string | undefined
80
+ const selectedPages = trigger.config?.selectedPages as Array<{ id: string }> | undefined
81
+ const isScopedToThisPage =
82
+ trigger.scope === 'page'
83
+ ? !triggerPageId || triggerPageId === pageId
84
+ : !selectedPages || selectedPages.length === 0 || selectedPages.some((p) => p.id === pageId)
85
+
86
+ if (!isScopedToThisPage) {
87
+ return false
88
+ }
89
+
90
+ return wf.nodes.some(
91
+ (node) => MUTATION_NODE_TYPES.has(node.type) && node.config?.tableName === tableName
92
+ )
93
+ })
94
+ }
95
+
96
+ const collectResourceTables = (value: unknown, tables: Set<string>, seen: Set<unknown>): void => {
97
+ if (!value || typeof value !== 'object' || seen.has(value)) {
98
+ return
99
+ }
100
+ seen.add(value)
101
+ if (Array.isArray(value)) {
102
+ value.forEach((item) => collectResourceTables(item, tables, seen))
103
+ return
104
+ }
105
+ const record = value as Record<string, unknown>
106
+ const definition = record.resourceDefinition as { tableName?: unknown } | undefined
107
+ if (definition && typeof definition.tableName === 'string') {
108
+ tables.add(definition.tableName.trim().toLowerCase())
109
+ }
110
+ Object.keys(record).forEach((key) => collectResourceTables(record[key], tables, seen))
111
+ }
112
+
113
+ /**
114
+ * True when anything on this page reads a table that holds money, the keys
115
+ * to it, or the customers' own records (`TableAccess.PROTECTED_TABLES`: gift
116
+ * cards, vouchers, their ledgers, orders, accounts). Such a page renders per
117
+ * request. A statically generated one bakes codes, balances and addresses
118
+ * into the build output and keeps serving a balance the checkout has already
119
+ * spent until the next revalidation.
120
+ *
121
+ * Shared by the static-props and static-paths plugins and the page pipeline's
122
+ * getServerSideProps finalizer, which must all reach the same verdict.
123
+ */
124
+ export const pageReadsProtectedTable = (uidl: {
125
+ node?: unknown
126
+ outputOptions?: { detailsPageInfo?: { tableName?: string } }
127
+ }): boolean => {
128
+ const tables = new Set<string>()
129
+ const detailsTable = uidl.outputOptions?.detailsPageInfo?.tableName
130
+ if (typeof detailsTable === 'string') {
131
+ tables.add(detailsTable.trim().toLowerCase())
132
+ }
133
+ collectResourceTables(uidl.node, tables, new Set())
134
+ return TableAccess.PROTECTED_TABLES.some((table) => tables.has(table))
135
+ }
136
+
137
+ /**
138
+ * Any `{{…}}` template placeholder (`{{Current User.id}}`, `{{urlDifferentiator}}`).
139
+ * A state query carrying one can only be resolved in the browser, so the page's
140
+ * server data function never runs it — sending the literal placeholder to the
141
+ * database fails (`invalid input syntax for type uuid: "{{Current User.id}}"`).
142
+ */
143
+ const TEMPLATE_PLACEHOLDER = /\{\{[^}]+\}\}/
144
+
145
+ export const stateQueryHasTemplatePlaceholder = (definition: UIDLStateDefinition): boolean =>
146
+ typeof definition.query === 'string' && TEMPLATE_PLACEHOLDER.test(definition.query)
147
+
148
+ /**
149
+ * True when the page's own data function seeds a state from one of the
150
+ * project's data sources — a state bound to a table or a raw query that has no
151
+ * `{{…}}` placeholder. Such a page renders per request: those values have to be
152
+ * computed every time a visitor arrives, and a statically generated page hands a
153
+ * client-side navigation the copy Next.js cached in the browser (prefetched
154
+ * links included) or the one ISR rendered before the last write.
155
+ *
156
+ * Shared by the static-paths plugin and the page pipeline's getServerSideProps
157
+ * finalizer, which must reach the same verdict. The state data-source plugin
158
+ * splits states with the same `stateQueryHasTemplatePlaceholder` test.
159
+ */
160
+ export const pageSeedsStateFromDataSource = (
161
+ uidl: { stateDefinitions?: Record<string, UIDLStateDefinition> },
162
+ dataSources?: Record<string, unknown>
163
+ ): boolean =>
164
+ Object.values(uidl.stateDefinitions || {}).some(
165
+ (definition) =>
166
+ !!definition.dataSourceBinding &&
167
+ !!dataSources?.[definition.dataSourceBinding.dataSourceId] &&
168
+ !stateQueryHasTemplatePlaceholder(definition)
169
+ )
170
+
171
+ /**
172
+ * The path a page is served at, from where its file lands: `/admin/orders`
173
+ * for `pages/admin/orders.js`, `/` for the home page.
174
+ */
175
+ const pageRouteOf = (outputOptions?: { folderPath?: string[]; fileName?: string }): string => {
176
+ const { folderPath = [], fileName = '' } = outputOptions || {}
177
+ const segments = [...folderPath, fileName].filter(
178
+ (segment, index, all) => segment !== '' && !(segment === 'index' && index === all.length - 1)
179
+ )
180
+ return `/${segments.join('/')}`
181
+ }
182
+
183
+ /**
184
+ * Whether a page's own data may be read as the store — only an admin panel
185
+ * page that nobody but the store's trusted readers may open
186
+ * (`TableAccess.pageReadsAsStore`). Every other page renders what a visitor
187
+ * is served of the store's tables.
188
+ */
189
+ export const pageDataReadsAsStore = (
190
+ uidl: { outputOptions?: { folderPath?: string[]; fileName?: string; pageId?: string } },
191
+ auth?: UIDLAuthentication | null
192
+ ): boolean =>
193
+ TableAccess.pageReadsAsStore(
194
+ { route: pageRouteOf(uidl.outputOptions), pageId: uidl.outputOptions?.pageId },
195
+ auth
196
+ )
197
+
198
+ /**
199
+ * The arguments a page's data read hands a data-source module after its
200
+ * params: `{ as: 'visitor' }` — read what a visitor is served (the route's row
201
+ * policy, hidden columns and refused tables) — or none on a page that reads as
202
+ * the store (`pageDataReadsAsStore`).
203
+ */
204
+ export const pageDataReadArguments = (
205
+ uidl: { outputOptions?: { folderPath?: string[]; fileName?: string; pageId?: string } },
206
+ auth?: UIDLAuthentication | null
207
+ ): types.Expression[] =>
208
+ pageDataReadsAsStore(uidl, auth)
209
+ ? []
210
+ : [
211
+ types.objectExpression([
212
+ types.objectProperty(types.identifier('as'), types.stringLiteral('visitor')),
213
+ ]),
214
+ ]
@@ -1,6 +1,173 @@
1
1
  import { StringUtils } from '@teleporthq/teleport-shared'
2
2
  import { UIDLStaticValue, UIDLStyleDefinitions, UIDLStyleValue } from '@teleporthq/teleport-types'
3
3
 
4
+ const CSS_FUNCTIONS = [
5
+ 'radial-gradient',
6
+ 'linear-gradient',
7
+ 'conic-gradient',
8
+ 'repeating-linear-gradient',
9
+ 'repeating-radial-gradient',
10
+ 'repeating-conic-gradient',
11
+ ]
12
+
13
+ // CSS `content` property has the strictest value grammar of any
14
+ // property the AI emits: it must be either a quoted string, one of
15
+ // a fixed set of keywords, or a recognised function call. The AI
16
+ // occasionally produces garbage here (e.g. the raw fragment `';`
17
+ // straight out of a hallucinated declaration), and the
18
+ // downstream JSS serializer happily concatenates that into
19
+ // `content: ';;` — a CSS parse error that breaks the entire
20
+ // stylesheet on Next.js dev (the browser stops applying any rule
21
+ // after the malformed one). When we can't recognise the value as
22
+ // valid, we fall back to an empty string literal — losing the
23
+ // decoration but keeping the stylesheet parseable.
24
+ const CONTENT_KEYWORDS = new Set([
25
+ 'none',
26
+ 'normal',
27
+ 'open-quote',
28
+ 'close-quote',
29
+ 'no-open-quote',
30
+ 'no-close-quote',
31
+ 'inherit',
32
+ 'initial',
33
+ 'unset',
34
+ 'revert',
35
+ 'revert-layer',
36
+ ])
37
+
38
+ const CONTENT_FUNCTION_PREFIXES = [
39
+ 'attr(',
40
+ 'counter(',
41
+ 'counters(',
42
+ 'var(',
43
+ 'url(',
44
+ 'image(',
45
+ 'image-set(',
46
+ 'linear-gradient(',
47
+ 'radial-gradient(',
48
+ 'conic-gradient(',
49
+ ]
50
+
51
+ const isProperlyQuotedString = (value: string): boolean => {
52
+ if (value.length < 2) {
53
+ return false
54
+ }
55
+ const first = value.charAt(0)
56
+ const last = value.charAt(value.length - 1)
57
+ if (first !== last) {
58
+ return false
59
+ }
60
+ if (first !== '"' && first !== "'") {
61
+ return false
62
+ }
63
+ // Walk the interior and reject unescaped occurrences of the same
64
+ // quote character — those would close the string early and leak
65
+ // arbitrary CSS into the surrounding stylesheet.
66
+ for (let i = 1; i < value.length - 1; i++) {
67
+ const ch = value.charAt(i)
68
+ if (ch === '\\') {
69
+ i++ // skip the escaped character
70
+ continue
71
+ }
72
+ if (ch === first) {
73
+ return false
74
+ }
75
+ }
76
+ return true
77
+ }
78
+
79
+ export const sanitizeContentValue = (raw: string): string => {
80
+ const trimmed = raw.trim()
81
+ if (trimmed === '') {
82
+ return "''"
83
+ }
84
+ if (CONTENT_KEYWORDS.has(trimmed)) {
85
+ return trimmed
86
+ }
87
+ for (const prefix of CONTENT_FUNCTION_PREFIXES) {
88
+ if (trimmed.startsWith(prefix) && trimmed.endsWith(')')) {
89
+ return trimmed
90
+ }
91
+ }
92
+ if (isProperlyQuotedString(trimmed)) {
93
+ return trimmed
94
+ }
95
+ // Last-resort repair: strip every quote and semicolon (the two
96
+ // characters that break the surrounding rule) and wrap the
97
+ // remainder in single quotes. If nothing legible survives, fall
98
+ // through to an empty string. We deliberately do NOT try to
99
+ // preserve "almost a quoted string" inputs — the AI's malformed
100
+ // emissions don't have a clear repair path and silently keeping
101
+ // them risks injecting CSS the user didn't author.
102
+ const stripped = trimmed.replace(/['";]/g, '').trim()
103
+ return "'" + stripped + "'"
104
+ }
105
+
106
+ const isValidCSSValue = (value: string | number, key?: string): boolean => {
107
+ if (typeof value === 'number') {
108
+ return true
109
+ }
110
+
111
+ // Check for CSS functions that are missing their parentheses (e.g. "radial-gradientfoo")
112
+ for (const fn of CSS_FUNCTIONS) {
113
+ if (value.includes(fn) && !value.includes(`${fn}(`)) {
114
+ return false
115
+ }
116
+ }
117
+
118
+ // The `content` property is treated separately by
119
+ // `sanitizeContentValue` — it has its own grammar (quoted string
120
+ // OR keyword OR function call) that the general colon/paren
121
+ // check below would mis-evaluate for a legitimate quoted string
122
+ // that happens to contain a `:`.
123
+ if (key === 'content') {
124
+ return true
125
+ }
126
+
127
+ // Check for values that contain embedded CSS declarations (e.g. "valueproperty-name: other")
128
+ // A colon in a CSS value normally only appears inside url() or var() or similar functions.
129
+ // If a colon appears outside of parentheses, the value is likely corrupted.
130
+ //
131
+ // Parentheses and colons inside a quoted string (e.g. a `url("data:...(...)")`
132
+ // data-URI or a `font-family: "Foo (Bold)"`) are literal text, not syntax, so
133
+ // the scan tracks the active quote and ignores everything inside it.
134
+ let parenDepth = 0
135
+ let quote = ''
136
+ for (let i = 0; i < value.length; i++) {
137
+ const char = value[i]
138
+ if (quote) {
139
+ if (char === quote && value[i - 1] !== '\\') {
140
+ quote = ''
141
+ }
142
+ continue
143
+ }
144
+ if (char === "'" || char === '"') {
145
+ quote = char
146
+ } else if (char === '(') {
147
+ parenDepth++
148
+ } else if (char === ')') {
149
+ parenDepth--
150
+ // A closing paren with no matching opener means the value is corrupted.
151
+ if (parenDepth < 0) {
152
+ return false
153
+ }
154
+ } else if (char === ':' && parenDepth === 0) {
155
+ // Colons outside parentheses in a CSS value indicate a corrupted/merged declaration
156
+ return false
157
+ }
158
+ }
159
+
160
+ // Unbalanced parentheses leave an unclosed CSS function — e.g. a stream that
161
+ // was truncated mid-value (`color-mix(in srgb, var(--color-surface) 50%,`).
162
+ // Emitting it produces `color: color-mix(...50%,;` which fails the CSS parser
163
+ // and breaks the whole stylesheet (and the Next.js production build).
164
+ if (parenDepth !== 0) {
165
+ return false
166
+ }
167
+
168
+ return true
169
+ }
170
+
4
171
  const getContentOfStyleKey = (styleValue: UIDLStyleValue) => {
5
172
  if (styleValue.type === 'static') {
6
173
  return styleValue.content
@@ -16,7 +183,22 @@ const getContentOfStyleKey = (styleValue: UIDLStyleValue) => {
16
183
 
17
184
  export const getContentOfStyleObject = (styleObject: UIDLStyleDefinitions) => {
18
185
  return Object.keys(styleObject).reduce((acc: Record<string, unknown>, key) => {
19
- acc[key] = getContentOfStyleKey(styleObject[key])
186
+ const value = getContentOfStyleKey(styleObject[key])
187
+ if (typeof value === 'string' || typeof value === 'number') {
188
+ if (isValidCSSValue(value, key)) {
189
+ // The `content` CSS property is the only one in the AI's
190
+ // typical output that consistently arrives malformed — the
191
+ // sanitiser repairs or empty-strings it so the surrounding
192
+ // rule stays parseable.
193
+ if (key === 'content' && typeof value === 'string') {
194
+ acc[key] = sanitizeContentValue(value)
195
+ } else {
196
+ acc[key] = value
197
+ }
198
+ }
199
+ } else {
200
+ acc[key] = value
201
+ }
20
202
  return acc
21
203
  }, {})
22
204
  }
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Delimiter balancing for `{{ … }}` binding expressions.
3
+ *
4
+ * THE DEFECT THIS EXISTS FOR. `parseStringWithTemplateExpressions` converted a
5
+ * UIDL string into a template literal and then handed the result straight to
6
+ * Babel. When the binding inside was unbalanced the produced source did not
7
+ * parse, `parse()` threw, and — because the inline-style caller has no
8
+ * try/catch — the SyntaxError escaped all the way out and killed the ENTIRE
9
+ * project build:
10
+ *
11
+ * const x = `translateX(${-(cameraX || ''}px) }px)`
12
+ * ^ Unexpected token, expected ","
13
+ *
14
+ * Two separate faults produced that line. The interpolated expression
15
+ * `-(cameraX || ''` was missing its closing paren, and the "re-close the CSS
16
+ * function" step counted parentheses across the WHOLE string — including the
17
+ * ones inside `${…}` — decided one was missing, and appended `px)` to the end,
18
+ * which could never help because the imbalance was inside the interpolation.
19
+ *
20
+ * One bad binding in one style property must never cost a project its build.
21
+ * These helpers make the imbalance repairable where it actually is, and let the
22
+ * caller degrade a single value instead of aborting.
23
+ */
24
+
25
+ /** Closing delimiter for each opener that nests inside an expression. */
26
+ const CLOSER_FOR_OPENER: Record<string, string> = {
27
+ '(': ')',
28
+ '[': ']',
29
+ '{': '}',
30
+ }
31
+
32
+ const CLOSERS = new Set(Object.values(CLOSER_FOR_OPENER))
33
+ const QUOTES = new Set(["'", '"', '`'])
34
+
35
+ export interface ExpressionScan {
36
+ /** Openers still waiting for their closer, outermost first. */
37
+ unclosed: string[]
38
+ /** Closers that never had a matching opener. */
39
+ strayCloserCount: number
40
+ /** The quote character still open at the end of the scan, if any. */
41
+ unterminatedQuote: string | null
42
+ }
43
+
44
+ /**
45
+ * Single left-to-right pass over an expression, quote and escape aware.
46
+ * Characters inside a string literal never affect nesting.
47
+ */
48
+ export const scanExpression = (expression: string): ExpressionScan => {
49
+ const unclosed: string[] = []
50
+ let strayCloserCount = 0
51
+ let quote: string | null = null
52
+
53
+ for (let index = 0; index < expression.length; index++) {
54
+ const char = expression[index]
55
+
56
+ if (char === '\\') {
57
+ index++
58
+ continue
59
+ }
60
+
61
+ if (quote !== null) {
62
+ if (char === quote) {
63
+ quote = null
64
+ }
65
+ continue
66
+ }
67
+
68
+ if (QUOTES.has(char)) {
69
+ quote = char
70
+ continue
71
+ }
72
+
73
+ if (CLOSER_FOR_OPENER[char]) {
74
+ unclosed.push(char)
75
+ continue
76
+ }
77
+
78
+ if (CLOSERS.has(char)) {
79
+ const expected = unclosed.length > 0 ? CLOSER_FOR_OPENER[unclosed[unclosed.length - 1]] : null
80
+ if (expected === char) {
81
+ unclosed.pop()
82
+ } else {
83
+ strayCloserCount++
84
+ }
85
+ }
86
+ }
87
+
88
+ return { unclosed, strayCloserCount, unterminatedQuote: quote }
89
+ }
90
+
91
+ /** True when every quote and bracket closes and no closer is stray. */
92
+ export const isBalancedExpression = (expression: string): boolean => {
93
+ const scan = scanExpression(expression)
94
+ return (
95
+ scan.unclosed.length === 0 && scan.strayCloserCount === 0 && scan.unterminatedQuote === null
96
+ )
97
+ }
98
+
99
+ /**
100
+ * Close an expression that ends mid-quote or mid-bracket:
101
+ * `-(cameraX || ''` → `-(cameraX || '')`.
102
+ *
103
+ * Returns the expression unchanged when it is already balanced, and when the
104
+ * imbalance is a STRAY CLOSER — appending cannot fix a missing opener, and
105
+ * inventing one would be a guess.
106
+ */
107
+ export const balanceExpression = (expression: string): string => {
108
+ const scan = scanExpression(expression)
109
+ if (scan.strayCloserCount > 0) {
110
+ return expression
111
+ }
112
+ if (scan.unclosed.length === 0 && scan.unterminatedQuote === null) {
113
+ return expression
114
+ }
115
+
116
+ const suffix = [scan.unterminatedQuote || '', ...unclosedInReverse(scan.unclosed)].join('')
117
+
118
+ return expression + suffix
119
+ }
120
+
121
+ const unclosedInReverse = (unclosed: string[]): string[] =>
122
+ unclosed
123
+ .slice()
124
+ .reverse()
125
+ .map((opener) => CLOSER_FOR_OPENER[opener])
126
+
127
+ /**
128
+ * Parenthesis balance of the STATIC parts of a template string — everything
129
+ * outside `${…}`.
130
+ *
131
+ * This is the number the "re-close the CSS function" step needs. Counting over
132
+ * the whole string mixes in the expressions' own parentheses, so an imbalance
133
+ * INSIDE an interpolation reads as a missing close on the CSS function and the
134
+ * step appends a unit and a `)` that belong nowhere.
135
+ */
136
+ export const countUnclosedStaticParens = (templateStr: string): number => {
137
+ let depth = 0
138
+ let index = 0
139
+
140
+ while (index < templateStr.length) {
141
+ if (templateStr[index] === '$' && templateStr[index + 1] === '{') {
142
+ index = skipInterpolation(templateStr, index + 2)
143
+ continue
144
+ }
145
+ if (templateStr[index] === '(') {
146
+ depth++
147
+ } else if (templateStr[index] === ')') {
148
+ depth--
149
+ }
150
+ index++
151
+ }
152
+
153
+ return depth > 0 ? depth : 0
154
+ }
155
+
156
+ /**
157
+ * Index just past the `}` that closes an interpolation opened at `start`.
158
+ * Tracks nested braces and string literals so `${ {a:'}'} }` is skipped whole.
159
+ * An unterminated interpolation consumes the rest of the string.
160
+ */
161
+ const skipInterpolation = (templateStr: string, start: number): number => {
162
+ let depth = 1
163
+ let quote: string | null = null
164
+
165
+ for (let index = start; index < templateStr.length; index++) {
166
+ const char = templateStr[index]
167
+
168
+ if (char === '\\') {
169
+ index++
170
+ continue
171
+ }
172
+
173
+ if (quote !== null) {
174
+ if (char === quote) {
175
+ quote = null
176
+ }
177
+ continue
178
+ }
179
+
180
+ if (QUOTES.has(char)) {
181
+ quote = char
182
+ continue
183
+ }
184
+
185
+ if (char === '{') {
186
+ depth++
187
+ } else if (char === '}') {
188
+ depth--
189
+ if (depth === 0) {
190
+ return index + 1
191
+ }
192
+ }
193
+ }
194
+
195
+ return templateStr.length
196
+ }
@@ -0,0 +1,25 @@
1
+ export type BinaryOperator =
2
+ | '==='
3
+ | '+'
4
+ | '-'
5
+ | '/'
6
+ | '%'
7
+ | '*'
8
+ | '**'
9
+ | '&'
10
+ | '|'
11
+ | '>>'
12
+ | '>>>'
13
+ | '<<'
14
+ | '^'
15
+ | '=='
16
+ | '!='
17
+ | '!=='
18
+ | 'in'
19
+ | 'instanceof'
20
+ | '>'
21
+ | '<'
22
+ | '>='
23
+ | '<='
24
+
25
+ export type UnaryOperation = '+' | '-' | 'void' | 'throw' | 'delete' | '!' | '~' | 'typeof'