@plone/aurora 1.0.0-alpha.10

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 (41) hide show
  1. package/.release-it.json +32 -0
  2. package/.stylelintrc +8 -0
  3. package/CHANGELOG.md +251 -0
  4. package/LICENSE.md +21 -0
  5. package/Makefile +82 -0
  6. package/README.md +61 -0
  7. package/acceptance/tests/basic.test.ts +14 -0
  8. package/app/config/index.test.ts +19 -0
  9. package/app/config/index.ts +15 -0
  10. package/app/config/server/content-migrations.server.test.ts +184 -0
  11. package/app/config/server/content-migrations.server.ts +59 -0
  12. package/app/config/server/migrations.server.ts +137 -0
  13. package/app/config/server.server.test.ts +33 -0
  14. package/app/config/server.server.ts +52 -0
  15. package/app/config/types.ts +49 -0
  16. package/app/entry.client.tsx +51 -0
  17. package/app/entry.server.tsx +81 -0
  18. package/app/i18n.ts +11 -0
  19. package/app/i18next.server.ts +26 -0
  20. package/app/middleware.server.test.ts +1088 -0
  21. package/app/middleware.server.ts +241 -0
  22. package/app/okroute.test.tsx +9 -0
  23. package/app/okroute.tsx +5 -0
  24. package/app/reset-fetcher.test.tsx +13 -0
  25. package/app/reset-fetcher.tsx +7 -0
  26. package/app/root.test.tsx +300 -0
  27. package/app/root.tsx +188 -0
  28. package/app/routes.ts +20 -0
  29. package/news/.gitkeep +0 -0
  30. package/package.json +104 -0
  31. package/public/favicon.ico +0 -0
  32. package/public/icon.svg +13 -0
  33. package/react-router.config.ts +5 -0
  34. package/registry-publicui.config.ts +11 -0
  35. package/registry.config.ts +13 -0
  36. package/tests/setup.ts +6 -0
  37. package/tests/testHelpers.tsx +29 -0
  38. package/towncrier.toml +33 -0
  39. package/tsconfig.json +35 -0
  40. package/vite.config.ts +111 -0
  41. package/vitest.config.ts +32 -0
