create-o2s-app 4.1.10 → 4.1.11

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 (43) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/scaffold/get-aliases-to-remove.d.ts +9 -0
  3. package/dist/scaffold/get-aliases-to-remove.d.ts.map +1 -0
  4. package/dist/scaffold/get-aliases-to-remove.js +21 -0
  5. package/dist/scaffold/get-aliases-to-remove.spec.d.ts +2 -0
  6. package/dist/scaffold/get-aliases-to-remove.spec.d.ts.map +1 -0
  7. package/dist/scaffold/get-aliases-to-remove.spec.js +26 -0
  8. package/dist/scaffold/index.d.ts.map +1 -1
  9. package/dist/scaffold/index.js +2 -0
  10. package/dist/scaffold/transform-app-module.d.ts.map +1 -1
  11. package/dist/scaffold/transform-app-module.js +4 -15
  12. package/dist/scaffold/transform-blocks-config.d.ts +7 -0
  13. package/dist/scaffold/transform-blocks-config.d.ts.map +1 -0
  14. package/dist/scaffold/transform-blocks-config.js +134 -0
  15. package/dist/scaffold/transform-blocks-config.spec.d.ts +2 -0
  16. package/dist/scaffold/transform-blocks-config.spec.d.ts.map +1 -0
  17. package/dist/scaffold/transform-blocks-config.spec.js +190 -0
  18. package/dist/scaffold/transform-legacy-block-files.spec.d.ts +2 -0
  19. package/dist/scaffold/transform-legacy-block-files.spec.d.ts.map +1 -0
  20. package/dist/scaffold/transform-legacy-block-files.spec.js +89 -0
  21. package/dist/scaffold/transform-page-model.d.ts.map +1 -1
  22. package/dist/scaffold/transform-page-model.js +4 -15
  23. package/dist/scaffold/transform-real-files.spec.d.ts +2 -0
  24. package/dist/scaffold/transform-real-files.spec.d.ts.map +1 -0
  25. package/dist/scaffold/transform-real-files.spec.js +154 -0
  26. package/dist/scaffold/transform-render-blocks.d.ts.map +1 -1
  27. package/dist/scaffold/transform-render-blocks.js +63 -17
  28. package/dist/scaffold/transform-render-blocks.spec.d.ts +2 -0
  29. package/dist/scaffold/transform-render-blocks.spec.d.ts.map +1 -0
  30. package/dist/scaffold/transform-render-blocks.spec.js +126 -0
  31. package/package.json +3 -1
  32. package/src/scaffold/get-aliases-to-remove.spec.ts +30 -0
  33. package/src/scaffold/get-aliases-to-remove.ts +19 -0
  34. package/src/scaffold/index.ts +2 -0
  35. package/src/scaffold/transform-app-module.ts +4 -16
  36. package/src/scaffold/transform-blocks-config.spec.ts +215 -0
  37. package/src/scaffold/transform-blocks-config.ts +113 -0
  38. package/src/scaffold/transform-legacy-block-files.spec.ts +68 -0
  39. package/src/scaffold/transform-page-model.ts +4 -16
  40. package/src/scaffold/transform-real-files.spec.ts +153 -0
  41. package/src/scaffold/transform-render-blocks.spec.ts +129 -0
  42. package/src/scaffold/transform-render-blocks.ts +73 -18
  43. package/vitest.config.mjs +3 -0
