@teleporthq/teleport-plugin-jsx-head-config 0.44.15 → 0.45.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.
@@ -0,0 +1,132 @@
1
+ import * as types from '@babel/types'
2
+ import generator from '@babel/generator'
3
+ import { createJSXHeadConfigPlugin } from '../src'
4
+ import { component, elementNode } from '@teleporthq/teleport-uidl-builders'
5
+ import {
6
+ ComponentStructure,
7
+ ChunkType,
8
+ FileType,
9
+ ChunkDefinition,
10
+ ComponentUIDL,
11
+ } from '@teleporthq/teleport-types'
12
+
13
+ /**
14
+ * Two things a canonical asset can say beyond its path:
15
+ * - `localizedParams`: a route parameter whose value differs per locale (a
16
+ * post's translated slug). Each hreflang link then reads the locale's own
17
+ * value from the row and falls back to the route's parameter — instead of
18
+ * pointing every locale at the current locale's slug.
19
+ * - `pageParam`: a listing paged by `?page=N` is its own page from the
20
+ * second one on: the canonical and og:url carry the parameter.
21
+ */
22
+
23
+ const makeJsxChunk = (): ChunkDefinition => ({
24
+ type: ChunkType.AST,
25
+ fileType: FileType.JS,
26
+ name: 'jsx-component',
27
+ content: {},
28
+ linkAfter: [],
29
+ meta: {
30
+ nodesLookup: {
31
+ container: {
32
+ type: 'JSXElement',
33
+ openingElement: {
34
+ type: 'JSXOpeningElement',
35
+ name: { type: 'JSXIdentifier', name: 'div' },
36
+ attributes: [],
37
+ selfClosing: false,
38
+ },
39
+ closingElement: { type: 'JSXClosingElement', name: { type: 'JSXIdentifier', name: 'div' } },
40
+ children: [],
41
+ },
42
+ },
43
+ },
44
+ })
45
+
46
+ const runPlugin = async (
47
+ seo: ComponentUIDL['seo'],
48
+ options: ComponentStructure['options'] = {}
49
+ ): Promise<string> => {
50
+ const plugin = createJSXHeadConfigPlugin()
51
+ const uidlSample = component('SimpleComponent', elementNode('container'))
52
+ uidlSample.node.content.key = 'container'
53
+ uidlSample.seo = seo
54
+ const structure: ComponentStructure = {
55
+ uidl: uidlSample,
56
+ options,
57
+ chunks: [makeJsxChunk()],
58
+ dependencies: {},
59
+ }
60
+ await plugin(structure)
61
+ const astNode = structure.chunks[0].meta.nodesLookup.container as types.JSXElement
62
+ return generator(astNode.children[0] as unknown as types.Node).code
63
+ }
64
+
65
+ const i18n = {
66
+ internationalization: {
67
+ main: { name: 'English', locale: 'en' },
68
+ languages: { en: 'English', ro: 'Romanian' } as Record<string, string>,
69
+ },
70
+ }
71
+
72
+ const slugByLocale = {
73
+ type: 'dynamic' as const,
74
+ content: { referenceType: 'prop' as const, refPath: ['blogPost', 'slugByLocale'] },
75
+ }
76
+
77
+ describe('hreflang with a slug per locale', () => {
78
+ it('reads each locale’s own slug from the row, falling back to the route parameter', async () => {
79
+ const code = await runPlugin(
80
+ {
81
+ assets: [
82
+ {
83
+ type: 'canonical',
84
+ path: 'https://acme.example/blog/[slug]',
85
+ localizedParams: { slug: slugByLocale },
86
+ },
87
+ ],
88
+ },
89
+ i18n
90
+ )
91
+ expect(code).toContain(
92
+ `hrefLang="ro" href={\`https://acme.example/ro/blog/\${props?.blogPost?.slugByLocale?.["ro"] ?? router.query.slug}\`}`
93
+ )
94
+ expect(code).toContain(
95
+ `hrefLang="en" href={\`https://acme.example/blog/\${props?.blogPost?.slugByLocale?.["en"] ?? router.query.slug}\`}`
96
+ )
97
+ expect(code).toContain(
98
+ `hrefLang="x-default" href={\`https://acme.example/blog/\${props?.blogPost?.slugByLocale?.["en"] ?? router.query.slug}\`}`
99
+ )
100
+ })
101
+
102
+ it('keeps the route parameter alone for a page without localized values', async () => {
103
+ const code = await runPlugin(
104
+ { assets: [{ type: 'canonical', path: 'https://acme.example/blog/[slug]' }] },
105
+ i18n
106
+ )
107
+ expect(code).toContain(
108
+ `hrefLang="ro" href={\`https://acme.example/ro/blog/\${router.query.slug}\`}`
109
+ )
110
+ })
111
+ })
112
+
113
+ describe('a paged listing', () => {
114
+ it('names the page in the canonical and og:url from the second page on', async () => {
115
+ const code = await runPlugin({
116
+ assets: [{ type: 'canonical', path: 'https://acme.example/blog', pageParam: 'page' }],
117
+ })
118
+ const suffix = `Number(router.query.page) > 1 ? \`?page=\${router.query.page}\` : ""`
119
+ expect(code).toContain(`rel="canonical" href={"https://acme.example/blog" + (${suffix})}`)
120
+ expect(code).toContain(`property="og:url" content={"https://acme.example/blog" + (${suffix})}`)
121
+ })
122
+
123
+ it('does the same under several locales', async () => {
124
+ const code = await runPlugin(
125
+ { assets: [{ type: 'canonical', path: 'https://acme.example/blog', pageParam: 'page' }] },
126
+ i18n
127
+ )
128
+ expect(code).toContain(
129
+ `rel="canonical" href={\`https://acme.example\${router.locale === router.defaultLocale ? "" : "/" + router.locale}/blog\` + (Number(router.query.page) > 1 ? \`?page=\${router.query.page}\` : "")}`
130
+ )
131
+ })
132
+ })
@@ -594,7 +594,7 @@ describe('plugin-jsx-head-config', () => {
594
594
  expect(code).toMatch(/\.replace\(\/<\/g/)
595
595
  })
596
596
 
597
- it('Should emit multiple JSON-LD scripts', async () => {
597
+ it('Should emit every JSON-LD entry in ONE script, as a JSON-LD array', async () => {
598
598
  const uidlSample = component('SimpleComponent', elementNode('container'))
599
599
  uidlSample.node.content.key = 'container'
600
600
  uidlSample.seo = {
@@ -613,13 +613,67 @@ describe('plugin-jsx-head-config', () => {
613
613
 
614
614
  const astNode = freshChunk.meta.nodesLookup.container as types.JSXElement
615
615
  const helmetNode = astNode.children[0] as types.JSXElement
616
- expect(helmetNode.children.length).toBe(2)
617
- expect((helmetNode.children[0] as types.JSXElement).openingElement.name).toMatchObject({
618
- name: 'script',
619
- })
620
- expect((helmetNode.children[1] as types.JSXElement).openingElement.name).toMatchObject({
621
- name: 'script',
622
- })
616
+ expect(helmetNode.children.length).toBe(1)
617
+ const code = codeOf(helmetNode.children[0] as types.JSXElement)
618
+ // Neighbouring pre-serialized documents are joined into one literal.
619
+ expect(code).toContain(
620
+ '__html: "[{\\"@type\\":\\"WebSite\\"},{\\"@type\\":\\"Organization\\"}]"'
621
+ )
622
+ })
623
+
624
+ it('Should join pre-serialized, route-bound and entity-bound entries into one valid array', async () => {
625
+ const uidlSample = component('SimpleComponent', elementNode('container'))
626
+ uidlSample.node.content.key = 'container'
627
+ uidlSample.seo = {
628
+ structuredData: [
629
+ '{"@type":"WebSite","name":"Acme"}',
630
+ '{"@type":"BreadcrumbList","itemListElement":[{"@type":"ListItem","position":1,"item":"https://example.com/events/[id]"}]}',
631
+ {
632
+ '@type': 'Product',
633
+ name: {
634
+ type: 'dynamic',
635
+ content: { referenceType: 'prop', id: 'root', refPath: ['product', 'name'] },
636
+ },
637
+ },
638
+ ],
639
+ }
640
+
641
+ const freshChunk = createFreshJsxChunk()
642
+ const structure: ComponentStructure = {
643
+ uidl: uidlSample,
644
+ options: {},
645
+ chunks: [freshChunk],
646
+ dependencies: {},
647
+ }
648
+
649
+ await plugin(structure)
650
+
651
+ const astNode = freshChunk.meta.nodesLookup.container as types.JSXElement
652
+ const helmetNode = astNode.children[0] as types.JSXElement
653
+ expect(helmetNode.children.length).toBe(1)
654
+ expect(structure.dependencies.useRouter).toBeDefined()
655
+
656
+ const script = helmetNode.children[0] as types.JSXElement
657
+ const attribute = script.openingElement.attributes.find(
658
+ (attr) => types.isJSXAttribute(attr) && attr.name.name === 'dangerouslySetInnerHTML'
659
+ ) as types.JSXAttribute
660
+ const html = (
661
+ (attribute.value as types.JSXExpressionContainer).expression as types.ObjectExpression
662
+ ).properties[0] as types.ObjectProperty
663
+ // tslint:disable-next-line:function-constructor
664
+ const evaluate = new Function('props', 'router', `return ${codeOf(html.value)}`)
665
+ const text = evaluate({ product: { name: 'Mug </script>' } }, { query: { id: '42' } })
666
+ expect(JSON.parse(text)).toEqual([
667
+ { '@type': 'WebSite', name: 'Acme' },
668
+ {
669
+ '@type': 'BreadcrumbList',
670
+ itemListElement: [
671
+ { '@type': 'ListItem', position: 1, item: 'https://example.com/events/42' },
672
+ ],
673
+ },
674
+ { '@type': 'Product', name: 'Mug </script>' },
675
+ ])
676
+ expect(text).not.toContain('</script>')
623
677
  })
624
678
 
625
679
  it('Should not change output when no structuredData is present', async () => {
@@ -36,7 +36,7 @@ const productEntry = (): UIDLStructuredDataObject => ({
36
36
 
37
37
  /** Renders the `__html` expression and evaluates it against a page-props object. */
38
38
  const renderJsonLd = (props: Record<string, unknown>): Record<string, unknown> => {
39
- const { scriptTag } = buildStructuredDataScript(productEntry())
39
+ const { scriptTag } = buildStructuredDataScript([productEntry()])
40
40
  const attribute = scriptTag.openingElement.attributes.find(
41
41
  (attr) => types.isJSXAttribute(attr) && attr.name.name === 'dangerouslySetInnerHTML'
42
42
  ) as types.JSXAttribute
@@ -102,15 +102,17 @@ describe('structured data — aggregateRating', () => {
102
102
  })
103
103
 
104
104
  it('falls back to `column` when no rating value column was given', () => {
105
- const { scriptTag } = buildStructuredDataScript({
106
- '@type': 'Product',
107
- aggregateRating: {
108
- type: 'computed',
109
- kind: 'aggregateRating',
110
- refPath: ['p'],
111
- column: 'ratingCount',
105
+ const { scriptTag } = buildStructuredDataScript([
106
+ {
107
+ '@type': 'Product',
108
+ aggregateRating: {
109
+ type: 'computed',
110
+ kind: 'aggregateRating',
111
+ refPath: ['p'],
112
+ column: 'ratingCount',
113
+ },
112
114
  },
113
- })
115
+ ])
114
116
  const code = generate(scriptTag).code
115
117
  // Degrades to using the count for both rather than emitting `undefined` as
116
118
  // the score, which would produce a malformed block.
@@ -0,0 +1,165 @@
1
+ import * as types from '@babel/types'
2
+ import generate from '@babel/generator'
3
+ import { UIDLStructuredDataEntry } from '@teleporthq/teleport-types'
4
+ import { buildStructuredDataScript } from '../src/structured-data-ast'
5
+
6
+ /**
7
+ * The computed entries a blog post page needs: a FAQPage built from the FAQ
8
+ * pairs the post's body holds (present only with two or more), and a
9
+ * BreadcrumbList whose category crumb exists only when the post has one —
10
+ * with positions that stay sequential either way. Both are WHOLE entries, so
11
+ * an absent one has to leave the JSON-LD array, not sit in it as a hole.
12
+ */
13
+
14
+ const evaluate = (entries: UIDLStructuredDataEntry[], props: Record<string, unknown>): unknown => {
15
+ const { scriptTag } = buildStructuredDataScript(entries)
16
+ const attribute = scriptTag.openingElement.attributes.find(
17
+ (attr) => types.isJSXAttribute(attr) && attr.name.name === 'dangerouslySetInnerHTML'
18
+ ) as types.JSXAttribute
19
+ const container = attribute.value as types.JSXExpressionContainer
20
+ const objectExpression = container.expression as types.ObjectExpression
21
+ const htmlProperty = objectExpression.properties[0] as types.ObjectProperty
22
+ const source = generate(htmlProperty.value as types.Expression).code
23
+ // eslint-disable-next-line no-new-func
24
+ const run = new Function('props', `return (${source});`) as (p: Record<string, unknown>) => string
25
+ const text = run(props)
26
+ return text ? JSON.parse(text) : null
27
+ }
28
+
29
+ const ARTICLE: UIDLStructuredDataEntry = {
30
+ '@context': 'https://schema.org',
31
+ '@type': 'BlogPosting',
32
+ headline: { type: 'dynamic', content: { referenceType: 'prop', refPath: ['blogPost', 'title'] } },
33
+ }
34
+
35
+ const FAQ: UIDLStructuredDataEntry = {
36
+ type: 'computed',
37
+ kind: 'faqPage',
38
+ refPath: ['blogPost'],
39
+ column: 'faq',
40
+ }
41
+
42
+ const TRAIL: UIDLStructuredDataEntry = {
43
+ type: 'computed',
44
+ kind: 'breadcrumbTrail',
45
+ refPath: ['blogPost'],
46
+ column: 'title',
47
+ slugColumn: 'slug',
48
+ urlPrefix: 'https://acme.example/blog/',
49
+ crumbs: [
50
+ { name: 'Home', item: 'https://acme.example' },
51
+ { name: 'Blog', item: 'https://acme.example/blog' },
52
+ ],
53
+ categoryNameColumn: 'categoryName',
54
+ categorySlugColumn: 'categorySlug',
55
+ categoryUrlPrefix: 'https://acme.example/blog/category/',
56
+ }
57
+
58
+ describe('faqPage', () => {
59
+ it('lists the FAQ pairs as a FAQPage beside the article', () => {
60
+ const faq = [
61
+ { question: 'Is it free?', answer: 'Yes.' },
62
+ { question: 'How long?', answer: 'A day.' },
63
+ ]
64
+ const document = evaluate([ARTICLE, FAQ], { blogPost: { title: 'T', faq } }) as unknown[]
65
+ expect(document).toHaveLength(2)
66
+ expect(document[1]).toEqual({
67
+ '@context': 'https://schema.org',
68
+ '@type': 'FAQPage',
69
+ mainEntity: [
70
+ {
71
+ '@type': 'Question',
72
+ name: 'Is it free?',
73
+ acceptedAnswer: { '@type': 'Answer', text: 'Yes.' },
74
+ },
75
+ {
76
+ '@type': 'Question',
77
+ name: 'How long?',
78
+ acceptedAnswer: { '@type': 'Answer', text: 'A day.' },
79
+ },
80
+ ],
81
+ })
82
+ })
83
+
84
+ it('leaves the array without a hole when the post has fewer than two pairs', () => {
85
+ const one = [{ question: 'Only one?', answer: 'Yes.' }]
86
+ expect(evaluate([ARTICLE, FAQ], { blogPost: { title: 'T', faq: one } })).toEqual([
87
+ { '@context': 'https://schema.org', '@type': 'BlogPosting', headline: 'T' },
88
+ ])
89
+ expect(evaluate([ARTICLE, FAQ], { blogPost: { title: 'T' } })).toHaveLength(1)
90
+ // Alone, an absent entry leaves an empty script rather than the word "undefined".
91
+ expect(evaluate([FAQ], { blogPost: {} })).toBeNull()
92
+ })
93
+ })
94
+
95
+ describe('breadcrumbTrail', () => {
96
+ it('puts the category between the listing and the post, positions in order', () => {
97
+ const trail = evaluate([TRAIL], {
98
+ blogPost: {
99
+ title: 'Seven checks',
100
+ slug: 'seven-checks',
101
+ categoryName: 'Cars',
102
+ categorySlug: 'cars',
103
+ },
104
+ }) as Record<string, unknown>
105
+ expect(trail).toEqual({
106
+ '@context': 'https://schema.org',
107
+ '@type': 'BreadcrumbList',
108
+ itemListElement: [
109
+ { '@type': 'ListItem', position: 1, name: 'Home', item: 'https://acme.example' },
110
+ { '@type': 'ListItem', position: 2, name: 'Blog', item: 'https://acme.example/blog' },
111
+ {
112
+ '@type': 'ListItem',
113
+ position: 3,
114
+ name: 'Cars',
115
+ item: 'https://acme.example/blog/category/cars',
116
+ },
117
+ {
118
+ '@type': 'ListItem',
119
+ position: 4,
120
+ name: 'Seven checks',
121
+ item: 'https://acme.example/blog/seven-checks',
122
+ },
123
+ ],
124
+ })
125
+ })
126
+
127
+ it('skips the category crumb for a post without one, keeping positions sequential', () => {
128
+ const trail = evaluate([TRAIL], {
129
+ blogPost: { title: 'Seven checks', slug: 'seven-checks', categoryName: null },
130
+ }) as Record<string, unknown>
131
+ expect(
132
+ (trail.itemListElement as Array<{ position: number; name: string }>).map((c) => [
133
+ c.position,
134
+ c.name,
135
+ ])
136
+ ).toEqual([
137
+ [1, 'Home'],
138
+ [2, 'Blog'],
139
+ [3, 'Seven checks'],
140
+ ])
141
+ })
142
+ })
143
+
144
+ describe('a category crumb without an address', () => {
145
+ it('is left out when the row names a category but has no slug for it', () => {
146
+ const trail = evaluate([TRAIL], {
147
+ blogPost: {
148
+ title: 'Seven checks',
149
+ slug: 'seven-checks',
150
+ categoryName: 'Cars',
151
+ categorySlug: null,
152
+ },
153
+ }) as Record<string, unknown>
154
+ expect(
155
+ (trail.itemListElement as Array<{ position: number; name: string }>).map((c) => [
156
+ c.position,
157
+ c.name,
158
+ ])
159
+ ).toEqual([
160
+ [1, 'Home'],
161
+ [2, 'Blog'],
162
+ [3, 'Seven checks'],
163
+ ])
164
+ })
165
+ })
@@ -27,7 +27,7 @@ const entry = (extra: UIDLStructuredDataObject): UIDLStructuredDataObject => ({
27
27
 
28
28
  /** The emitted JavaScript, as text. */
29
29
  const renderSource = (document: UIDLStructuredDataObject): string => {
30
- const { scriptTag } = buildStructuredDataScript(document)
30
+ const { scriptTag } = buildStructuredDataScript([document])
31
31
  const attribute = scriptTag.openingElement.attributes.find(
32
32
  (attr) => types.isJSXAttribute(attr) && attr.name.name === 'dangerouslySetInnerHTML'
33
33
  ) as types.JSXAttribute
@@ -41,7 +41,7 @@ const render = (
41
41
  document: UIDLStructuredDataObject,
42
42
  props: Record<string, unknown>
43
43
  ): Record<string, unknown> => {
44
- const { scriptTag } = buildStructuredDataScript(document)
44
+ const { scriptTag } = buildStructuredDataScript([document])
45
45
  const attribute = scriptTag.openingElement.attributes.find(
46
46
  (attr) => types.isJSXAttribute(attr) && attr.name.name === 'dangerouslySetInnerHTML'
47
47
  ) as types.JSXAttribute
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,eAAe,EAGf,sBAAsB,EACvB,MAAM,4BAA4B,CAAA;AAMnC,UAAU,mBAAmB;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,0BAA0B,CAAC,EAAE,MAAM,CAAA;IACnC,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,eAAO,MAAM,qBAAqB,EAAE,sBAUnC,CAAA;AAED,eAAO,MAAM,yBAAyB,EAAE,sBAAsB,CAAC,mBAAmB,CAqiBjF,CAAA;;AAED,wBAA0C"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,sBAAsB,EACtB,eAAe,EAGf,sBAAsB,EAEvB,MAAM,4BAA4B,CAAA;AAMnC,UAAU,mBAAmB;IAC3B,kBAAkB,CAAC,EAAE,MAAM,CAAA;IAC3B,mBAAmB,CAAC,EAAE,MAAM,CAAA;IAC5B,uBAAuB,CAAC,EAAE,MAAM,CAAA;IAChC,0BAA0B,CAAC,EAAE,MAAM,CAAA;IACnC,iBAAiB,CAAC,EAAE,OAAO,CAAA;IAC3B,eAAe,CAAC,EAAE,OAAO,CAAA;CAC1B;AAED,eAAO,MAAM,qBAAqB,EAAE,sBAUnC,CAAA;AAED,eAAO,MAAM,yBAAyB,EAAE,sBAAsB,CAAC,mBAAmB,CAqnBjF,CAAA;;AAED,wBAA0C"}