fimo 0.8.0 → 0.9.0-experimental.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/content-templates/hooks-template.eta +4 -2
- package/assets/content-templates/types-template.eta +66 -1
- package/assets/skills/fimo/SKILL.md +1 -1
- package/assets/skills/fimo/references/content.md +86 -15
- package/assets/skills/fimo-cli/SKILL.md +6 -2
- package/assets/skills/fimo-cli/references/content.md +61 -2
- package/assets/skills/fimo-cli/references/integrations/firecrawl.md +20 -4
- package/assets/skills/fimo-cli/references/integrations.md +5 -1
- package/assets/skills/fimo-cli/references/webhooks.md +162 -0
- package/assets/skills/fimo-migration/SKILL.md +22 -2
- package/assets/skills/fimo-migration/references/content.md +24 -0
- package/assets/skills/fimo-migration/references/manifest.md +35 -0
- package/assets/skills/fimo-migration/references/qa.md +24 -2
- package/assets/skills/fimo-migration/references/workflow.md +12 -1
- package/assets/skills/fimo-migration/references/wrap.md +617 -0
- package/assets/skills/fimo-studio/SKILL.md +5 -3
- package/assets/skills/fimo-studio/references/cms.md +9 -1
- package/assets/skills/fimo-studio/references/visual-editing.md +5 -3
- package/assets/skills/fimo-studio/references/webhooks.md +42 -0
- package/dist/build/vite/plugins/translations.d.ts +2 -8
- package/dist/build/vite/plugins/translations.js +3 -121
- package/dist/cli/bundle.json +1 -1
- package/dist/cli/index.js +1051 -144
- package/dist/runtime/app/FimoProviders.d.ts +1 -11
- package/dist/runtime/app/FimoProviders.js +2 -23
- package/dist/runtime/astro/index.d.ts +2 -0
- package/dist/runtime/astro/index.js +3 -0
- package/dist/runtime/astro/server.d.ts +3 -0
- package/dist/runtime/astro/server.js +6 -0
- package/dist/runtime/content/client/internal.js +1 -0
- package/dist/runtime/content/client/types.d.ts +16 -0
- package/dist/runtime/i18n/FimoLocaleContext.js +1 -0
- package/dist/runtime/next/FimoNextProviders.d.ts +24 -0
- package/dist/runtime/next/FimoNextProviders.js +20 -0
- package/dist/runtime/next/FimoNextScripts.d.ts +10 -0
- package/dist/runtime/next/FimoNextScripts.js +19 -0
- package/dist/runtime/next/index.d.ts +14 -0
- package/dist/runtime/next/index.js +14 -0
- package/dist/runtime/next/server.d.ts +2 -0
- package/dist/runtime/next/server.js +4 -0
- package/dist/runtime/nuxt/composables.d.ts +9 -0
- package/dist/runtime/nuxt/composables.js +57 -0
- package/dist/runtime/nuxt/index.d.ts +3 -0
- package/dist/runtime/nuxt/index.js +6 -0
- package/dist/runtime/nuxt/server.d.ts +3 -0
- package/dist/runtime/nuxt/server.js +6 -0
- package/dist/runtime/primitives/labels-hook.d.ts +33 -0
- package/dist/runtime/primitives/labels-hook.js +41 -0
- package/dist/runtime/primitives/labels-store.d.ts +12 -0
- package/dist/runtime/primitives/labels-store.js +60 -0
- package/dist/runtime/primitives/lib/useFimoLiveValue.d.ts +5 -3
- package/dist/runtime/primitives/lib/useFimoLiveValue.js +11 -4
- package/dist/runtime/primitives/translations.d.ts +1 -27
- package/dist/runtime/primitives/translations.js +7 -85
- package/dist/runtime/react/FimoSpaProviders.d.ts +36 -0
- package/dist/runtime/react/FimoSpaProviders.js +63 -0
- package/dist/runtime/react/index.d.ts +33 -0
- package/dist/runtime/react/index.js +39 -0
- package/dist/runtime/remix/FimoRemixProviders.d.ts +16 -0
- package/dist/runtime/remix/FimoRemixProviders.js +12 -0
- package/dist/runtime/remix/FimoRemixScripts.d.ts +10 -0
- package/dist/runtime/remix/FimoRemixScripts.js +19 -0
- package/dist/runtime/remix/index.d.ts +12 -0
- package/dist/runtime/remix/index.js +11 -0
- package/dist/runtime/remix/server.d.ts +2 -0
- package/dist/runtime/remix/server.js +2 -0
- package/dist/runtime/shared/display-routes.d.ts +14 -0
- package/dist/runtime/shared/display-routes.js +25 -0
- package/dist/runtime/shared/fimo-config.server.js +1 -0
- package/dist/runtime/shared/fimo-config.types.d.ts +2 -0
- package/dist/runtime/shared/i18n-messages.d.ts +29 -0
- package/dist/runtime/shared/i18n-messages.js +79 -0
- package/dist/runtime/shared/labels-fetch.pure.d.ts +17 -0
- package/dist/runtime/shared/labels-fetch.pure.js +71 -0
- package/dist/runtime/shared/labels-fetch.server.d.ts +7 -0
- package/dist/runtime/shared/labels-fetch.server.js +97 -0
- package/dist/runtime/shared/labels-t.pure.d.ts +2 -0
- package/dist/runtime/shared/labels-t.pure.js +10 -0
- package/dist/runtime/strapi/client.d.ts +30 -0
- package/dist/runtime/strapi/client.js +89 -0
- package/dist/runtime/strapi/index.d.ts +5 -0
- package/dist/runtime/strapi/index.js +6 -0
- package/dist/runtime/strapi/reshape.d.ts +46 -0
- package/dist/runtime/strapi/reshape.js +114 -0
- package/dist/runtime/svelte/index.d.ts +3 -0
- package/dist/runtime/svelte/index.js +7 -0
- package/dist/runtime/svelte/server.d.ts +3 -0
- package/dist/runtime/svelte/server.js +6 -0
- package/dist/runtime/vue/index.d.ts +3 -0
- package/dist/runtime/vue/index.js +5 -0
- package/dist/runtime/vue/server.d.ts +3 -0
- package/dist/runtime/vue/server.js +6 -0
- package/dist/runtime/wrapped/FimoFileLink.d.ts +17 -0
- package/dist/runtime/wrapped/FimoFileLink.js +19 -0
- package/dist/runtime/wrapped/FimoMediaImage.d.ts +14 -0
- package/dist/runtime/wrapped/FimoMediaImage.js +20 -0
- package/dist/runtime/wrapped/FimoMediaVideo.d.ts +14 -0
- package/dist/runtime/wrapped/FimoMediaVideo.js +20 -0
- package/dist/runtime/wrapped/FimoRichTextBlock.d.ts +23 -0
- package/dist/runtime/wrapped/FimoRichTextBlock.js +22 -0
- package/dist/runtime/wrapped/FimoText.d.ts +22 -0
- package/dist/runtime/wrapped/FimoText.js +20 -0
- package/dist/runtime/wrapped/WrappedContentContext.d.ts +28 -0
- package/dist/runtime/wrapped/WrappedContentContext.js +30 -0
- package/dist/runtime/wrapped/WrappedProviders.d.ts +33 -0
- package/dist/runtime/wrapped/WrappedProviders.js +101 -0
- package/dist/runtime/wrapped/dom.d.ts +4 -0
- package/dist/runtime/wrapped/dom.js +23 -0
- package/dist/runtime/wrapped/server.d.ts +77 -0
- package/dist/runtime/wrapped/server.js +237 -0
- package/dist/scripts/apply-wrap-templates.d.ts +61 -0
- package/dist/scripts/apply-wrap-templates.js +132 -0
- package/dist/scripts/apply-wrap.d.ts +46 -0
- package/dist/scripts/apply-wrap.js +278 -0
- package/dist/scripts/cms/discover.d.ts +2 -0
- package/dist/scripts/cms/discover.js +17 -0
- package/dist/scripts/cms/example-content.d.ts +33 -0
- package/dist/scripts/cms/example-content.js +162 -0
- package/dist/scripts/cms/strapi/detect.d.ts +2 -0
- package/dist/scripts/cms/strapi/detect.js +186 -0
- package/dist/scripts/cms/strapi/index.d.ts +3 -0
- package/dist/scripts/cms/strapi/index.js +25 -0
- package/dist/scripts/cms/strapi/list-source.d.ts +17 -0
- package/dist/scripts/cms/strapi/list-source.js +90 -0
- package/dist/scripts/cms/strapi/schema-map.d.ts +9 -0
- package/dist/scripts/cms/strapi/schema-map.js +277 -0
- package/dist/scripts/cms/strapi/shapes.d.ts +23 -0
- package/dist/scripts/cms/strapi/shapes.js +38 -0
- package/dist/scripts/cms/strapi/touchpoints.d.ts +31 -0
- package/dist/scripts/cms/strapi/touchpoints.js +145 -0
- package/dist/scripts/cms/strapi/wire-client.d.ts +15 -0
- package/dist/scripts/cms/strapi/wire-client.js +107 -0
- package/dist/scripts/cms/strapi/wiring.d.ts +17 -0
- package/dist/scripts/cms/strapi/wiring.js +46 -0
- package/dist/scripts/cms/types.d.ts +145 -0
- package/dist/scripts/cms/types.js +11 -0
- package/dist/scripts/detect-framework.d.ts +39 -0
- package/dist/scripts/detect-framework.js +133 -0
- package/dist/scripts/draft-rows.d.ts +19 -0
- package/dist/scripts/draft-rows.js +135 -0
- package/dist/scripts/draft-schemas.d.ts +27 -0
- package/dist/scripts/draft-schemas.js +188 -0
- package/dist/scripts/extract-translations.js +16 -11
- package/dist/scripts/frameworks/astro/routes.d.ts +3 -0
- package/dist/scripts/frameworks/astro/routes.js +55 -0
- package/dist/scripts/frameworks/astro/template-style.d.ts +7 -0
- package/dist/scripts/frameworks/astro/template-style.js +19 -0
- package/dist/scripts/frameworks/discover.d.ts +70 -0
- package/dist/scripts/frameworks/discover.js +178 -0
- package/dist/scripts/frameworks/next/rewire.d.ts +30 -0
- package/dist/scripts/frameworks/next/rewire.js +258 -0
- package/dist/scripts/frameworks/next/routes.d.ts +17 -0
- package/dist/scripts/frameworks/next/routes.js +134 -0
- package/dist/scripts/frameworks/next/wiring.d.ts +33 -0
- package/dist/scripts/frameworks/next/wiring.js +186 -0
- package/dist/scripts/frameworks/nuxt/routes.d.ts +3 -0
- package/dist/scripts/frameworks/nuxt/routes.js +54 -0
- package/dist/scripts/frameworks/nuxt/template-style.d.ts +9 -0
- package/dist/scripts/frameworks/nuxt/template-style.js +27 -0
- package/dist/scripts/frameworks/remix/routes.d.ts +3 -0
- package/dist/scripts/frameworks/remix/routes.js +50 -0
- package/dist/scripts/frameworks/support.d.ts +75 -0
- package/dist/scripts/frameworks/support.js +165 -0
- package/dist/scripts/frameworks/sveltekit/routes.d.ts +3 -0
- package/dist/scripts/frameworks/sveltekit/routes.js +50 -0
- package/dist/scripts/frameworks/sveltekit/template-style.d.ts +9 -0
- package/dist/scripts/frameworks/sveltekit/template-style.js +54 -0
- package/dist/scripts/frameworks/vite/routes.d.ts +15 -0
- package/dist/scripts/frameworks/vite/routes.js +93 -0
- package/dist/scripts/frameworks/vite/wiring.d.ts +10 -0
- package/dist/scripts/frameworks/vite/wiring.js +99 -0
- package/dist/scripts/i18n-namespace.d.ts +27 -0
- package/dist/scripts/i18n-namespace.js +155 -0
- package/dist/scripts/lib/validation-report.d.ts +1 -0
- package/dist/scripts/lib/validation-report.js +3 -0
- package/dist/scripts/render-parity/capture.d.ts +56 -0
- package/dist/scripts/render-parity/capture.js +366 -0
- package/dist/scripts/render-parity/compare.d.ts +59 -0
- package/dist/scripts/render-parity/compare.js +0 -0
- package/dist/scripts/render-parity/normalize-html.d.ts +13 -0
- package/dist/scripts/render-parity/normalize-html.js +223 -0
- package/dist/scripts/render-parity/types.d.ts +41 -0
- package/dist/scripts/render-parity/types.js +1 -0
- package/dist/scripts/scan-wrappable.d.ts +196 -0
- package/dist/scripts/scan-wrappable.js +1232 -0
- package/dist/scripts/validate-route-metadata.js +11 -0
- package/dist/scripts/validate-schemas.js +42 -1
- package/package.json +84 -4
- package/release.json +2 -2
- package/templates/react-router/package.json +1 -1
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { decodeJsxEntities, KeyAllocator, slugify } from './apply-wrap.js';
|
|
4
|
+
import { scanWrappable } from './scan-wrappable.js';
|
|
5
|
+
/**
|
|
6
|
+
* Shared injection helper for SFC-style templates: first instance script,
|
|
7
|
+
* never a `<script module>` block (module scope cannot read page data), or a
|
|
8
|
+
* fresh script when the file has none.
|
|
9
|
+
*/
|
|
10
|
+
export function injectIntoInstanceScript(code, head, scriptTag) {
|
|
11
|
+
const instance = code.match(/<script(?![^>]*\bmodule\b)[^>]*>\r?\n?/);
|
|
12
|
+
if (instance && instance.index !== undefined) {
|
|
13
|
+
const at = instance.index + instance[0].length;
|
|
14
|
+
return `${code.slice(0, at)}\t${head}\n${code.slice(at)}`;
|
|
15
|
+
}
|
|
16
|
+
return `${scriptTag}\n\t${head}\n</script>\n\n${code}`;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A file that already binds `t` (an i18n library, a custom helper) is agent
|
|
20
|
+
* work: the dogfood proved rewiring foreign t() calls breaks rendering.
|
|
21
|
+
*/
|
|
22
|
+
function bindsForeignT(code) {
|
|
23
|
+
return (/\buseI18n\s*\(/.test(code) ||
|
|
24
|
+
/(?:const|let|var)\s+t\s*=/.test(code) ||
|
|
25
|
+
/import\s*\{[^}]*\bt\b[^}]*\}\s*from/.test(code));
|
|
26
|
+
}
|
|
27
|
+
function previewPattern(preview) {
|
|
28
|
+
const core = preview
|
|
29
|
+
.replace(/…$/, '')
|
|
30
|
+
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
31
|
+
.replace(/\\? /g, '\\s+');
|
|
32
|
+
return new RegExp(`>(\\s*)(${core}[^<{]*?)(\\s*)<`);
|
|
33
|
+
}
|
|
34
|
+
export function applyTemplateWrapToFile(code, style, items, allocator) {
|
|
35
|
+
const applied = [];
|
|
36
|
+
const skipped = [];
|
|
37
|
+
const labels = {};
|
|
38
|
+
const hasHead = style.headMarker.test(code);
|
|
39
|
+
if (!hasHead && bindsForeignT(code)) {
|
|
40
|
+
return {
|
|
41
|
+
code,
|
|
42
|
+
applied,
|
|
43
|
+
skipped: items.map((item) => ({ item, reason: 'file binds its own t() — agent work' })),
|
|
44
|
+
labels,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
if (!hasHead && style.injectHead(code, style.head) === null) {
|
|
48
|
+
return {
|
|
49
|
+
code,
|
|
50
|
+
applied,
|
|
51
|
+
skipped: items.map((item) => ({ item, reason: 'no safe wiring point in this file — agent work' })),
|
|
52
|
+
labels,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const file = items[0]?.file ?? '';
|
|
56
|
+
const scope = style.fileScope?.(file) ?? slugify(basename(file).replace(/\.[a-z0-9]+$/i, '')) ?? 'shared';
|
|
57
|
+
let next = code;
|
|
58
|
+
for (const item of items) {
|
|
59
|
+
if (item.kind !== 'text') {
|
|
60
|
+
skipped.push({ item, reason: `${item.kind} stays agent work` });
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
const match = next.match(previewPattern(item.preview));
|
|
64
|
+
if (!match || match.index === undefined) {
|
|
65
|
+
skipped.push({ item, reason: 'text node not matched in source — agent work' });
|
|
66
|
+
continue;
|
|
67
|
+
}
|
|
68
|
+
const collapsed = match[2].replace(/\s+/g, ' ').trim();
|
|
69
|
+
const id = allocator.allocate(scope || 'shared', slugify(collapsed));
|
|
70
|
+
const escaped = collapsed.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
|
|
71
|
+
const replacement = `>${match[1]}${style.open}"${id}", "${escaped}"${style.close}${match[3]}<`;
|
|
72
|
+
next = next.slice(0, match.index) + replacement + next.slice(match.index + match[0].length);
|
|
73
|
+
labels[id] = decodeJsxEntities(collapsed);
|
|
74
|
+
applied.push({ kind: 'text', file: item.file, line: item.line, id, preview: item.preview });
|
|
75
|
+
}
|
|
76
|
+
if (applied.length > 0 && !style.headMarker.test(next)) {
|
|
77
|
+
next = style.injectHead(next, style.head) ?? next;
|
|
78
|
+
}
|
|
79
|
+
return { code: next, applied, skipped, labels };
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Apply the template wraps across a project — same contract as applyWrap:
|
|
83
|
+
* scans, mutates source files, returns the generated labels for staging and
|
|
84
|
+
* seeding. The style's ensureWiring hook then writes any one-time project
|
|
85
|
+
* wiring (e.g. a root layout labels loader) when files were wrapped.
|
|
86
|
+
*/
|
|
87
|
+
export function applyTemplateWrap(rootDir, opts) {
|
|
88
|
+
const { style } = opts;
|
|
89
|
+
const scan = scanWrappable(rootDir, { excludePrefixes: opts.excludePrefixes });
|
|
90
|
+
const existingLabels = (() => {
|
|
91
|
+
try {
|
|
92
|
+
return JSON.parse(readFileSync(join(rootDir, '.fimo', 'migration', 'labels.json'), 'utf8'));
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return {};
|
|
96
|
+
}
|
|
97
|
+
})();
|
|
98
|
+
const allocator = new KeyAllocator([...Object.keys(existingLabels), ...scan.wrappedIds.labels]);
|
|
99
|
+
const result = { applied: [], skipped: [], labels: {}, filesChanged: [] };
|
|
100
|
+
const byFile = new Map();
|
|
101
|
+
for (const item of scan.items) {
|
|
102
|
+
if (!item.file.endsWith(style.ext)) {
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const list = byFile.get(item.file) ?? [];
|
|
106
|
+
list.push(item);
|
|
107
|
+
byFile.set(item.file, list);
|
|
108
|
+
}
|
|
109
|
+
for (const [file, items] of byFile) {
|
|
110
|
+
const filePath = join(rootDir, file);
|
|
111
|
+
let code;
|
|
112
|
+
try {
|
|
113
|
+
code = readFileSync(filePath, 'utf8');
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
result.skipped.push(...items.map((item) => ({ item, reason: 'unreadable file' })));
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const fileResult = applyTemplateWrapToFile(code, style, items, allocator);
|
|
120
|
+
result.applied.push(...fileResult.applied);
|
|
121
|
+
result.skipped.push(...fileResult.skipped);
|
|
122
|
+
Object.assign(result.labels, fileResult.labels);
|
|
123
|
+
if (fileResult.applied.length > 0) {
|
|
124
|
+
writeFileSync(filePath, fileResult.code);
|
|
125
|
+
result.filesChanged.push(file);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (result.filesChanged.length > 0 && style.ensureWiring) {
|
|
129
|
+
result.filesChanged.push(...style.ensureWiring(rootDir));
|
|
130
|
+
}
|
|
131
|
+
return result;
|
|
132
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { type WrappableItem } from './scan-wrappable.js';
|
|
2
|
+
export interface AppliedTransform {
|
|
3
|
+
kind: 'text' | 'image' | 'file-link';
|
|
4
|
+
file: string;
|
|
5
|
+
line: number;
|
|
6
|
+
id: string;
|
|
7
|
+
preview: string;
|
|
8
|
+
}
|
|
9
|
+
export interface ApplyWrapResult {
|
|
10
|
+
applied: AppliedTransform[];
|
|
11
|
+
skipped: Array<{
|
|
12
|
+
item: WrappableItem;
|
|
13
|
+
reason: string;
|
|
14
|
+
}>;
|
|
15
|
+
labels: Record<string, string>;
|
|
16
|
+
filesChanged: string[];
|
|
17
|
+
}
|
|
18
|
+
export declare function decodeJsxEntities(text: string): string;
|
|
19
|
+
/** Deterministic scope from the file path: app/about/page.tsx -> about. */
|
|
20
|
+
export declare function keyScope(file: string): string;
|
|
21
|
+
export declare function slugify(text: string): string;
|
|
22
|
+
export declare class KeyAllocator {
|
|
23
|
+
private readonly used;
|
|
24
|
+
constructor(existing: Iterable<string>);
|
|
25
|
+
allocate(scope: string, slug: string): string;
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Merge the fimo/next import with an existing one, or insert a new one AFTER
|
|
29
|
+
* the last import statement — positioned via the AST, never line matching
|
|
30
|
+
* (a multiline `import {\n …` opening line is not the end of the imports,
|
|
31
|
+
* as a real portfolio migration proved).
|
|
32
|
+
*/
|
|
33
|
+
export declare function ensureFimoImport(code: string, specifiers: string[], importModule?: string): string;
|
|
34
|
+
export declare function applyWrapToFile(code: string, items: WrappableItem[], allocator: KeyAllocator, importModule?: string): {
|
|
35
|
+
code: string;
|
|
36
|
+
applied: AppliedTransform[];
|
|
37
|
+
skipped: Array<{
|
|
38
|
+
item: WrappableItem;
|
|
39
|
+
reason: string;
|
|
40
|
+
}>;
|
|
41
|
+
labels: Record<string, string>;
|
|
42
|
+
};
|
|
43
|
+
export declare function applyWrap(rootDir: string, opts?: {
|
|
44
|
+
excludePrefixes?: string[];
|
|
45
|
+
importModule?: string;
|
|
46
|
+
}): ApplyWrapResult;
|
|
@@ -0,0 +1,278 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, join } from 'node:path';
|
|
3
|
+
import { parseSync } from 'oxc-parser';
|
|
4
|
+
import { scanWrappable } from './scan-wrappable.js';
|
|
5
|
+
/**
|
|
6
|
+
* The --apply codemod: performs the PROVABLY-SAFE wrap transforms
|
|
7
|
+
* deterministically, leaving every judgment call to the agent.
|
|
8
|
+
*
|
|
9
|
+
* In scope: plain JSX text -> FimoText, <img src="literal"> -> FimoMediaImage,
|
|
10
|
+
* <a href="/file.pdf"> -> FimoFileLink.
|
|
11
|
+
* Out of scope (agent work): attributes (useLabels crosses the RSC boundary),
|
|
12
|
+
* formatted text (marks -> FimoRichTextBlock), next/image <Image>
|
|
13
|
+
* (framework-specific props), collections, layout wiring.
|
|
14
|
+
*
|
|
15
|
+
* Correctness is enforced by the gates, not assumed: the render-parity
|
|
16
|
+
* baseline is captured BEFORE applying, and `fimo migrate wrap --check`
|
|
17
|
+
* verifies the result like any other actor's work.
|
|
18
|
+
*/
|
|
19
|
+
/** Elements whose children cannot contain a <span> wrapper. */
|
|
20
|
+
const NO_ELEMENT_CHILDREN = new Set(['option', 'title', 'textarea', 'script', 'style', 'select']);
|
|
21
|
+
function collapse(text) {
|
|
22
|
+
return text.replace(/\s+/g, ' ').trim();
|
|
23
|
+
}
|
|
24
|
+
// JSX text carries HTML entities (', &, …). The FALLBACK keeps the
|
|
25
|
+
// original source form, but the label VALUE is rendered literally by
|
|
26
|
+
// FimoText — seeding the raw entity re-escapes it on screen (the remix
|
|
27
|
+
// dogfood shipped "What's next?"). Decode when generating values.
|
|
28
|
+
const JSX_ENTITIES = {
|
|
29
|
+
'&': '&',
|
|
30
|
+
'<': '<',
|
|
31
|
+
'>': '>',
|
|
32
|
+
'"': '"',
|
|
33
|
+
''': "'",
|
|
34
|
+
' ': ' ',
|
|
35
|
+
'©': '©',
|
|
36
|
+
};
|
|
37
|
+
export function decodeJsxEntities(text) {
|
|
38
|
+
return text
|
|
39
|
+
.replace(/&(amp|lt|gt|quot|apos|nbsp|copy);/g, (entity) => JSX_ENTITIES[entity] ?? entity)
|
|
40
|
+
.replace(/&#(\d+);/g, (_, code) => String.fromCodePoint(Number(code)))
|
|
41
|
+
.replace(/&#x([0-9a-f]+);/gi, (_, code) => String.fromCodePoint(parseInt(code, 16)));
|
|
42
|
+
}
|
|
43
|
+
/** Deterministic scope from the file path: app/about/page.tsx -> about. */
|
|
44
|
+
export function keyScope(file) {
|
|
45
|
+
const normalized = file.replace(/\\/g, '/');
|
|
46
|
+
const appMatch = normalized.match(/(?:^|\/)app\/(.*)\/?page\.[jt]sx?$/);
|
|
47
|
+
if (appMatch) {
|
|
48
|
+
const dir = appMatch[1].replace(/\/$/, '');
|
|
49
|
+
if (!dir) {
|
|
50
|
+
return 'home';
|
|
51
|
+
}
|
|
52
|
+
const segments = dir
|
|
53
|
+
.split('/')
|
|
54
|
+
.filter((segment) => !segment.startsWith('(') && !segment.startsWith('@'))
|
|
55
|
+
.map((segment) => segment.replace(/^\[+|\]+$/g, '').replace(/^\.\.\./, ''));
|
|
56
|
+
return segments.join('.') || 'home';
|
|
57
|
+
}
|
|
58
|
+
if (/(?:^|\/)app\/layout\.[jt]sx?$/.test(normalized)) {
|
|
59
|
+
return 'layout';
|
|
60
|
+
}
|
|
61
|
+
const stem = basename(normalized).replace(/\.[jt]sx?$/, '');
|
|
62
|
+
return slugify(stem) || 'shared';
|
|
63
|
+
}
|
|
64
|
+
export function slugify(text) {
|
|
65
|
+
return collapse(text)
|
|
66
|
+
.toLowerCase()
|
|
67
|
+
.normalize('NFD')
|
|
68
|
+
.replace(/[̀-ͯ]/g, '')
|
|
69
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
70
|
+
.replace(/^-+|-+$/g, '')
|
|
71
|
+
.split('-')
|
|
72
|
+
.slice(0, 4)
|
|
73
|
+
.join('-');
|
|
74
|
+
}
|
|
75
|
+
export class KeyAllocator {
|
|
76
|
+
used = new Set();
|
|
77
|
+
constructor(existing) {
|
|
78
|
+
for (const key of existing) {
|
|
79
|
+
this.used.add(key);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
allocate(scope, slug) {
|
|
83
|
+
const base = `${scope}.${slug || 'item'}`;
|
|
84
|
+
let candidate = base;
|
|
85
|
+
let counter = 2;
|
|
86
|
+
while (this.used.has(candidate)) {
|
|
87
|
+
candidate = `${base}-${counter++}`;
|
|
88
|
+
}
|
|
89
|
+
this.used.add(candidate);
|
|
90
|
+
return candidate;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Merge the fimo/next import with an existing one, or insert a new one AFTER
|
|
95
|
+
* the last import statement — positioned via the AST, never line matching
|
|
96
|
+
* (a multiline `import {\n …` opening line is not the end of the imports,
|
|
97
|
+
* as a real portfolio migration proved).
|
|
98
|
+
*/
|
|
99
|
+
export function ensureFimoImport(code, specifiers, importModule = 'fimo/next') {
|
|
100
|
+
if (specifiers.length === 0) {
|
|
101
|
+
return code;
|
|
102
|
+
}
|
|
103
|
+
const moduleRe = importModule.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
|
104
|
+
const importMatch = code.match(new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*(['\"])${moduleRe}\\2\\s*;?`));
|
|
105
|
+
if (importMatch) {
|
|
106
|
+
const existing = importMatch[1]
|
|
107
|
+
.split(',')
|
|
108
|
+
.map((token) => token.trim())
|
|
109
|
+
.filter(Boolean);
|
|
110
|
+
const merged = [...new Set([...existing, ...specifiers])].sort();
|
|
111
|
+
return code.replace(importMatch[0], `import { ${merged.join(', ')} } from "${importModule}";`);
|
|
112
|
+
}
|
|
113
|
+
const statement = `import { ${[...new Set(specifiers)].sort().join(', ')} } from "${importModule}";`;
|
|
114
|
+
let insertAt = 0;
|
|
115
|
+
try {
|
|
116
|
+
const program = parseSync('module.tsx', code).program;
|
|
117
|
+
for (const node of program.body ?? []) {
|
|
118
|
+
if (node.type === 'ImportDeclaration') {
|
|
119
|
+
insertAt = node.end;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
catch {
|
|
124
|
+
insertAt = 0;
|
|
125
|
+
}
|
|
126
|
+
if (insertAt === 0) {
|
|
127
|
+
return `${statement}\n${code}`;
|
|
128
|
+
}
|
|
129
|
+
return `${code.slice(0, insertAt)}\n${statement}${code.slice(insertAt)}`;
|
|
130
|
+
}
|
|
131
|
+
export function applyWrapToFile(code, items, allocator, importModule = 'fimo/next') {
|
|
132
|
+
const applied = [];
|
|
133
|
+
const skipped = [];
|
|
134
|
+
const labels = {};
|
|
135
|
+
const edits = [];
|
|
136
|
+
const specifiers = new Set();
|
|
137
|
+
for (const item of items) {
|
|
138
|
+
const span = item.span;
|
|
139
|
+
if (!span) {
|
|
140
|
+
skipped.push({ item, reason: 'no span info' });
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
const scope = keyScope(item.file);
|
|
144
|
+
if (item.kind === 'text') {
|
|
145
|
+
if (span.parentTag && NO_ELEMENT_CHILDREN.has(span.parentTag.toLowerCase())) {
|
|
146
|
+
skipped.push({ item, reason: `<${span.parentTag}> cannot contain a wrapper element` });
|
|
147
|
+
continue;
|
|
148
|
+
}
|
|
149
|
+
const raw = code.slice(span.start, span.end);
|
|
150
|
+
const core = raw.trim();
|
|
151
|
+
if (!core) {
|
|
152
|
+
skipped.push({ item, reason: 'whitespace only' });
|
|
153
|
+
continue;
|
|
154
|
+
}
|
|
155
|
+
const lead = raw.slice(0, raw.indexOf(core));
|
|
156
|
+
const trail = raw.slice(raw.indexOf(core) + core.length);
|
|
157
|
+
const id = allocator.allocate(scope, slugify(core));
|
|
158
|
+
edits.push({
|
|
159
|
+
start: span.start,
|
|
160
|
+
end: span.end,
|
|
161
|
+
replacement: `${lead}<FimoText id="${id}">${core}</FimoText>${trail}`,
|
|
162
|
+
});
|
|
163
|
+
specifiers.add('FimoText');
|
|
164
|
+
labels[id] = decodeJsxEntities(collapse(core));
|
|
165
|
+
applied.push({ kind: 'text', file: item.file, line: item.line, id, preview: item.preview });
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
if (item.kind === 'image') {
|
|
169
|
+
if (span.openNameStart === undefined ||
|
|
170
|
+
span.openNameEnd === undefined ||
|
|
171
|
+
code.slice(span.openNameStart, span.openNameEnd) !== 'img') {
|
|
172
|
+
skipped.push({ item, reason: 'next/image and custom components stay agent work' });
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
const id = allocator.allocate(scope, slugify(basename(item.preview).replace(/\.[a-z0-9]+$/i, '')));
|
|
176
|
+
edits.push({
|
|
177
|
+
start: span.openNameStart,
|
|
178
|
+
end: span.openNameEnd,
|
|
179
|
+
replacement: `FimoMediaImage id="${id}"`,
|
|
180
|
+
});
|
|
181
|
+
specifiers.add('FimoMediaImage');
|
|
182
|
+
applied.push({ kind: 'image', file: item.file, line: item.line, id, preview: item.preview });
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
if (item.kind === 'file-link') {
|
|
186
|
+
if (span.openNameStart === undefined ||
|
|
187
|
+
span.openNameEnd === undefined ||
|
|
188
|
+
span.closeNameStart === undefined ||
|
|
189
|
+
span.closeNameEnd === undefined) {
|
|
190
|
+
skipped.push({ item, reason: 'self-closing or unparsable anchor' });
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
const id = allocator.allocate(scope, slugify(basename(item.preview).replace(/\.[a-z0-9]+$/i, '')));
|
|
194
|
+
edits.push({ start: span.openNameStart, end: span.openNameEnd, replacement: `FimoFileLink id="${id}"` });
|
|
195
|
+
edits.push({ start: span.closeNameStart, end: span.closeNameEnd, replacement: 'FimoFileLink' });
|
|
196
|
+
specifiers.add('FimoFileLink');
|
|
197
|
+
applied.push({ kind: 'file-link', file: item.file, line: item.line, id, preview: item.preview });
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
skipped.push({ item, reason: `${item.kind} stays agent work` });
|
|
201
|
+
}
|
|
202
|
+
let next = code;
|
|
203
|
+
for (const edit of edits.sort((a, b) => b.start - a.start)) {
|
|
204
|
+
next = next.slice(0, edit.start) + edit.replacement + next.slice(edit.end);
|
|
205
|
+
}
|
|
206
|
+
next = ensureFimoImport(next, [...specifiers], importModule);
|
|
207
|
+
return { code: next, applied, skipped, labels };
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Apply the safe transforms across the project. Mutates source files and
|
|
211
|
+
* merges generated labels into `.fimo/migration/labels.json` (never
|
|
212
|
+
* overwriting existing keys).
|
|
213
|
+
*/
|
|
214
|
+
/** Recorded coverage exemptions the codemod must NOT wrap — items the user
|
|
215
|
+
* deliberately kept out (dev-only UI, OG-image markup, …). Matched by the
|
|
216
|
+
* same (file, kind, preview) triple the coverage gate uses, so "record the
|
|
217
|
+
* exemption first, then --apply auto-wraps the rest" holds. */
|
|
218
|
+
function readApplyExemptions(rootDir) {
|
|
219
|
+
try {
|
|
220
|
+
const manifest = JSON.parse(readFileSync(join(rootDir, '.fimo', 'migration', 'manifest.json'), 'utf8'));
|
|
221
|
+
const raw = manifest?.wrap?.exemptions;
|
|
222
|
+
return Array.isArray(raw)
|
|
223
|
+
? raw.filter((entry) => typeof entry?.file === 'string' &&
|
|
224
|
+
typeof entry?.kind === 'string' &&
|
|
225
|
+
typeof entry?.preview === 'string')
|
|
226
|
+
: [];
|
|
227
|
+
}
|
|
228
|
+
catch {
|
|
229
|
+
return [];
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
export function applyWrap(rootDir, opts = {}) {
|
|
233
|
+
const scan = scanWrappable(rootDir, { excludePrefixes: opts.excludePrefixes });
|
|
234
|
+
const existingLabels = (() => {
|
|
235
|
+
try {
|
|
236
|
+
return JSON.parse(readFileSync(join(rootDir, '.fimo', 'migration', 'labels.json'), 'utf8'));
|
|
237
|
+
}
|
|
238
|
+
catch {
|
|
239
|
+
return {};
|
|
240
|
+
}
|
|
241
|
+
})();
|
|
242
|
+
// Honor recorded exemptions: the codemod skips them so the coverage gate's
|
|
243
|
+
// exemption and the codemod stay consistent — otherwise --apply would wrap
|
|
244
|
+
// an item the user just exempted and the gate would flag the drift.
|
|
245
|
+
const exemptions = readApplyExemptions(rootDir);
|
|
246
|
+
const isExempt = (item) => exemptions.some((exemption) => exemption.file === item.file && exemption.kind === item.kind && exemption.preview === item.preview);
|
|
247
|
+
const allocator = new KeyAllocator([...Object.keys(existingLabels), ...scan.wrappedIds.labels]);
|
|
248
|
+
const byFile = new Map();
|
|
249
|
+
for (const item of scan.items) {
|
|
250
|
+
if (isExempt(item)) {
|
|
251
|
+
continue;
|
|
252
|
+
}
|
|
253
|
+
const list = byFile.get(item.file) ?? [];
|
|
254
|
+
list.push(item);
|
|
255
|
+
byFile.set(item.file, list);
|
|
256
|
+
}
|
|
257
|
+
const result = { applied: [], skipped: [], labels: {}, filesChanged: [] };
|
|
258
|
+
for (const [file, items] of byFile) {
|
|
259
|
+
const filePath = join(rootDir, file);
|
|
260
|
+
let code;
|
|
261
|
+
try {
|
|
262
|
+
code = readFileSync(filePath, 'utf8');
|
|
263
|
+
}
|
|
264
|
+
catch {
|
|
265
|
+
result.skipped.push(...items.map((item) => ({ item, reason: 'unreadable file' })));
|
|
266
|
+
continue;
|
|
267
|
+
}
|
|
268
|
+
const fileResult = applyWrapToFile(code, items, allocator, opts.importModule ?? 'fimo/next');
|
|
269
|
+
result.applied.push(...fileResult.applied);
|
|
270
|
+
result.skipped.push(...fileResult.skipped);
|
|
271
|
+
Object.assign(result.labels, fileResult.labels);
|
|
272
|
+
if (fileResult.applied.length > 0) {
|
|
273
|
+
writeFileSync(filePath, fileResult.code);
|
|
274
|
+
result.filesChanged.push(file);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
return result;
|
|
278
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { strapiConnector } from './strapi/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* CMS-connector registry. Add a connector factory here to support a new
|
|
4
|
+
* headless CMS; each returns its `CmsConnector` when it recognizes the
|
|
5
|
+
* frontend, or null. First match wins. This is the ONLY CMS-neutral file that
|
|
6
|
+
* enumerates the supported CMSs (the analogue of `frameworks/discover.ts`).
|
|
7
|
+
*/
|
|
8
|
+
const CONNECTORS = [strapiConnector];
|
|
9
|
+
export function detectCms(frontendDir) {
|
|
10
|
+
for (const factory of CONNECTORS) {
|
|
11
|
+
const connector = factory(frontendDir);
|
|
12
|
+
if (connector) {
|
|
13
|
+
return connector;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import type { CmsCollectionSchema } from './types.js';
|
|
2
|
+
/**
|
|
3
|
+
* Generate example content for a CMS schema WITHOUT connecting to the CMS. The
|
|
4
|
+
* shapes match `api.importEntries`: media fields get a self-contained
|
|
5
|
+
* placeholder, references point at the first example of the target type
|
|
6
|
+
* (`<target>-example-1`) so they resolve against the co-seeded data, blocks
|
|
7
|
+
* (components / dynamic zones) get a filled array so page-builder pages render
|
|
8
|
+
* instead of showing empty, and localized types get per-locale string variance
|
|
9
|
+
* so the per-language editability is visible in Fimo. This is CMS-neutral: it
|
|
10
|
+
* consumes the mapped Fimo schema only.
|
|
11
|
+
*/
|
|
12
|
+
export interface ExampleSeed {
|
|
13
|
+
/** Fimo type name. */
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly isSingleton: boolean;
|
|
16
|
+
readonly localized: boolean;
|
|
17
|
+
/** Entry data rows (slug lives inside data for collections). */
|
|
18
|
+
readonly rows: Array<Record<string, unknown>>;
|
|
19
|
+
/** Reference descriptor for `importEntries`. */
|
|
20
|
+
readonly references: Record<string, {
|
|
21
|
+
target?: string;
|
|
22
|
+
targets?: string[];
|
|
23
|
+
by: 'slug';
|
|
24
|
+
many?: boolean;
|
|
25
|
+
}>;
|
|
26
|
+
}
|
|
27
|
+
export interface ExampleOptions {
|
|
28
|
+
/** Rows per collection type (singletons always get exactly one). */
|
|
29
|
+
readonly count?: number;
|
|
30
|
+
/** Locale suffix on string values + the batch locale (for localized types). */
|
|
31
|
+
readonly locale?: string;
|
|
32
|
+
}
|
|
33
|
+
export declare function generateExampleSeed(schema: CmsCollectionSchema, options?: ExampleOptions): ExampleSeed;
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
const DEFAULT_COUNT = 3;
|
|
2
|
+
/** Variants seeded per dynamic-zone (`oneOf`) field — a representative page, not
|
|
3
|
+
* all N components. Real content (the pull) exercises the rest. */
|
|
4
|
+
const EXAMPLE_BLOCK_VARIANTS = 5;
|
|
5
|
+
/** Items seeded for a repeatable fixed-shape block. */
|
|
6
|
+
const EXAMPLE_REPEATABLE_ITEMS = 2;
|
|
7
|
+
/** Recursion cap for nested blocks — the schema is already depth-bounded; this
|
|
8
|
+
* keeps generation finite even for pathological nesting. */
|
|
9
|
+
const MAX_FILL_DEPTH = 3;
|
|
10
|
+
function kebabCase(name) {
|
|
11
|
+
return name
|
|
12
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1-$2')
|
|
13
|
+
.replace(/[^a-zA-Z0-9]+/g, '-')
|
|
14
|
+
.toLowerCase()
|
|
15
|
+
.replace(/^-+|-+$/g, '');
|
|
16
|
+
}
|
|
17
|
+
function humanize(field) {
|
|
18
|
+
return field
|
|
19
|
+
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
|
20
|
+
.replace(/[_-]+/g, ' ')
|
|
21
|
+
.replace(/^\w/, (c) => c.toUpperCase());
|
|
22
|
+
}
|
|
23
|
+
function richTextDoc(text) {
|
|
24
|
+
return {
|
|
25
|
+
type: 'doc',
|
|
26
|
+
content: [{ type: 'paragraph', content: [{ type: 'text', text }] }],
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
/** A self-contained placeholder image (inline SVG data-URI) in the media
|
|
30
|
+
* envelope shape the wrap runtime already understands — no external host, no
|
|
31
|
+
* CSP surprises, so cards/heroes render instead of showing broken images. */
|
|
32
|
+
function placeholderMedia(label) {
|
|
33
|
+
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630"><rect width="100%" height="100%" fill="#e5e7eb"/><text x="50%" y="50%" font-family="sans-serif" font-size="44" fill="#9ca3af" text-anchor="middle" dominant-baseline="middle">${label}</text></svg>`;
|
|
34
|
+
return {
|
|
35
|
+
source: 'local',
|
|
36
|
+
url: `data:image/svg+xml;utf8,${encodeURIComponent(svg)}`,
|
|
37
|
+
alt: `${label} placeholder`,
|
|
38
|
+
width: 1200,
|
|
39
|
+
height: 630,
|
|
40
|
+
mime: 'image/svg+xml',
|
|
41
|
+
name: 'placeholder.svg',
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Deterministic ISO date (no wall clock): 2024-01-01 + (n-1) days. */
|
|
45
|
+
function exampleDate(n) {
|
|
46
|
+
return new Date(Date.UTC(2024, 0, n)).toISOString().slice(0, 10);
|
|
47
|
+
}
|
|
48
|
+
function exampleReferenceSlug(field) {
|
|
49
|
+
const targetName = field.target ?? field.targets?.[0];
|
|
50
|
+
if (!targetName) {
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
const slug = `${kebabCase(targetName)}-example-1`;
|
|
54
|
+
return field.many ? [slug] : slug;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Fill a NON-reference field value from its Fimo def (scalars, blocks, and any
|
|
58
|
+
* baked default such as a block variant's `__component` discriminator).
|
|
59
|
+
* Reference fields return `undefined` here: the top-level pass owns them, and
|
|
60
|
+
* server-side slug resolution does not reach references nested inside blocks.
|
|
61
|
+
*/
|
|
62
|
+
function fillFieldValue(field, def, ctx) {
|
|
63
|
+
const baked = def.default;
|
|
64
|
+
if (baked !== undefined) {
|
|
65
|
+
return baked;
|
|
66
|
+
}
|
|
67
|
+
switch (def.type) {
|
|
68
|
+
case 'string':
|
|
69
|
+
return `${humanize(field)} example ${ctx.index}${ctx.localeSuffix}`;
|
|
70
|
+
case 'richtext':
|
|
71
|
+
return richTextDoc(`Example ${humanize(ctx.schemaName).toLowerCase()} content ${ctx.index}${ctx.localeSuffix}.`);
|
|
72
|
+
case 'number':
|
|
73
|
+
return ctx.index;
|
|
74
|
+
case 'boolean':
|
|
75
|
+
return ctx.index % 2 === 1;
|
|
76
|
+
case 'date':
|
|
77
|
+
return exampleDate(ctx.index);
|
|
78
|
+
case 'json':
|
|
79
|
+
return {};
|
|
80
|
+
case 'media':
|
|
81
|
+
return placeholderMedia(humanize(field));
|
|
82
|
+
case 'blocks':
|
|
83
|
+
return fillBlocks(def, ctx);
|
|
84
|
+
default:
|
|
85
|
+
// reference (nested) — omitted; the frontend accesses relations defensively.
|
|
86
|
+
return undefined;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Fill a blocks value — always an array so page builders can `.map()` it. A
|
|
91
|
+
* dynamic zone (`oneOf`) seeds one item per variant (representative subset,
|
|
92
|
+
* each tagged with its `_type` discriminator); a fixed component (`fields`)
|
|
93
|
+
* seeds one item (single) or a few (repeatable).
|
|
94
|
+
*/
|
|
95
|
+
function fillBlocks(def, ctx) {
|
|
96
|
+
if (ctx.depth >= MAX_FILL_DEPTH) {
|
|
97
|
+
return [];
|
|
98
|
+
}
|
|
99
|
+
const childCtx = { ...ctx, depth: ctx.depth + 1 };
|
|
100
|
+
const schema = def.schema;
|
|
101
|
+
if ('oneOf' in schema) {
|
|
102
|
+
return schema.oneOf.slice(0, EXAMPLE_BLOCK_VARIANTS).map((variant) => ({
|
|
103
|
+
_type: variant.uid,
|
|
104
|
+
...fillItem(variant.fields, childCtx),
|
|
105
|
+
}));
|
|
106
|
+
}
|
|
107
|
+
const itemCount = def.max === 1 ? 1 : EXAMPLE_REPEATABLE_ITEMS;
|
|
108
|
+
return Array.from({ length: itemCount }, () => fillItem(schema.fields, childCtx));
|
|
109
|
+
}
|
|
110
|
+
/** Fill every non-reference field of a block item. */
|
|
111
|
+
function fillItem(fields, ctx) {
|
|
112
|
+
const item = {};
|
|
113
|
+
for (const [name, def] of Object.entries(fields)) {
|
|
114
|
+
const value = fillFieldValue(name, def, ctx);
|
|
115
|
+
if (value !== undefined) {
|
|
116
|
+
item[name] = value;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
return item;
|
|
120
|
+
}
|
|
121
|
+
export function generateExampleSeed(schema, options = {}) {
|
|
122
|
+
const locale = options.locale;
|
|
123
|
+
const localeSuffix = locale ? ` (${locale})` : '';
|
|
124
|
+
const count = schema.isSingleton ? 1 : Math.max(1, options.count ?? DEFAULT_COUNT);
|
|
125
|
+
const references = {};
|
|
126
|
+
const rows = [];
|
|
127
|
+
for (let i = 1; i <= count; i += 1) {
|
|
128
|
+
const row = {};
|
|
129
|
+
if (!schema.isSingleton) {
|
|
130
|
+
row.slug = `${kebabCase(schema.name)}-example-${i}`;
|
|
131
|
+
}
|
|
132
|
+
for (const [field, def] of Object.entries(schema.fields)) {
|
|
133
|
+
// A connector-supplied example (dynamic zones, components) wins over the
|
|
134
|
+
// type-driven default — critical for dynamic zones, which must be arrays.
|
|
135
|
+
if (schema.examples && field in schema.examples) {
|
|
136
|
+
row[field] = schema.examples[field];
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
// References are top-level only: record the descriptor so the import
|
|
140
|
+
// endpoint resolves the slug to a documentId server-side.
|
|
141
|
+
if (def.type === 'reference') {
|
|
142
|
+
const value = exampleReferenceSlug(def);
|
|
143
|
+
if (value !== undefined) {
|
|
144
|
+
row[field] = value;
|
|
145
|
+
references[field] = {
|
|
146
|
+
...(def.target ? { target: def.target } : {}),
|
|
147
|
+
...(def.targets ? { targets: def.targets } : {}),
|
|
148
|
+
by: 'slug',
|
|
149
|
+
...(def.many ? { many: true } : {}),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
const value = fillFieldValue(field, def, { localeSuffix, index: i, schemaName: schema.name, depth: 0 });
|
|
155
|
+
if (value !== undefined) {
|
|
156
|
+
row[field] = value;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
rows.push(row);
|
|
160
|
+
}
|
|
161
|
+
return { name: schema.name, isSingleton: schema.isSingleton, localized: schema.localized, rows, references };
|
|
162
|
+
}
|