@@ -0,0 +1,215 @@
1
+ import { transformBlocksConfig } from './transform-blocks-config';
2
+ import * as fs from 'fs-extra';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
6
+
7
+ const FILE_PATH = 'apps/api-harmonization/src/blocks.config.ts';
8
+
9
+ const BLOCKS_CONFIG = `import * as ArticleList from '@o2s/blocks.article-list/api-harmonization';
10
+ import * as Article from '@o2s/blocks.article/api-harmonization';
11
+ import * as Faq from '@o2s/blocks.faq/api-harmonization';
12
+ import * as HeroSection from '@o2s/blocks.hero-section/api-harmonization';
13
+
14
+ // BLOCK IMPORT
15
+
16
+ /**
17
+ * Central registry of the blocks used by this app.
18
+ */
19
+ export const blocks = [
20
+ Article,
21
+ ArticleList,
22
+ Faq,
23
+ HeroSection,
24
+ // BLOCK REGISTER
25
+ ];
26
+
27
+ export type Blocks =
28
+ // BLOCK TYPE
29
+ | Article.Model.ArticleBlock['__typename']
30
+ | ArticleList.Model.ArticleListBlock['__typename']
31
+ | Faq.Model.FaqBlock['__typename']
32
+ | HeroSection.Model.HeroSectionBlock['__typename'];
33
+ `;
34
+
35
+ describe('transformBlocksConfig', () => {
36
+ let projectDir: string;
37
+
38
+ const writeConfig = async (content: string) => {
39
+ await fs.outputFile(path.join(projectDir, FILE_PATH), content, 'utf-8');
40
+ };
41
+
42
+ const readConfig = () => fs.readFile(path.join(projectDir, FILE_PATH), 'utf-8');
43
+
44
+ beforeEach(async () => {
45
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'create-o2s-app-blocks-config-'));
46
+ });
47
+
48
+ afterEach(async () => {
49
+ await fs.remove(projectDir);
50
+ });
51
+
52
+ it('removes the import, registry entry and union member of unselected blocks', async () => {
53
+ await writeConfig(BLOCKS_CONFIG);
54
+
55
+ await transformBlocksConfig(projectDir, ['article', 'faq']);
56
+
57
+ expect(await readConfig()).toBe(`import * as Article from '@o2s/blocks.article/api-harmonization';
58
+ import * as Faq from '@o2s/blocks.faq/api-harmonization';
59
+
60
+ // BLOCK IMPORT
61
+
62
+ /**
63
+ * Central registry of the blocks used by this app.
64
+ */
65
+ export const blocks = [
66
+ Article,
67
+ Faq,
68
+ // BLOCK REGISTER
69
+ ];
70
+
71
+ export type Blocks =
72
+ // BLOCK TYPE
73
+ | Article.Model.ArticleBlock['__typename']
74
+ | Faq.Model.FaqBlock['__typename'];
75
+ `);
76
+ });
77
+
78
+ it('does not treat a block name as a prefix of another block name', async () => {
79
+ await writeConfig(BLOCKS_CONFIG);
80
+
81
+ await transformBlocksConfig(projectDir, ['article-list']);
82
+
83
+ const result = await readConfig();
84
+ expect(result).toContain("import * as ArticleList from '@o2s/blocks.article-list/api-harmonization';");
85
+ expect(result).not.toContain("from '@o2s/blocks.article/api-harmonization'");
86
+ expect(result).not.toMatch(/^\s+Article,$/m);
87
+ expect(result).toMatch(/^\s+ArticleList,$/m);
88
+ expect(result).not.toContain('Article.Model.ArticleBlock');
89
+ });
90
+
91
+ it('keeps the union terminated when its last member is removed', async () => {
92
+ await writeConfig(BLOCKS_CONFIG);
93
+
94
+ await transformBlocksConfig(projectDir, ['article', 'faq']);
95
+
96
+ expect(await readConfig()).toContain(" | Faq.Model.FaqBlock['__typename'];\n");
97
+ });
98
+
99
+ it('keeps the generator markers and a valid union when all blocks are removed', async () => {
100
+ await writeConfig(BLOCKS_CONFIG);
101
+
102
+ await transformBlocksConfig(projectDir, []);
103
+
104
+ const result = await readConfig();
105
+ expect(result).not.toContain('@o2s/blocks.');
106
+ expect(result).toContain('// BLOCK IMPORT');
107
+ expect(result).toContain('export const blocks = [\n // BLOCK REGISTER\n];');
108
+ expect(result).toContain('export type Blocks =\n // BLOCK TYPE\n | never;\n');
109
+ });
110
+
111
+ it('keeps the union terminated when it is defined in a different order than the imports', async () => {
112
+ await writeConfig(
113
+ BLOCKS_CONFIG.replace(
114
+ " | Faq.Model.FaqBlock['__typename']\n | HeroSection.Model.HeroSectionBlock['__typename'];",
115
+ " | HeroSection.Model.HeroSectionBlock['__typename']\n | Faq.Model.FaqBlock['__typename'];",
116
+ ),
117
+ );
118
+
119
+ await transformBlocksConfig(projectDir, ['faq', 'hero-section']);
120
+
121
+ const result = await readConfig();
122
+ expect(result).toContain(
123
+ " | HeroSection.Model.HeroSectionBlock['__typename']\n | Faq.Model.FaqBlock['__typename'];\n",
124
+ );
125
+ });
126
+
127
+ it('leaves the file untouched when every block is selected', async () => {
128
+ await writeConfig(BLOCKS_CONFIG);
129
+
130
+ await transformBlocksConfig(projectDir, ['article', 'article-list', 'faq', 'hero-section']);
131
+
132
+ expect(await readConfig()).toBe(BLOCKS_CONFIG);
133
+ });
134
+
135
+ it('does not remove non-block identifiers outside the blocks array', async () => {
136
+ const content = `import * as Faq from '@o2s/blocks.faq/api-harmonization';
137
+ import * as HeroSection from '@o2s/blocks.hero-section/api-harmonization';
138
+
139
+ const unrelated = {
140
+ HeroSection,
141
+ };
142
+
143
+ export const blocks = [
144
+ Faq,
145
+ HeroSection,
146
+ ];
147
+ `;
148
+ await writeConfig(content);
149
+
150
+ await transformBlocksConfig(projectDir, ['faq']);
151
+
152
+ const result = await readConfig();
153
+ expect(result).toContain('const unrelated = {\n HeroSection,\n};');
154
+ expect(result).toContain('export const blocks = [\n Faq,\n];');
155
+ });
156
+
157
+ it('keeps the union valid without the `// BLOCK TYPE` marker when all blocks are removed', async () => {
158
+ await writeConfig(BLOCKS_CONFIG.replace(' // BLOCK TYPE\n', ''));
159
+
160
+ await transformBlocksConfig(projectDir, []);
161
+
162
+ expect(await readConfig()).toContain('export type Blocks =\n | never;\n');
163
+ });
164
+
165
+ it('does not add a semicolon to an empty union that had none', async () => {
166
+ await writeConfig(
167
+ BLOCKS_CONFIG.replace(
168
+ " | HeroSection.Model.HeroSectionBlock['__typename'];",
169
+ " | HeroSection.Model.HeroSectionBlock['__typename']",
170
+ ),
171
+ );
172
+
173
+ await transformBlocksConfig(projectDir, []);
174
+
175
+ expect(await readConfig()).toContain(' // BLOCK TYPE\n | never\n');
176
+ });
177
+
178
+ it('warns when the `Blocks` union cannot be found after removing all its members', async () => {
179
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
180
+ await writeConfig(
181
+ BLOCKS_CONFIG.replace('export type Blocks =\n // BLOCK TYPE\n', 'export type Blocks = // union\n'),
182
+ );
183
+
184
+ await transformBlocksConfig(projectDir, []);
185
+
186
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('apps/api-harmonization/src/blocks.config.ts'));
187
+ warn.mockRestore();
188
+ });
189
+
190
+ it('handles a type-annotated blocks array', async () => {
191
+ await writeConfig(BLOCKS_CONFIG.replace('export const blocks = [', 'export const blocks: BlockModule[] = ['));
192
+
193
+ await transformBlocksConfig(projectDir, ['faq']);
194
+
195
+ expect(await readConfig()).toContain(
196
+ 'export const blocks: BlockModule[] = [\n Faq,\n // BLOCK REGISTER\n];',
197
+ );
198
+ });
199
+
200
+ it('handles a blocks array declared `as const`', async () => {
201
+ await writeConfig(BLOCKS_CONFIG.replace(' // BLOCK REGISTER\n];', ' // BLOCK REGISTER\n] as const;'));
202
+
203
+ await transformBlocksConfig(projectDir, ['faq']);
204
+
205
+ const result = await readConfig();
206
+ expect(result).toContain('export const blocks = [\n Faq,\n // BLOCK REGISTER\n] as const;');
207
+ // the union after the array is still processed
208
+ expect(result).toContain(" | Faq.Model.FaqBlock['__typename'];\n");
209
+ });
210
+
211
+ it('does nothing when blocks.config.ts does not exist', async () => {
212
+ await expect(transformBlocksConfig(projectDir, ['faq'])).resolves.toBeUndefined();
213
+ expect(await fs.pathExists(path.join(projectDir, FILE_PATH))).toBe(false);
214
+ });
215
+ });
@@ -0,0 +1,113 @@
1
+ import { getAliasesToRemove } from './get-aliases-to-remove';
2
+ import * as fs from 'fs-extra';
3
+ import kleur from 'kleur';
4
+ import * as path from 'path';
5
+
6
+ const FILE_PATH = 'apps/api-harmonization/src/blocks.config.ts';
7
+
8
+ // Regex matches: import * as Alias from '@o2s/blocks.<name>/api-harmonization';
9
+ const BLOCK_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api-harmonization';$/;
10
+
11
+ // Regex matches the start of the block registry, with an optional type annotation:
12
+ // export const blocks = [ / export const blocks: BlockModule[] = [
13
+ const BLOCKS_ARRAY_START_REGEX = /^export const blocks\s*(?::[^=]+)?=\s*\[\s*$/;
14
+
15
+ // Regex matches the end of the block registry: ]; / ] as const;
16
+ const BLOCKS_ARRAY_END_REGEX = /^\](?:\s+as\s+const)?;?\s*$/;
17
+
18
+ // Regex matches an entry of the block registry: Alias,
19
+ const BLOCK_ENTRY_REGEX = /^\s+(\w+),\s*$/;
20
+
21
+ // Regex matches: | Alias.Model.SomeTypenameBlock['__typename']
22
+ const UNION_TYPE_REGEX = /^\s+\| (\w+)\.Model\.\w+\['__typename'\]/;
23
+
24
+ // Regex matches the start of the union: export type Blocks =
25
+ const BLOCKS_TYPE_REGEX = /^export type Blocks\s*=\s*$/;
26
+
27
+ /**
28
+ * Removes unselected blocks from `blocks.config.ts`, the single place where the API harmonization
29
+ * app registers its blocks: the `import`, the entry in the `blocks` array and the member of the
30
+ * `Blocks` union.
31
+ */
32
+ export const transformBlocksConfig = async (projectDir: string, selectedBlockNames: string[]): Promise<void> => {
33
+ const filePath = path.join(projectDir, FILE_PATH);
34
+
35
+ if (!(await fs.pathExists(filePath))) return;
36
+
37
+ const content = await fs.readFile(filePath, 'utf-8');
38
+ const lines = content.split('\n');
39
+
40
+ const aliasesToRemove = getAliasesToRemove(lines, BLOCK_IMPORT_REGEX, selectedBlockNames);
41
+
42
+ if (aliasesToRemove.size === 0) return;
43
+
44
+ const result: string[] = [];
45
+ let insideBlocksArray = false;
46
+ let lastKeptUnionIndex = -1;
47
+ let removedUnionTerminator = false;
48
+ let unionMemberCount = 0;
49
+ let typeMarkerIndex = -1;
50
+ let blocksTypeIndex = -1;
51
+
52
+ for (const line of lines) {
53
+ if (BLOCKS_ARRAY_START_REGEX.test(line)) {
54
+ insideBlocksArray = true;
55
+ result.push(line);
56
+ continue;
57
+ }
58
+
59
+ if (insideBlocksArray) {
60
+ if (BLOCKS_ARRAY_END_REGEX.test(line)) {
61
+ insideBlocksArray = false;
62
+ } else {
63
+ const entryMatch = line.match(BLOCK_ENTRY_REGEX);
64
+ if (entryMatch && entryMatch[1] && aliasesToRemove.has(entryMatch[1])) continue;
65
+ }
66
+
67
+ result.push(line);
68
+ continue;
69
+ }
70
+
71
+ const importMatch = line.match(BLOCK_IMPORT_REGEX);
72
+ if (importMatch && importMatch[1] && aliasesToRemove.has(importMatch[1])) continue;
73
+
74
+ const unionMatch = line.match(UNION_TYPE_REGEX);
75
+ if (unionMatch && unionMatch[1]) {
76
+ unionMemberCount++;
77
+
78
+ if (aliasesToRemove.has(unionMatch[1])) {
79
+ // The removed member may carry the `;` that terminates the `Blocks` union.
80
+ if (line.trimEnd().endsWith(';')) removedUnionTerminator = true;
81
+ continue;
82
+ }
83
+
84
+ lastKeptUnionIndex = result.length;
85
+ }
86
+
87
+ if (line.includes('// BLOCK TYPE')) typeMarkerIndex = result.length;
88
+ if (BLOCKS_TYPE_REGEX.test(line)) blocksTypeIndex = result.length;
89
+
90
+ result.push(line);
91
+ }
92
+
93
+ if (unionMemberCount > 0 && lastKeptUnionIndex < 0) {
94
+ // Every block was removed: keep the union valid so the generator can still add blocks.
95
+ // Insert after the generator marker, or right after `export type Blocks =` without it.
96
+ const insertAfter = typeMarkerIndex >= 0 ? typeMarkerIndex : blocksTypeIndex;
97
+
98
+ if (insertAfter >= 0) {
99
+ result.splice(insertAfter + 1, 0, ` | never${removedUnionTerminator ? ';' : ''}`);
100
+ } else {
101
+ console.warn(
102
+ kleur.yellow(
103
+ `Warning: could not find the \`Blocks\` union in ${FILE_PATH}; it is left without members and the project will not build until you fix it.`,
104
+ ),
105
+ );
106
+ }
107
+ } else if (removedUnionTerminator && lastKeptUnionIndex >= 0) {
108
+ // Move the terminating `;` to the last remaining member of the union.
109
+ result[lastKeptUnionIndex] = `${result[lastKeptUnionIndex]?.trimEnd()};`;
110
+ }
111
+
112
+ await fs.writeFile(filePath, result.join('\n'), 'utf-8');
113
+ };
@@ -0,0 +1,68 @@
1
+ import { transformAppModule } from './transform-app-module';
2
+ import { transformPageModel } from './transform-page-model';
3
+ import * as fs from 'fs-extra';
4
+ import * as os from 'os';
5
+ import * as path from 'path';
6
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
7
+
8
+ // Block registration used by templates that predate `blocks.config.ts`.
9
+
10
+ const APP_MODULE_PATH = 'apps/api-harmonization/src/app.module.ts';
11
+ const PAGE_MODEL_PATH = 'apps/api-harmonization/src/modules/page/page.model.ts';
12
+
13
+ const APP_MODULE = `import * as Faq from '@o2s/blocks.faq/api-harmonization';
14
+ import * as TicketList from '@o2s/blocks.ticket-list/api-harmonization';
15
+
16
+ @Module({
17
+ imports: [
18
+ Faq.Module.register(AppConfig),
19
+ TicketList.Module.register(AppConfig),
20
+ ],
21
+ })
22
+ export class AppModule {}
23
+ `;
24
+
25
+ const PAGE_MODEL = `import * as Faq from '@o2s/blocks.faq/api-harmonization';
26
+ import * as TicketList from '@o2s/blocks.ticket-list/api-harmonization';
27
+
28
+ export type Blocks =
29
+ | Faq.Model.FaqBlock['__typename']
30
+ | TicketList.Model.TicketListBlock['__typename'];
31
+ `;
32
+
33
+ describe('legacy block registration transforms', () => {
34
+ let projectDir: string;
35
+
36
+ beforeEach(async () => {
37
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'create-o2s-app-legacy-'));
38
+ });
39
+
40
+ afterEach(async () => {
41
+ await fs.remove(projectDir);
42
+ });
43
+
44
+ it('transformAppModule removes the import and module registration of unselected blocks', async () => {
45
+ await fs.outputFile(path.join(projectDir, APP_MODULE_PATH), APP_MODULE, 'utf-8');
46
+
47
+ await transformAppModule(projectDir, ['faq']);
48
+
49
+ const result = await fs.readFile(path.join(projectDir, APP_MODULE_PATH), 'utf-8');
50
+ expect(result).not.toContain('TicketList');
51
+ expect(result).toContain('Faq.Module.register(AppConfig),');
52
+ });
53
+
54
+ it('transformPageModel removes the import and union member of unselected blocks', async () => {
55
+ await fs.outputFile(path.join(projectDir, PAGE_MODEL_PATH), PAGE_MODEL, 'utf-8');
56
+
57
+ await transformPageModel(projectDir, ['ticket-list']);
58
+
59
+ const result = await fs.readFile(path.join(projectDir, PAGE_MODEL_PATH), 'utf-8');
60
+ expect(result).not.toContain('Faq');
61
+ expect(result).toContain("| TicketList.Model.TicketListBlock['__typename'];");
62
+ });
63
+
64
+ it('both transforms skip files that do not exist', async () => {
65
+ await expect(transformAppModule(projectDir, ['faq'])).resolves.toBeUndefined();
66
+ await expect(transformPageModel(projectDir, ['faq'])).resolves.toBeUndefined();
67
+ });
68
+ });
@@ -1,3 +1,4 @@
1
+ import { getAliasesToRemove } from './get-aliases-to-remove';
1
2
  import * as fs from 'fs-extra';
