@teleporthq/teleport-project-generator-next 0.45.21 → 0.45.22

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 (151) hide show
  1. package/__tests__/code-copy-runtime.test.ts +31 -24
  2. package/__tests__/forum-files-route.test.ts +147 -0
  3. package/__tests__/forum-markdown.test.ts +136 -0
  4. package/__tests__/forum-page-data.test.ts +1329 -0
  5. package/__tests__/forum-project-plugin.test.ts +789 -0
  6. package/__tests__/forum-replies-route.test.ts +82 -0
  7. package/__tests__/forum-topics-only-end2end.test.ts +124 -0
  8. package/__tests__/i18n-app-runtime.test.ts +187 -0
  9. package/__tests__/page-revalidate-plugin.test.ts +111 -0
  10. package/__tests__/rich-text-editor-frame.test.ts +25 -0
  11. package/dist/cjs/forum/files-route.d.ts +26 -0
  12. package/dist/cjs/forum/files-route.d.ts.map +1 -0
  13. package/dist/cjs/forum/files-route.js +42 -0
  14. package/dist/cjs/forum/files-route.js.map +1 -0
  15. package/dist/cjs/forum/markdown-source.d.ts +17 -0
  16. package/dist/cjs/forum/markdown-source.d.ts.map +1 -0
  17. package/dist/cjs/forum/markdown-source.js +23 -0
  18. package/dist/cjs/forum/markdown-source.js.map +1 -0
  19. package/dist/cjs/forum/notifications-route.d.ts +17 -0
  20. package/dist/cjs/forum/notifications-route.d.ts.map +1 -0
  21. package/dist/cjs/forum/notifications-route.js +30 -0
  22. package/dist/cjs/forum/notifications-route.js.map +1 -0
  23. package/dist/cjs/forum/page-data-source.d.ts +58 -0
  24. package/dist/cjs/forum/page-data-source.d.ts.map +1 -0
  25. package/dist/cjs/forum/page-data-source.js +168 -0
  26. package/dist/cjs/forum/page-data-source.js.map +1 -0
  27. package/dist/cjs/forum/page-rewrite.d.ts +50 -0
  28. package/dist/cjs/forum/page-rewrite.d.ts.map +1 -0
  29. package/dist/cjs/forum/page-rewrite.js +473 -0
  30. package/dist/cjs/forum/page-rewrite.js.map +1 -0
  31. package/dist/cjs/forum/project-plugin.d.ts +34 -0
  32. package/dist/cjs/forum/project-plugin.d.ts.map +1 -0
  33. package/dist/cjs/forum/project-plugin.js +272 -0
  34. package/dist/cjs/forum/project-plugin.js.map +1 -0
  35. package/dist/cjs/forum/replies-route.d.ts +21 -0
  36. package/dist/cjs/forum/replies-route.d.ts.map +1 -0
  37. package/dist/cjs/forum/replies-route.js +33 -0
  38. package/dist/cjs/forum/replies-route.js.map +1 -0
  39. package/dist/cjs/forum/seo.d.ts +29 -0
  40. package/dist/cjs/forum/seo.d.ts.map +1 -0
  41. package/dist/cjs/forum/seo.js +61 -0
  42. package/dist/cjs/forum/seo.js.map +1 -0
  43. package/dist/cjs/forum/settings.d.ts +97 -0
  44. package/dist/cjs/forum/settings.d.ts.map +1 -0
  45. package/dist/cjs/forum/settings.js +162 -0
  46. package/dist/cjs/forum/settings.js.map +1 -0
  47. package/dist/cjs/index.d.ts +1 -0
  48. package/dist/cjs/index.d.ts.map +1 -1
  49. package/dist/cjs/index.js +87 -80
  50. package/dist/cjs/index.js.map +1 -1
  51. package/dist/cjs/instant-search/sections.d.ts.map +1 -1
  52. package/dist/cjs/instant-search/sections.js +18 -0
  53. package/dist/cjs/instant-search/sections.js.map +1 -1
  54. package/dist/cjs/instant-search/settings.d.ts +1 -1
  55. package/dist/cjs/instant-search/settings.d.ts.map +1 -1
  56. package/dist/cjs/instant-search/settings.js +2 -0
  57. package/dist/cjs/instant-search/settings.js.map +1 -1
  58. package/dist/cjs/internationalization/app-i18n-runtime.d.ts +39 -0
  59. package/dist/cjs/internationalization/app-i18n-runtime.d.ts.map +1 -0
  60. package/dist/cjs/internationalization/app-i18n-runtime.js +126 -0
  61. package/dist/cjs/internationalization/app-i18n-runtime.js.map +1 -0
  62. package/dist/cjs/internationalization/project.d.ts.map +1 -1
  63. package/dist/cjs/internationalization/project.js +6 -0
  64. package/dist/cjs/internationalization/project.js.map +1 -1
  65. package/dist/cjs/page-revalidate/project-plugin.d.ts.map +1 -1
  66. package/dist/cjs/page-revalidate/project-plugin.js +5 -1
  67. package/dist/cjs/page-revalidate/project-plugin.js.map +1 -1
  68. package/dist/cjs/rich-text-editor/content-support-source.d.ts +2 -1
  69. package/dist/cjs/rich-text-editor/content-support-source.d.ts.map +1 -1
  70. package/dist/cjs/rich-text-editor/content-support-source.js +9 -2
  71. package/dist/cjs/rich-text-editor/content-support-source.js.map +1 -1
  72. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  73. package/dist/esm/forum/files-route.d.ts +26 -0
  74. package/dist/esm/forum/files-route.d.ts.map +1 -0
  75. package/dist/esm/forum/files-route.js +38 -0
  76. package/dist/esm/forum/files-route.js.map +1 -0
  77. package/dist/esm/forum/markdown-source.d.ts +17 -0
  78. package/dist/esm/forum/markdown-source.d.ts.map +1 -0
  79. package/dist/esm/forum/markdown-source.js +19 -0
  80. package/dist/esm/forum/markdown-source.js.map +1 -0
  81. package/dist/esm/forum/notifications-route.d.ts +17 -0
  82. package/dist/esm/forum/notifications-route.d.ts.map +1 -0
  83. package/dist/esm/forum/notifications-route.js +26 -0
  84. package/dist/esm/forum/notifications-route.js.map +1 -0
  85. package/dist/esm/forum/page-data-source.d.ts +58 -0
  86. package/dist/esm/forum/page-data-source.d.ts.map +1 -0
  87. package/dist/esm/forum/page-data-source.js +164 -0
  88. package/dist/esm/forum/page-data-source.js.map +1 -0
  89. package/dist/esm/forum/page-rewrite.d.ts +50 -0
  90. package/dist/esm/forum/page-rewrite.d.ts.map +1 -0
  91. package/dist/esm/forum/page-rewrite.js +446 -0
  92. package/dist/esm/forum/page-rewrite.js.map +1 -0
  93. package/dist/esm/forum/project-plugin.d.ts +34 -0
  94. package/dist/esm/forum/project-plugin.d.ts.map +1 -0
  95. package/dist/esm/forum/project-plugin.js +269 -0
  96. package/dist/esm/forum/project-plugin.js.map +1 -0
  97. package/dist/esm/forum/replies-route.d.ts +21 -0
  98. package/dist/esm/forum/replies-route.d.ts.map +1 -0
  99. package/dist/esm/forum/replies-route.js +29 -0
  100. package/dist/esm/forum/replies-route.js.map +1 -0
  101. package/dist/esm/forum/seo.d.ts +29 -0
  102. package/dist/esm/forum/seo.d.ts.map +1 -0
  103. package/dist/esm/forum/seo.js +56 -0
  104. package/dist/esm/forum/seo.js.map +1 -0
  105. package/dist/esm/forum/settings.d.ts +97 -0
  106. package/dist/esm/forum/settings.d.ts.map +1 -0
  107. package/dist/esm/forum/settings.js +158 -0
  108. package/dist/esm/forum/settings.js.map +1 -0
  109. package/dist/esm/index.d.ts +1 -0
  110. package/dist/esm/index.d.ts.map +1 -1
  111. package/dist/esm/index.js +6 -0
  112. package/dist/esm/index.js.map +1 -1
  113. package/dist/esm/instant-search/sections.d.ts.map +1 -1
  114. package/dist/esm/instant-search/sections.js +18 -0
  115. package/dist/esm/instant-search/sections.js.map +1 -1
  116. package/dist/esm/instant-search/settings.d.ts +1 -1
  117. package/dist/esm/instant-search/settings.d.ts.map +1 -1
  118. package/dist/esm/instant-search/settings.js +2 -0
  119. package/dist/esm/instant-search/settings.js.map +1 -1
  120. package/dist/esm/internationalization/app-i18n-runtime.d.ts +39 -0
  121. package/dist/esm/internationalization/app-i18n-runtime.d.ts.map +1 -0
  122. package/dist/esm/internationalization/app-i18n-runtime.js +120 -0
  123. package/dist/esm/internationalization/app-i18n-runtime.js.map +1 -0
  124. package/dist/esm/internationalization/project.d.ts.map +1 -1
  125. package/dist/esm/internationalization/project.js +6 -0
  126. package/dist/esm/internationalization/project.js.map +1 -1
  127. package/dist/esm/page-revalidate/project-plugin.d.ts.map +1 -1
  128. package/dist/esm/page-revalidate/project-plugin.js +5 -1
  129. package/dist/esm/page-revalidate/project-plugin.js.map +1 -1
  130. package/dist/esm/rich-text-editor/content-support-source.d.ts +2 -1
  131. package/dist/esm/rich-text-editor/content-support-source.d.ts.map +1 -1
  132. package/dist/esm/rich-text-editor/content-support-source.js +9 -2
  133. package/dist/esm/rich-text-editor/content-support-source.js.map +1 -1
  134. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  135. package/package.json +19 -19
  136. package/src/forum/files-route.ts +133 -0
  137. package/src/forum/markdown-source.ts +177 -0
  138. package/src/forum/notifications-route.ts +87 -0
  139. package/src/forum/page-data-source.ts +810 -0
  140. package/src/forum/page-rewrite.ts +567 -0
  141. package/src/forum/project-plugin.ts +328 -0
  142. package/src/forum/replies-route.ts +91 -0
  143. package/src/forum/seo.ts +245 -0
  144. package/src/forum/settings.ts +261 -0
  145. package/src/index.ts +6 -0
  146. package/src/instant-search/sections.ts +20 -0
  147. package/src/instant-search/settings.ts +2 -0
  148. package/src/internationalization/app-i18n-runtime.ts +165 -0
  149. package/src/internationalization/project.ts +7 -0
  150. package/src/page-revalidate/project-plugin.ts +5 -1
  151. package/src/rich-text-editor/content-support-source.ts +14 -2