@@ -0,0 +1,241 @@
1
+ import { jwtDecode } from 'jwt-decode';
2
+ import { data, createContext, redirect } from 'react-router';
3
+ import { flattenToAppURL } from '@plone/helpers';
4
+ import { clearAuthOnResponse, getAuthFromRequest } from '@plone/react-router';
5
+ import config from '@plone/registry';
6
+ import type PloneClient from '@plone/client';
7
+ import type { Route } from './+types/root';
8
+ import installServer from './config/server.server';
9
+ import { migrateContent } from './config/server/content-migrations.server';
10
+
11
+ export const ploneClientContext = createContext<PloneClient>();
12
+ export const ploneContentContext =
13
+ createContext<Awaited<ReturnType<PloneClient['getContent']>>['data']>();
14
+ export const ploneSiteContext =
15
+ createContext<Awaited<ReturnType<PloneClient['getSite']>>['data']>();
16
+ export const ploneUserContext = createContext<
17
+ Awaited<ReturnType<PloneClient['getUser']>>['data'] | null
18
+ >(null);
19
+ export const ploneClearAuthCookieContext = createContext<boolean>(false);
20
+
21
+ function getAuthorizedResourceHeaders(
22
+ request: Request,
23
+ token?: string,
24
+ ): HeadersInit {
25
+ const headers = new Headers(request.headers);
26
+
27
+ if (token) {
28
+ headers.set('Authorization', `Bearer ${token}`);
29
+ } else {
30
+ headers.delete('Authorization');
31
+ }
32
+
33
+ return headers;
34
+ }
35
+
36
+ export const installServerMiddleware: Route.MiddlewareFunction = async (
37
+ { request, context },
38
+ next,
39
+ ) => {
40
+ installServer();
41
+ };
42
+
43
+ export const PloneClientMiddleware: Route.MiddlewareFunction = async (
44
+ { request, context },
45
+ next,
46
+ ) => {
47
+ const token = await getAuthFromRequest(request);
48
+
49
+ const PloneClient = config
50
+ .getUtility({
51
+ name: 'ploneClient',
52
+ type: 'client',
53
+ })
54
+ .method();
55
+
56
+ const cli = PloneClient.initialize({
57
+ apiPath: config.settings.apiPath,
58
+ token,
59
+ });
60
+
61
+ context.set(ploneClientContext, cli);
62
+ };
63
+
64
+ export const otherResources: Route.MiddlewareFunction = async (
65
+ { request, params, context },
66
+ next,
67
+ ) => {
68
+ const path = `/${params['*'] || ''}`;
69
+
70
+ // Ignore requests for some specific paths
71
+ if (/.well-known\/appspecific\/com.chrome.devtools.json/.test(path)) {
72
+ throw Response.json({});
73
+ }
74
+
75
+ if (
76
+ /^https?:\/\//.test(path) ||
77
+ /^favicon.ico\/\//.test(path) ||
78
+ /expand/.test(path) ||
79
+ /^\/assets/.test(path) ||
80
+ /\.(css|css\.map)$/.test(path)
81
+ ) {
82
+ // eslint-disable-next-line no-console
83
+ console.log('matched path not fetched', path);
84
+ throw data('Content Not Found', { status: 404 });
85
+ }
86
+ };
87
+
88
+ export const getAPIResourceWithAuth: Route.MiddlewareFunction = async (
89
+ { request, params },
90
+ next,
91
+ ) => {
92
+ const path = `/${params['*'] || ''}`;
93
+
94
+ if (
95
+ /\/@@images\//.test(path) ||
96
+ /\/@@download\//.test(path) ||
97
+ /\/@@site-logo\//.test(path) ||
98
+ /\/@portrait\//.test(path)
99
+ ) {
100
+ const token = await getAuthFromRequest(request);
101
+ const url = `${config.settings.apiPath}${path}`;
102
+ const response = await fetch(url, {
103
+ method: 'GET',
104
+ headers: getAuthorizedResourceHeaders(request, token),
105
+ });
106
+
107
+ if (token && response.status === 401) {
108
+ const anonymousResponse = await fetch(url, {
109
+ method: 'GET',
110
+ headers: getAuthorizedResourceHeaders(request),
111
+ });
112
+
113
+ if (anonymousResponse.ok) {
114
+ return clearAuthOnResponse(
115
+ new Response(anonymousResponse.body, {
116
+ status: anonymousResponse.status,
117
+ statusText: anonymousResponse.statusText,
118
+ headers: anonymousResponse.headers,
119
+ }),
120
+ );
121
+ }
122
+
123
+ return clearAuthOnResponse(
124
+ new Response(response.body, {
125
+ status: response.status,
126
+ statusText: response.statusText,
127
+ headers: response.headers,
128
+ }),
129
+ );
130
+ }
131
+
132
+ return response;
133
+ }
134
+ };
135
+
136
+ export const fetchPloneContent: Route.MiddlewareFunction = async (
137
+ { request, params, context },
138
+ next,
139
+ ) => {
140
+ const expand = ['navroot', 'breadcrumbs', 'navigation', 'actions'];
141
+ const token = await getAuthFromRequest(request);
142
+
143
+ let cli = context.get(ploneClientContext);
144
+
145
+ const path = `/${params['*'] || ''}`;
146
+
147
+ let userId = '';
148
+ if (token) {
149
+ try {
150
+ const decodedToken = jwtDecode<{
151
+ sub: string;
152
+ exp: number;
153
+ fullname: string | null;
154
+ }>(token);
155
+ userId = decodedToken.sub || '';
156
+ } catch {}
157
+ }
158
+
159
+ if (userId) expand.push('types');
160
+
161
+ const setPloneContext = (
162
+ content: Awaited<ReturnType<PloneClient['getContent']>>,
163
+ site: Awaited<ReturnType<PloneClient['getSite']>>,
164
+ user: Awaited<ReturnType<PloneClient['getUser']>>['data'] | null,
165
+ ) => {
166
+ migrateContent(content.data);
167
+
168
+ context.set(ploneContentContext, flattenToAppURL(content.data));
169
+ context.set(ploneSiteContext, flattenToAppURL(site.data));
170
+ context.set(ploneUserContext, user);
171
+ };
172
+
173
+ try {
174
+ const [content, site, user] = await Promise.all([
175
+ cli.getContent({ path, expand }),
176
+ cli.getSite(),
177
+ userId ? cli.getUser({ id: userId }).catch(() => null) : null,
178
+ ]);
179
+
180
+ setPloneContext(content, site, user?.data ?? null);
181
+ } catch (error: any) {
182
+ if (error.status >= 300 && error.status < 400 && error.location) {
183
+ return redirect(error.location, {
184
+ status: error.status,
185
+ });
186
+ }
187
+ if (token && error?.status === 401) {
188
+ const PloneClient = config
189
+ .getUtility({
190
+ name: 'ploneClient',
191
+ type: 'client',
192
+ })
193
+ .method();
194
+ cli = PloneClient.initialize({
195
+ apiPath: config.settings.apiPath,
196
+ });
197
+ context.set(ploneClientContext, cli);
198
+
199
+ try {
200
+ const [content, site] = await Promise.all([
201
+ cli.getContent({
202
+ path,
203
+ expand: expand.filter((item) => item !== 'types'),
204
+ }),
205
+ cli.getSite(),
206
+ ]);
207
+
208
+ setPloneContext(content, site, null);
209
+ context.set(ploneClearAuthCookieContext, true);
210
+ return;
211
+ } catch (anonymousError: any) {
212
+ throw data('Content Not Found', {
213
+ status:
214
+ typeof anonymousError.status === 'number'
215
+ ? anonymousError.status
216
+ : 500,
217
+ });
218
+ }
219
+ }
220
+
221
+ throw data('Content Not Found', {
222
+ status: typeof error.status === 'number' ? error.status : 500,
223
+ });
224
+ }
225
+ };
226
+
227
+ export const linkMiddleware: Route.MiddlewareFunction = async (
228
+ { context },
229
+ next,
230
+ ) => {
231
+ const content = context.get(ploneContentContext);
232
+
233
+ if (
234
+ content['@type'] === 'Link' &&
235
+ !content['@components'].actions.object.find(
236
+ (action) => action.id === 'edit',
237
+ )
238
+ ) {
239
+ return redirect(content.remoteUrl);
240
+ }
241
+ };
@@ -0,0 +1,9 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { loader } from './okroute';
3
+
4
+ describe('okroute', () => {
5
+ it('should return a 200 response', async () => {
6
+ const response = await loader();
7
+ expect(response.status).toBe(200);
8
+ });
9
+ });
@@ -0,0 +1,5 @@
1
+ export async function loader() {
2
+ return new Response(null, {
3
+ status: 200,
4
+ });
5
+ }
@@ -0,0 +1,13 @@
1
+ import { expect, test } from 'vitest';
2
+
3
+ import { action, loader } from './reset-fetcher';
4
+
5
+ test('action function returns a response null', async () => {
6
+ const response = await action();
7
+ expect(response).toBe(null);
8
+ });
9
+
10
+ test('loader function returns a response null', async () => {
11
+ const response = await loader();
12
+ expect(response).toBe(null);
13
+ });
@@ -0,0 +1,7 @@
1
+ export const loader = async () => {
2
+ return null;
3
+ };
4
+
5
+ export async function action() {
6
+ return null;
7
+ }
@@ -0,0 +1,300 @@
1
+ import { expect, describe, it, vi, afterEach } from 'vitest';
2
+ import { render, screen } from '@testing-library/react';
3
+ import { createRoutesStub, RouterContextProvider } from 'react-router';
4
+ import config from '@plone/registry';
5
+ import { Layout, ErrorBoundary, loader } from './root';
6
+ import {
7
+ ploneClientContext,
8
+ ploneClearAuthCookieContext,
9
+ ploneContentContext,
10
+ ploneSiteContext,
11
+ } from './middleware.server';
12
+ import { migrateContent } from './config/server/content-migrations.server';
13
+ import { renderWithI18n } from '../tests/testHelpers';
14
+
15
+ vi.mock('./i18next.server', () => ({
16
+ i18nextMiddleware: vi.fn(),
17
+ getLocale: vi.fn().mockReturnValue('en'),
18
+ }));
19
+
20
+ async function renderStub() {
21
+ const Stub = createRoutesStub([
22
+ {
23
+ path: '/',
24
+ Component: () => (
25
+ <Layout
26
+ params={{}}
27
+ loaderData={{
28
+ locale: 'en',
29
+ content: {} as any,
30
+ site: {} as any,
31
+ isAuthenticated: false,
32
+ }}
33
+ matches={[{} as any]}
34
+ >
35
+ <p>Root Layout</p>
36
+ </Layout>
37
+ ),
38
+ // a fallback is needed
39
+ HydrateFallback: () => <></>,
40
+ loader() {
41
+ return {
42
+ content: {},
43
+ locale: 'en',
44
+ };
45
+ },
46
+ },
47
+ ]);
48
+
49
+ await renderWithI18n(<Stub initialEntries={['/']} />);
50
+ }
51
+
52
+ const registerSomersaultBlockMigrations = () => {
53
+ config.registerUtility({
54
+ name: 'testSomersaultBlockMigrationTitle',
55
+ type: 'somersaultBlockMigration',
56
+ method: ({ block, content }) =>
57
+ block['@type'] === 'title'
58
+ ? [
59
+ {
60
+ type: 'title',
61
+ children: [
62
+ {
63
+ text: typeof content.title === 'string' ? content.title : '',
64
+ },
65
+ ],
66
+ },
67
+ ]
68
+ : [],
69
+ });
70
+
71
+ config.registerUtility({
72
+ name: 'testSomersaultBlockMigrationLegacyValue',
73
+ type: 'somersaultBlockMigration',
74
+ method: ({ block }) => (Array.isArray(block.value) ? block.value : []),
75
+ });
76
+ };
77
+
78
+ afterEach(() => {
79
+ vi.restoreAllMocks();
80
+ config.settings = {};
81
+ const utilities = config.utilities as Partial<Record<string, unknown>>;
82
+ delete utilities.client;
83
+ delete utilities.somersaultBlockMigration;
84
+ delete utilities.somersaultMigration;
85
+ delete utilities.rootContentSubRequest;
86
+ delete utilities.rootLoaderData;
87
+ });
88
+
89
+ describe('loader', () => {
90
+ it('should return content and site from context', async () => {
91
+ config.settings.defaultLanguage = 'en';
92
+ config.settings.supportedLanguages = ['en'];
93
+ const mockContent = { '@id': 'http://example.com/', title: 'Home' };
94
+ const mockSite = { '@id': 'http://example.com/' };
95
+ const request = new Request('http://example.com');
96
+ const context = new RouterContextProvider();
97
+ context.set(ploneClientContext, {} as any);
98
+ context.set(ploneContentContext, mockContent as any);
99
+ context.set(ploneSiteContext, mockSite as any);
100
+
101
+ const result = await loader({
102
+ request,
103
+ params: {},
104
+ context,
105
+ pattern: '/',
106
+ url: new URL(request.url),
107
+ });
108
+
109
+ expect(result.data.locale).toBe('en');
110
+ expect(result.data.content).toBeDefined();
111
+ expect(result.data.site).toBeDefined();
112
+ });
113
+
114
+ it('should return content for a non-root path', async () => {
115
+ config.settings.defaultLanguage = 'en';
116
+ config.settings.supportedLanguages = ['en'];
117
+ const mockContent = {
118
+ '@id': 'http://example.com/test-content',
119
+ title: 'Test',
120
+ };
121
+ const mockSite = { '@id': 'http://example.com/' };
122
+ const request = new Request('http://example.com/test-content');
123
+ const context = new RouterContextProvider();
124
+ context.set(ploneClientContext, {} as any);
125
+ context.set(ploneContentContext, mockContent as any);
126
+ context.set(ploneSiteContext, mockSite as any);
127
+
128
+ const result = await loader({
129
+ request,
130
+ params: { '*': 'test-content' },
131
+ context,
132
+ pattern: '/test-content',
133
+ url: new URL(request.url),
134
+ });
135
+
136
+ expect(result.data.locale).toBe('en');
137
+ expect(result.data.content).toBeDefined();
138
+ expect(result.data.site).toBeDefined();
139
+ });
140
+
141
+ it('should clear the auth cookie when middleware requests it', async () => {
142
+ config.settings.defaultLanguage = 'en';
143
+ config.settings.supportedLanguages = ['en'];
144
+ const mockContent = { '@id': 'http://example.com/', title: 'Home' };
145
+ const mockSite = { '@id': 'http://example.com/' };
146
+ const request = new Request('http://example.com');
147
+ const context = new RouterContextProvider();
148
+ context.set(ploneClientContext, {} as any);
149
+ context.set(ploneContentContext, mockContent as any);
150
+ context.set(ploneSiteContext, mockSite as any);
151
+ context.set(ploneClearAuthCookieContext, true);
152
+
153
+ const result = (await loader({
154
+ request,
155
+ params: {},
156
+ context,
157
+ pattern: '/',
158
+ url: new URL(request.url),
159
+ })) as any;
160
+
161
+ expect(result.data.content).toEqual(mockContent);
162
+ expect(result.init.headers['Set-Cookie']).toContain('auth_seven=');
163
+ });
164
+ });
165
+
166
+ describe('Layout', () => {
167
+ it('should render the root Layout', async () => {
168
+ await renderStub();
169
+ expect(await screen.findByText('Root Layout')).toBeInTheDocument();
170
+ });
171
+ });
172
+
173
+ describe('ErrorBoundary', () => {
174
+ it('should render the error message', async () => {
175
+ const error = new Error('Test error');
176
+ render(<ErrorBoundary error={error} params={{}} />);
177
+ expect(screen.getByText('Test error')).toBeInTheDocument();
178
+ });
179
+ });
180
+
181
+ it('should place the migrated title block in the legacy block order', async () => {
182
+ const mockContent = {
183
+ '@id': 'http://example.com/',
184
+ title: 'Page title',
185
+ blocks: {
186
+ a: {
187
+ '@type': 'text',
188
+ value: [{ type: 'p', children: [{ text: 'First block' }] }],
189
+ },
190
+ titleBlock: {
191
+ '@type': 'title',
192
+ },
193
+ b: {
194
+ '@type': 'text',
195
+ value: [{ type: 'p', children: [{ text: 'Second block' }] }],
196
+ },
197
+ },
198
+ blocks_layout: {
199
+ items: ['a', 'titleBlock', 'b'],
200
+ },
201
+ };
202
+ const mockSite = { '@id': 'http://example.com/' };
203
+ const somersaultMigration = vi.fn(({ value }) => value);
204
+ config.settings.defaultLanguage = 'en';
205
+ config.settings.supportedLanguages = ['en'];
206
+ registerSomersaultBlockMigrations();
207
+ config.registerUtility({
208
+ name: 'testSomersaultMigration',
209
+ type: 'somersaultMigration',
210
+ method: somersaultMigration,
211
+ });
212
+ const request = new Request('http://example.com');
213
+ migrateContent(mockContent as any);
214
+ const context = new RouterContextProvider();
215
+ context.set(ploneClientContext, {} as any);
216
+ context.set(ploneContentContext, mockContent as any);
217
+ context.set(ploneSiteContext, mockSite as any);
218
+
219
+ const result = await loader({
220
+ request,
221
+ params: {},
222
+ context,
223
+ pattern: '/',
224
+ url: new URL(request.url),
225
+ });
226
+
227
+ expect(somersaultMigration).toHaveBeenCalledTimes(1);
228
+ expect(result.data.content.blocks.__somersault__).toEqual({
229
+ '@type': '__somersault__',
230
+ value: [
231
+ {
232
+ type: 'p',
233
+ children: [{ text: 'First block' }],
234
+ },
235
+ {
236
+ type: 'title',
237
+ children: [{ text: 'Page title' }],
238
+ },
239
+ {
240
+ type: 'p',
241
+ children: [{ text: 'Second block' }],
242
+ },
243
+ ],
244
+ });
245
+ });
246
+
247
+ it('should skip somersault migration when the somersault block already exists', async () => {
248
+ const existingSomersaultValue = [
249
+ {
250
+ type: 'title',
251
+ children: [{ text: 'Already migrated' }],
252
+ },
253
+ ];
254
+ const mockContent = {
255
+ '@id': 'http://example.com/',
256
+ title: 'Page title',
257
+ blocks: {
258
+ __somersault__: {
259
+ '@type': '__somersault__',
260
+ value: existingSomersaultValue,
261
+ },
262
+ a: {
263
+ '@type': 'text',
264
+ value: [{ type: 'p', children: [{ text: 'Legacy block' }] }],
265
+ },
266
+ },
267
+ blocks_layout: {
268
+ items: ['a'],
269
+ },
270
+ };
271
+ const mockSite = { '@id': 'http://example.com/' };
272
+ const somersaultMigration = vi.fn(({ value }) => value);
273
+ config.settings.defaultLanguage = 'en';
274
+ config.settings.supportedLanguages = ['en'];
275
+ registerSomersaultBlockMigrations();
276
+ config.registerUtility({
277
+ name: 'testSomersaultMigration',
278
+ type: 'somersaultMigration',
279
+ method: somersaultMigration,
280
+ });
281
+ const request = new Request('http://example.com');
282
+ migrateContent(mockContent as any);
283
+ const context = new RouterContextProvider();
284
+ context.set(ploneClientContext, {} as any);
285
+ context.set(ploneContentContext, mockContent as any);
286
+ context.set(ploneSiteContext, mockSite as any);
287
+ const result = await loader({
288
+ request,
289
+ params: {},
290
+ context,
291
+ pattern: '/',
292
+ url: new URL(request.url),
293
+ });
294
+
295
+ expect(somersaultMigration).not.toHaveBeenCalled();
296
+ expect(result.data.content.blocks.__somersault__).toEqual({
297
+ '@type': '__somersault__',
298
+ value: existingSomersaultValue,
299
+ });
300
+ });