2
3
  import * as path from 'path';
3
4
 
@@ -9,6 +10,8 @@ const BLOCK_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api
9
10
  // Regex matches: | Alias.Model.SomeTypenameBlock['__typename']
10
11
  const UNION_TYPE_REGEX = /^\s+\| (\w+)\.Model\.\w+\['__typename'\]/;
11
12
 
13
+ // TODO: remove this transform once `create-o2s-app/base` registers blocks in
14
+ // `apps/api-harmonization/src/blocks.config.ts` (handled by `transform-blocks-config.ts`).
12
15
  export const transformPageModel = async (projectDir: string, selectedBlockNames: string[]): Promise<void> => {
13
16
  const filePath = path.join(projectDir, FILE_PATH);
14
17
 
@@ -17,22 +20,7 @@ export const transformPageModel = async (projectDir: string, selectedBlockNames:
17
20
  const content = await fs.readFile(filePath, 'utf-8');
18
21
  const lines = content.split('\n');
19
22
 
20
- // Discover alias → blockName map from the actual file
21
- const aliasToBlock = new Map<string, string>();
22
- for (const line of lines) {
23
- const match = line.match(BLOCK_IMPORT_REGEX);
24
- if (match && match[1] && match[2]) {
25
- aliasToBlock.set(match[1], match[2]); // alias → blockName
26
- }
27
- }
28
-
29
- // Build set of aliases for blocks the user did NOT select
30
- const aliasesToRemove = new Set<string>();
31
- for (const [alias, blockName] of aliasToBlock.entries()) {
32
- if (!selectedBlockNames.includes(blockName)) {
33
- aliasesToRemove.add(alias);
34
- }
35
- }
23
+ const aliasesToRemove = getAliasesToRemove(lines, BLOCK_IMPORT_REGEX, selectedBlockNames);
36
24
 
37
25
  if (aliasesToRemove.size === 0) return;
38
26
 
@@ -0,0 +1,153 @@
1
+ import { transformBlocksConfig } from './transform-blocks-config';
2
+ import { transformRenderBlocks } from './transform-render-blocks';
3
+ import * as fs from 'fs-extra';
4
+ import * as os from 'os';
5
+ import * as path from 'path';
6
+ import * as ts from 'typescript';
7
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
8
+
9
+ /**
10
+ * Runs the transforms on the real files from this repository, so a change in their format
11
+ * (e.g. a new type annotation) fails here instead of breaking scaffolded projects.
12
+ */
13
+
14
+ const REPO_ROOT = path.resolve(__dirname, '../../../../..');
15
+
16
+ const BLOCKS_CONFIG_PATH = 'apps/api-harmonization/src/blocks.config.ts';
17
+ const RENDER_BLOCKS_PATH = 'apps/frontend/src/blocks/renderBlocks.tsx';
18
+
19
+ const API_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/api-harmonization';$/;
20
+ const FRONTEND_IMPORT_REGEX = /^import \* as (\w+) from '@o2s\/blocks\.([^/]+)\/frontend';$/;
21
+ const NAMED_IMPORT_REGEX = /^import \{([^}]+)\} from '[^']+';$/;
22
+ const IDENTIFIER_REGEX = /\b[A-Za-z_$][\w$]*\b/g;
23
+
24
+ const discoverBlocks = (content: string, importRegex: RegExp): Map<string, string> => {
25
+ const blocks = new Map<string, string>(); // blockName → alias
26
+ for (const line of content.split('\n')) {
27
+ const match = line.match(importRegex);
28
+ if (match && match[1] && match[2]) blocks.set(match[2], match[1]);
29
+ }
30
+ return blocks;
31
+ };
32
+
33
+ const identifiers = (lines: string[]) => new Set(lines.flatMap((line) => line.match(IDENTIFIER_REGEX) ?? []));
34
+
35
+ const namedImports = (lines: string[]) =>
36
+ lines.flatMap((line) => {
37
+ const match = line.match(NAMED_IMPORT_REGEX);
38
+ return match && match[1]
39
+ ? match[1].split(',').map(
40
+ (specifier) =>
41
+ specifier
42
+ .split(/\s+as\s+/)
43
+ .pop()
44
+ ?.trim() ?? '',
45
+ )
46
+ : [];
47
+ });
48
+
49
+ const syntaxErrors = (content: string, fileName: string) =>
50
+ (
51
+ ts.transpileModule(content, {
52
+ fileName,
53
+ reportDiagnostics: true,
54
+ compilerOptions: { jsx: ts.JsxEmit.Preserve, target: ts.ScriptTarget.ESNext },
55
+ }).diagnostics ?? []
56
+ ).map((diagnostic) => ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'));
57
+
58
+ /** Block selections to check: none, all, each block alone, all but each block, and alternating halves. */
59
+ const selectionsFor = (blockNames: string[]): [string, string[]][] => [
60
+ ['no blocks', []],
61
+ ['all blocks', blockNames],
62
+ ...blockNames.map((name): [string, string[]] => [`only ${name}`, [name]]),
63
+ ...blockNames.map((name): [string, string[]] => [`all but ${name}`, blockNames.filter((other) => other !== name)]),
64
+ ['even blocks', blockNames.filter((_, index) => index % 2 === 0)],
65
+ ['odd blocks', blockNames.filter((_, index) => index % 2 === 1)],
66
+ ];
67
+
68
+ describe('transforms on the real repository files', () => {
69
+ let projectDir: string;
70
+
71
+ beforeEach(async () => {
72
+ projectDir = await fs.mkdtemp(path.join(os.tmpdir(), 'create-o2s-app-real-files-'));
73
+ });
74
+
75
+ afterEach(async () => {
76
+ await fs.remove(projectDir);
77
+ });
78
+
79
+ describe(BLOCKS_CONFIG_PATH, async () => {
80
+ const original = await fs.readFile(path.join(REPO_ROOT, BLOCKS_CONFIG_PATH), 'utf-8');
81
+ const blocks = discoverBlocks(original, API_IMPORT_REGEX);
82
+
83
+ it('discovers the blocks registered in the file', () => {
84
+ expect(blocks.size).toBeGreaterThan(0);
85
+ });
86
+
87
+ it.each(selectionsFor([...blocks.keys()]))('%s', async (_, selected) => {
88
+ await fs.outputFile(path.join(projectDir, BLOCKS_CONFIG_PATH), original, 'utf-8');
89
+
90
+ await transformBlocksConfig(projectDir, selected);
91
+
92
+ const result = await fs.readFile(path.join(projectDir, BLOCKS_CONFIG_PATH), 'utf-8');
93
+ const lines = result.split('\n');
94
+ const used = identifiers(lines);
95
+
96
+ for (const [blockName, alias] of blocks) {
97
+ if (selected.includes(blockName)) {
98
+ expect(result).toContain(`import * as ${alias} from '@o2s/blocks.${blockName}/api-harmonization';`);
99
+ expect(lines).toContain(` ${alias},`);
100
+ expect(result).toMatch(new RegExp(`^\\s+\\| ${alias}\\.Model\\.`, 'm'));
101
+ } else {
102
+ expect(result).not.toContain(`'@o2s/blocks.${blockName}/`);
103
+ expect(used.has(alias)).toBe(false);
104
+ }
105
+ }
106
+
107
+ expect(syntaxErrors(result, 'blocks.config.ts')).toEqual([]);
108
+ });
109
+ });
110
+
111
+ describe(RENDER_BLOCKS_PATH, async () => {
112
+ const original = await fs.readFile(path.join(REPO_ROOT, RENDER_BLOCKS_PATH), 'utf-8');
113
+ const blocks = discoverBlocks(original, FRONTEND_IMPORT_REGEX);
114
+ const originalLines = original.split('\n');
115
+ const originallyUnused = new Set(
116
+ namedImports(originalLines).filter(
117
+ (name) => !identifiers(originalLines.filter((line) => !NAMED_IMPORT_REGEX.test(line))).has(name),
118
+ ),
119
+ );
120
+
121
+ it('discovers the blocks registered in the file', () => {
122
+ expect(blocks.size).toBeGreaterThan(0);
123
+ });
124
+
125
+ it.each(selectionsFor([...blocks.keys()]))('%s', async (_, selected) => {
126
+ await fs.outputFile(path.join(projectDir, RENDER_BLOCKS_PATH), original, 'utf-8');
127
+
128
+ await transformRenderBlocks(projectDir, selected);
129
+
130
+ const result = await fs.readFile(path.join(projectDir, RENDER_BLOCKS_PATH), 'utf-8');
131
+ const lines = result.split('\n');
132
+ const usedOutsideImports = identifiers(lines.filter((line) => !NAMED_IMPORT_REGEX.test(line)));
133
+
134
+ for (const [blockName, alias] of blocks) {
135
+ if (selected.includes(blockName)) {
136
+ expect(result).toContain(`import * as ${alias} from '@o2s/blocks.${blockName}/frontend';`);
137
+ expect(result).toContain(`<${alias}.Renderer`);
138
+ } else {
139
+ expect(result).not.toContain(`'@o2s/blocks.${blockName}/`);
140
+ expect(usedOutsideImports.has(alias)).toBe(false);
141
+ }
142
+ }
143
+
144
+ // No named import is left unused by the transform (e.g. onSignOut without user-account).
145
+ for (const name of namedImports(lines)) {
146
+ if (!originallyUnused.has(name)) expect(usedOutsideImports.has(name)).toBe(true);
147
+ }
148
+
149
+ expect(result).not.toMatch(/\n\n\n/);
150
+ expect(syntaxErrors(result, 'renderBlocks.tsx')).toEqual([]);
151
+ });
152
+ });
153
+ });