@@ -0,0 +1,567 @@
1
+ import * as types from '@babel/types'
2
+ import { parse, parseExpression } from '@babel/parser'
3
+ import { CodeGenerator } from '@babel/generator'
4
+ import { JSIdentifiers, PageArrival, StringUtils } from '@teleporthq/teleport-shared'
5
+ import { ForumDetailsPage } from './settings'
6
+
7
+ /** The prop the page's extra data travels under (SEO, the community, the reply cursor). */
8
+ export const FORUM_PAGE_PROP = '__tqForum'
9
+ const DATA_IMPORT = '__tqForumData'
10
+
11
+ /** Which record a page is about. */
12
+ export type ForumPageRecord =
13
+ /** The one its address ends with, by the route column (`slug`): `context.params[column]`. */
14
+ | { column: string }
15
+ /** Always the same one, by its slug: a page with a static address (`/forum/new`). */
16
+ | { slug: string }
17
+
18
+ export type ForumPageRewrite = ForumPageRecord & {
19
+ kind: ForumDetailsPage
20
+ /** The prop the page reads its row from (`initialPropsData.exposeAs.name`), or null when it binds none. */
21
+ exposeAs: string | null
22
+ /** From the page's folder to the project root (`../../../` for `pages/forum/t/`). */
23
+ rootPrefix: string
24
+ /** `utils/forum-page-data`, under `rootPrefix`. */
25
+ dataModulePath: string
26
+ /** `utils/page-arrival`, under `rootPrefix`. */
27
+ pageArrivalPath: string
28
+ }
29
+
30
+ /** The states each page declares (`forum-markers.ts` there) that start from the module's answer. */
31
+ export const FORUM_SEEDED_STATES: Record<ForumDetailsPage, string[]> = {
32
+ topic: [
33
+ 'viewer',
34
+ 'topicDetails',
35
+ 'replies',
36
+ 'reactions',
37
+ 'score',
38
+ 'myVote',
39
+ 'hasMoreReplies',
40
+ 'replySort',
41
+ 'replyTo',
42
+ ],
43
+ community: [
44
+ 'viewer',
45
+ 'topics',
46
+ 'rules',
47
+ 'moderators',
48
+ 'sortBy',
49
+ 'paging',
50
+ 'pendingJoinCount',
51
+ 'openReportCount',
52
+ ],
53
+ manage: ['viewer', 'rulesText'],
54
+ newTopic: ['viewer'],
55
+ }
56
+
57
+ /**
58
+ * A seeded state the answer keeps elsewhere, as a path into it: `topicDetails`
59
+ * is the topic the record prop reads; `rulesText` the community's rules as the
60
+ * Manage form edits them (its field reads the state once, when it mounts).
61
+ */
62
+ const SEED_ANSWER_PATH: Record<string, string> = {
63
+ topicDetails: 'topic',
64
+ rulesText: 'community.rules_text',
65
+ }
66
+
67
+ interface ForumPageSource {
68
+ /** The module's call: `slug`, `session`, `query`, `one` and (with `url`) `pageUrl` are in scope. */
69
+ load: string
70
+ /** The answer's key the page's record prop (`exposeAs`) reads. */
71
+ record: string
72
+ /** What travels under `__tqForum`. */
73
+ extra: string
74
+ /** The call takes the page's address (the topic's JSON-LD). */
75
+ url?: boolean
76
+ /** An anonymous answer is cached at the edge; without it the page is every visitor's own. */
77
+ shared?: boolean
78
+ }
79
+
80
+ const FORUM_PAGE_SOURCES: Record<ForumDetailsPage, ForumPageSource> = {
81
+ topic: {
82
+ load: `loadTopicPage({ slug, session, rootReplyId: one(query.reply), sort: one(query.sort), url: pageUrl })`,
83
+ record: 'topic',
84
+ extra: `{ seo: data.seo, community: data.community, nextReplyOffset: data.nextReplyOffset }`,
85
+ url: true,
86
+ shared: true,
87
+ },
88
+ community: {
89
+ load: `loadCommunityPage({ slug, session, sort: one(query.sort), page: parseInt(one(query.page), 10) || 1 })`,
90
+ record: 'community',
91
+ extra: `{ seo: data.seo }`,
92
+ shared: true,
93
+ },
94
+ // A community's Manage and New topic pages: one visitor's own, never in a search engine.
95
+ manage: {
96
+ load: `loadCommunityGate({ slug, session, need: 'moderate' })`,
97
+ record: 'community',
98
+ extra: `{ seo: { noindex: true } }`,
99
+ },
100
+ newTopic: {
101
+ load: `loadCommunityGate({ slug, session, need: 'post' })`,
102
+ record: 'community',
103
+ extra: `{ seo: { noindex: true } }`,
104
+ },
105
+ }
106
+
107
+ const DATA_FUNCTIONS = ['getStaticProps', 'getServerSideProps', 'getStaticPaths']
108
+ /** The page-access guard's verdict variable (`access-rules/page-access-guard-plugin.ts`). */
109
+ const ACCESS_DENIED = '__tqAccessDenied'
110
+ const SKIP_WALK_KEYS = new Set([
111
+ 'loc',
112
+ 'range',
113
+ 'start',
114
+ 'end',
115
+ 'leadingComments',
116
+ 'trailingComments',
117
+ 'innerComments',
118
+ ])
119
+
120
+ const walk = (node: unknown, visit: (node: types.Node) => void): void => {
121
+ if (!node || typeof node !== 'object') {
122
+ return
123
+ }
124
+ const anyNode = node as Record<string, unknown> & { type?: string }
125
+ if (typeof anyNode.type === 'string') {
126
+ visit(anyNode as unknown as types.Node)
127
+ }
128
+ for (const key of Object.keys(anyNode)) {
129
+ if (SKIP_WALK_KEYS.has(key)) {
130
+ continue
131
+ }
132
+ const value = anyNode[key]
133
+ if (Array.isArray(value)) {
134
+ value.forEach((child) => walk(child, visit))
135
+ } else if (value && typeof (value as { type?: string }).type === 'string') {
136
+ walk(value, visit)
137
+ }
138
+ }
139
+ }
140
+
141
+ const mentions = (node: types.Node, name: string): boolean => {
142
+ let found = false
143
+ walk(node, (inner) => {
144
+ if (inner.type === 'Identifier' && inner.name === name) {
145
+ found = true
146
+ }
147
+ })
148
+ return found
149
+ }
150
+
151
+ const exportedFunctionName = (statement: types.Statement): string | null =>
152
+ statement.type === 'ExportNamedDeclaration' &&
153
+ statement.declaration?.type === 'FunctionDeclaration' &&
154
+ statement.declaration.id
155
+ ? statement.declaration.id.name
156
+ : null
157
+
158
+ /** Import bindings nothing in the program uses any more, once the data functions are gone. */
159
+ const dropUnusedImports = (program: types.Program, alsoUsedBy: types.Node[]): void => {
160
+ const used = new Set<string>()
161
+ walk(
162
+ [...program.body.filter((statement) => statement.type !== 'ImportDeclaration'), ...alsoUsedBy],
163
+ (node) => {
164
+ if (node.type === 'Identifier' || node.type === 'JSXIdentifier') {
165
+ used.add(node.name)
166
+ }
167
+ }
168
+ )
169
+ program.body = program.body.filter((statement) => {
170
+ if (statement.type !== 'ImportDeclaration' || statement.specifiers.length === 0) {
171
+ return true
172
+ }
173
+ // React stays whatever the JSX runtime: the generated pages import it by name.
174
+ statement.specifiers = statement.specifiers.filter(
175
+ (specifier) => specifier.local.name === 'React' || used.has(specifier.local.name)
176
+ )
177
+ return statement.specifiers.length > 0
178
+ })
179
+ }
180
+
181
+ /**
182
+ * The locale's messages of a project with internationalization: the locale
183
+ * fetcher put them in the page's `getStaticProps`, which this rewrite takes
184
+ * away. Without them `next-intl` has nothing to translate with, and every
185
+ * word of the page — its navigation and footer too — shows its key.
186
+ */
187
+ const LOCALE_MESSAGES_PATH = '/locales/'
188
+
189
+ /** Whether one of the data functions this rewrite takes away loaded the locale's messages. */
190
+ const loadsLocaleMessages = (statements: types.Statement[]): boolean => {
191
+ let found = false
192
+ walk(statements, (node) => {
193
+ if (node.type === 'StringLiteral' && node.value === LOCALE_MESSAGES_PATH) {
194
+ found = true
195
+ }
196
+ })
197
+ return found
198
+ }
199
+
200
+ const dataFunctionSource = (rewrite: ForumPageRewrite, localized: boolean): string => {
201
+ const source = FORUM_PAGE_SOURCES[rewrite.kind]
202
+ const slug =
203
+ 'column' in rewrite
204
+ ? `one(params[${JSON.stringify(rewrite.column)}])`
205
+ : JSON.stringify(rewrite.slug)
206
+ const seeded = FORUM_SEEDED_STATES[rewrite.kind]
207
+ .map((state) => `${state}: data.${SEED_ANSWER_PATH[state] ?? state}`)
208
+ .join(', ')
209
+ const record = rewrite.exposeAs
210
+ ? `${JSON.stringify(rewrite.exposeAs)}: data.${source.record},\n `
211
+ : ''
212
+ const pageUrl = source.url
213
+ ? `
214
+ const host = String((req && req.headers && req.headers.host) || '')
215
+ const pageUrl = /^[a-z0-9.-]+(:\\d+)?$/i.test(host) ? 'https://' + host + String(req.url || '').split('?')[0] : ''`
216
+ : ''
217
+ const cache = source.shared
218
+ ? `session ? 'private, no-store' : 'public, s-maxage=30, stale-while-revalidate=300'`
219
+ : `'private, no-store'`
220
+ return `// Rendered per request by the Forum plugin: who is asking decides what is shown.
221
+ export async function getServerSideProps(context) {
222
+ const { params = {}, query = {}, req, res } = context
223
+ const one = (value) => String(Array.isArray(value) ? value[0] : value == null ? '' : value)
224
+ const slug = ${slug}
225
+ const session = await ${DATA_IMPORT}.readSession(req)${pageUrl}
226
+ const data = await ${DATA_IMPORT}.${source.load}
227
+ if (!data) {
228
+ res.setHeader('Cache-Control', 'no-store')
229
+ return { notFound: true }
230
+ }
231
+ res.setHeader('Cache-Control', ${cache})${
232
+ localized
233
+ ? `
234
+ const messages = (await import('${LOCALE_MESSAGES_PATH}' + context.locale + '.json')).default`
235
+ : ''
236
+ }
237
+ return {
238
+ props: {
239
+ ...params,${localized ? '\n messages,' : ''}
240
+ ${record}${seeded},
241
+ ${FORUM_PAGE_PROP}: ${source.extra},
242
+ },
243
+ }
244
+ }
245
+ `
246
+ }
247
+
248
+ const HEAD_CHILDREN = [
249
+ `props.${FORUM_PAGE_PROP} && props.${FORUM_PAGE_PROP}.seo && props.${FORUM_PAGE_PROP}.seo.noindex ? <meta name="robots" content="noindex" /> : null`,
250
+ `props.${FORUM_PAGE_PROP} && props.${FORUM_PAGE_PROP}.seo && props.${FORUM_PAGE_PROP}.seo.jsonLd ? <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(props.${FORUM_PAGE_PROP}.seo.jsonLd).replace(/</g, '\\\\u003c') }} /> : null`,
251
+ ]
252
+
253
+ const jsxExpressionChild = (source: string): types.JSXExpressionContainer =>
254
+ types.jsxExpressionContainer(parseExpression(source, { plugins: ['jsx'] }) as types.Expression)
255
+
256
+ /** The page's component: what `export default` names (through the arrival wrapper when already wrapped). */
257
+ const pageComponent = (
258
+ program: types.Program
259
+ ): types.FunctionDeclaration | types.ArrowFunctionExpression | types.FunctionExpression | null => {
260
+ const exportDefault = program.body.find(
261
+ (statement): statement is types.ExportDefaultDeclaration =>
262
+ statement.type === 'ExportDefaultDeclaration'
263
+ )
264
+ if (!exportDefault) {
265
+ return null
266
+ }
267
+ let declaration: types.Node = exportDefault.declaration
268
+ if (declaration.type === 'CallExpression' && declaration.arguments[0]) {
269
+ declaration = declaration.arguments[0]
270
+ }
271
+ if (declaration.type === 'FunctionDeclaration') {
272
+ return declaration
273
+ }
274
+ if (declaration.type !== 'Identifier') {
275
+ return null
276
+ }
277
+ const name = declaration.name
278
+ for (const statement of program.body) {
279
+ if (statement.type === 'FunctionDeclaration' && statement.id?.name === name) {
280
+ return statement
281
+ }
282
+ if (statement.type === 'VariableDeclaration') {
283
+ for (const declarator of statement.declarations) {
284
+ if (
285
+ declarator.id.type === 'Identifier' &&
286
+ declarator.id.name === name &&
287
+ declarator.init &&
288
+ (declarator.init.type === 'ArrowFunctionExpression' ||
289
+ declarator.init.type === 'FunctionExpression')
290
+ ) {
291
+ return declarator.init
292
+ }
293
+ }
294
+ }
295
+ }
296
+ return null
297
+ }
298
+
299
+ const isSeededFromProps = (argument: types.Node | undefined, stateKey: string): boolean =>
300
+ !!argument &&
301
+ argument.type === 'ConditionalExpression' &&
302
+ argument.test.type === 'BinaryExpression' &&
303
+ argument.test.left.type === 'MemberExpression' &&
304
+ argument.test.left.property.type === 'Identifier' &&
305
+ argument.test.left.property.name === stateKey
306
+
307
+ /**
308
+ * `const [viewer, setViewer] = useState(<default>)` becomes
309
+ * `useState(props.viewer !== undefined ? props.viewer : <default>)` for every
310
+ * state the module seeds — the same shape the React base component emits for
311
+ * a state with a data-source binding (`createStateHookAST`), so a page whose
312
+ * states already carry one is left as it is. Returns the states seeded.
313
+ */
314
+ const seedStatesFromProps = (component: types.Node, stateKeys: string[]): string[] => {
315
+ const seeded: string[] = []
316
+ const names = new Map(stateKeys.map((key) => [JSIdentifiers.createSafeJSIdentifier(key), key]))
317
+ walk(component, (node) => {
318
+ if (node.type !== 'VariableDeclarator' || node.id.type !== 'ArrayPattern' || !node.init) {
319
+ return
320
+ }
321
+ const first = node.id.elements[0]
322
+ const init = node.init
323
+ if (
324
+ !first ||
325
+ first.type !== 'Identifier' ||
326
+ !names.has(first.name) ||
327
+ init.type !== 'CallExpression' ||
328
+ init.callee.type !== 'Identifier' ||
329
+ init.callee.name !== 'useState'
330
+ ) {
331
+ return
332
+ }
333
+ const stateKey = names.get(first.name) as string
334
+ const fallback =
335
+ (init.arguments[0] as types.Expression | undefined) ?? types.identifier('undefined')
336
+ if (isSeededFromProps(fallback, stateKey)) {
337
+ seeded.push(stateKey)
338
+ return
339
+ }
340
+ const propAccess = () =>
341
+ types.memberExpression(
342
+ types.identifier('props'),
343
+ types.identifier(StringUtils.createStateOrPropStoringValue(stateKey))
344
+ )
345
+ init.arguments = [
346
+ types.conditionalExpression(
347
+ types.binaryExpression('!==', propAccess(), types.identifier('undefined')),
348
+ propAccess(),
349
+ fallback
350
+ ),
351
+ ]
352
+ seeded.push(stateKey)
353
+ })
354
+ return seeded
355
+ }
356
+
357
+ /** The helper the workflows plugin shapes a record into a form state with. */
358
+ const RECORD_FORM_HELPER = '__normalizeAdminFormRow'
359
+
360
+ const isRecordCopyInto = (statement: types.Statement, setters: Set<string>): boolean =>
361
+ statement.type === 'ExpressionStatement' &&
362
+ statement.expression.type === 'CallExpression' &&
363
+ statement.expression.callee.type === 'Identifier' &&
364
+ setters.has(statement.expression.callee.name) &&
365
+ statement.expression.arguments[0]?.type === 'CallExpression' &&
366
+ statement.expression.arguments[0].callee.type === 'Identifier' &&
367
+ statement.expression.arguments[0].callee.name === RECORD_FORM_HELPER
368
+
369
+ /** `useEffect(() => { if (<test>) {} }, [])`: an effect whose only branch was emptied. */
370
+ const isEmptiedEffect = (statement: types.Statement): boolean => {
371
+ if (
372
+ statement.type !== 'ExpressionStatement' ||
373
+ statement.expression.type !== 'CallExpression' ||
374
+ statement.expression.callee.type !== 'Identifier' ||
375
+ statement.expression.callee.name !== 'useEffect'
376
+ ) {
377
+ return false
378
+ }
379
+ const effect = statement.expression.arguments[0]
380
+ if (effect?.type !== 'ArrowFunctionExpression' || effect.body.type !== 'BlockStatement') {
381
+ return false
382
+ }
383
+ const [only, ...rest] = effect.body.body
384
+ return (
385
+ rest.length === 0 &&
386
+ only?.type === 'IfStatement' &&
387
+ !only.alternate &&
388
+ only.consequent.type === 'BlockStatement' &&
389
+ only.consequent.body.length === 0
390
+ )
391
+ }
392
+
393
+ /**
394
+ * On a details page the workflows plugin copies the record into "the page's
395
+ * form" when it mounts — the first object state it finds, shaped by that
396
+ * state's defaults. On a forum page that state is one the module seeds
397
+ * (`viewer`): the copy would put its signed-out defaults back right after the
398
+ * first render. Every seeded state's copy is dropped, and the effect with it
399
+ * once it sets nothing else. Returns the states that lost one.
400
+ */
401
+ const dropRecordCopies = (component: types.Node, seededStates: string[]): string[] => {
402
+ const stateBySetter = new Map(
403
+ seededStates.map((state) => [StringUtils.createStateStoringFunction(state), state])
404
+ )
405
+ const setters = new Set(stateBySetter.keys())
406
+ const dropped: string[] = []
407
+ walk(component, (node) => {
408
+ if (node.type !== 'BlockStatement') {
409
+ return
410
+ }
411
+ node.body = node.body.filter((statement) => {
412
+ if (!isRecordCopyInto(statement, setters)) {
413
+ return true
414
+ }
415
+ const call = (statement as types.ExpressionStatement).expression as types.CallExpression
416
+ dropped.push(stateBySetter.get((call.callee as types.Identifier).name) as string)
417
+ return false
418
+ })
419
+ })
420
+ if (dropped.length > 0) {
421
+ walk(component, (node) => {
422
+ if (node.type === 'BlockStatement') {
423
+ node.body = node.body.filter((statement) => !isEmptiedEffect(statement))
424
+ }
425
+ })
426
+ }
427
+ return dropped
428
+ }
429
+
430
+ const ensurePropsParam = (component: types.Node): void => {
431
+ const fn = component as
432
+ | types.FunctionDeclaration
433
+ | types.ArrowFunctionExpression
434
+ | types.FunctionExpression
435
+ if (fn.params.length === 0) {
436
+ fn.params.push(types.identifier('props'))
437
+ }
438
+ }
439
+
440
+ const injectHead = (program: types.Program): boolean => {
441
+ let injected = false
442
+ walk(program, (node) => {
443
+ if (injected || node.type !== 'JSXElement') {
444
+ return
445
+ }
446
+ const name = node.openingElement.name
447
+ if (name.type !== 'JSXIdentifier' || name.name !== 'Head') {
448
+ return
449
+ }
450
+ HEAD_CHILDREN.forEach((source) => node.children.push(jsxExpressionChild(source)))
451
+ if (node.openingElement.selfClosing) {
452
+ node.openingElement.selfClosing = false
453
+ node.closingElement = types.jsxClosingElement(types.jsxIdentifier('Head'))
454
+ }
455
+ injected = true
456
+ })
457
+ return injected
458
+ }
459
+
460
+ const wrapForArrival = (program: types.Program, rewrite: ForumPageRewrite): void => {
461
+ const exportDefault = program.body.find(
462
+ (statement): statement is types.ExportDefaultDeclaration =>
463
+ statement.type === 'ExportDefaultDeclaration'
464
+ )
465
+ if (!exportDefault || exportDefault.declaration.type !== 'Identifier') {
466
+ return
467
+ }
468
+ exportDefault.declaration = types.callExpression(
469
+ types.identifier(PageArrival.PAGE_ARRIVAL_WRAPPER),
470
+ [exportDefault.declaration]
471
+ )
472
+ program.body.unshift(
473
+ types.importDeclaration(
474
+ [types.importDefaultSpecifier(types.identifier(PageArrival.PAGE_ARRIVAL_WRAPPER))],
475
+ types.stringLiteral(`${rewrite.rootPrefix}${rewrite.pageArrivalPath}`)
476
+ )
477
+ )
478
+ }
479
+
480
+ export interface ForumPageRewriteResult {
481
+ content: string
482
+ /** The states now seeded from the page's props. */
483
+ seededStates: string[]
484
+ /** The page's head got the robots and JSON-LD lines. */
485
+ headInjected: boolean
486
+ /** The page now remounts on every arrival (needs `utils/page-arrival.js`). */
487
+ remounts: boolean
488
+ }
489
+
490
+ /**
491
+ * Rewrites a generated forum details page (the topic, the community, its
492
+ * Manage and New topic pages) — or the static New topic page of a forum
493
+ * without communities — so it renders per request from the forum data
494
+ * module: its `getStaticProps` / `getStaticPaths` (or an earlier
495
+ * `getServerSideProps`) are replaced by one that reads the session, calls the
496
+ * module, answers `notFound` when it refuses and sets the cache header; the
497
+ * page's own states start from the module's answer through its props, and
498
+ * keep it (no copy of the record over them on mount); the
499
+ * head carries `noindex` and the JSON-LD when the module says so; and the page
500
+ * remounts on every arrival, as every page seeded from props does. Returns
501
+ * null when the file is not a page this can rewrite (no default export).
502
+ */
503
+ export const rewriteForumPage = (
504
+ content: string,
505
+ rewrite: ForumPageRewrite
506
+ ): ForumPageRewriteResult | null => {
507
+ const ast = parse(content, { sourceType: 'module', plugins: ['jsx'] })
508
+ const program = ast.program
509
+ const component = pageComponent(program)
510
+ if (!component) {
511
+ return null
512
+ }
513
+ const alreadyWrapped = program.body.some(
514
+ (statement) =>
515
+ statement.type === 'ExportDefaultDeclaration' &&
516
+ statement.declaration.type === 'CallExpression' &&
517
+ statement.declaration.callee.type === 'Identifier' &&
518
+ statement.declaration.callee.name === PageArrival.PAGE_ARRIVAL_WRAPPER
519
+ )
520
+
521
+ // A protected page's guard (`access-rules/page-access-guard-plugin.ts`) opens
522
+ // its data function; it opens the new one too.
523
+ const guard: types.Statement[] = []
524
+ const removed: types.Statement[] = []
525
+ program.body = program.body.filter((statement) => {
526
+ const name = exportedFunctionName(statement)
527
+ if (name === 'getServerSideProps') {
528
+ const body = (statement as types.ExportNamedDeclaration)
529
+ .declaration as types.FunctionDeclaration
530
+ guard.push(...body.body.body.filter((inner) => mentions(inner, ACCESS_DENIED)))
531
+ }
532
+ const isDataFunction = !!name && DATA_FUNCTIONS.includes(name)
533
+ if (isDataFunction) {
534
+ removed.push(statement)
535
+ }
536
+ return !isDataFunction
537
+ })
538
+ dropUnusedImports(program, guard)
539
+
540
+ const dataFunction = parse(dataFunctionSource(rewrite, loadsLocaleMessages(removed)), {
541
+ sourceType: 'module',
542
+ }).program.body
543
+ const declaration = (dataFunction[0] as types.ExportNamedDeclaration)
544
+ .declaration as types.FunctionDeclaration
545
+ declaration.body.body.splice(1, 0, ...guard)
546
+ program.body.push(...dataFunction)
547
+ program.body.unshift(
548
+ types.importDeclaration(
549
+ [types.importDefaultSpecifier(types.identifier(DATA_IMPORT))],
550
+ types.stringLiteral(`${rewrite.rootPrefix}${rewrite.dataModulePath}`)
551
+ )
552
+ )
553
+
554
+ ensurePropsParam(component)
555
+ const seededStates = seedStatesFromProps(component, FORUM_SEEDED_STATES[rewrite.kind])
556
+ dropRecordCopies(component, seededStates)
557
+ const headInjected = injectHead(program)
558
+ if (!alreadyWrapped) {
559
+ wrapForArrival(program, rewrite)
560
+ }
561
+
562
+ const generated = new CodeGenerator(ast, {
563
+ jsescOption: { minimal: true },
564
+ retainLines: false,
565
+ }).generate()
566
+ return { content: generated.code, seededStates, headInjected, remounts: true }
567
+ }