@synchronized-studio/cmsassets-agent 0.1.3 → 0.2.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/dist/aiReview-2CEFN6ZS.js +9 -0
- package/dist/aiReview-WD5QPIHJ.js +9 -0
- package/dist/chunk-HYSTWSLW.js +411 -0
- package/dist/chunk-MW74S44G.js +1073 -0
- package/dist/chunk-OJVHNQQN.js +1035 -0
- package/dist/chunk-RALRI2YO.js +406 -0
- package/dist/chunk-XHL55FTA.js +1745 -0
- package/dist/chunk-YZRA5AHC.js +1706 -0
- package/dist/cli.js +14 -5
- package/dist/index.d.ts +9 -9
- package/dist/index.js +3 -3
- package/package.json +2 -2
|
@@ -0,0 +1,1745 @@
|
|
|
1
|
+
import {
|
|
2
|
+
WRAP_TEMPLATES,
|
|
3
|
+
buildCmsOptions,
|
|
4
|
+
findInjectionPoints,
|
|
5
|
+
getImportStatement,
|
|
6
|
+
getTransformFunctionName,
|
|
7
|
+
validateDiff
|
|
8
|
+
} from "./chunk-MW74S44G.js";
|
|
9
|
+
import {
|
|
10
|
+
chatCompletion,
|
|
11
|
+
isOpenAiError
|
|
12
|
+
} from "./chunk-E74TGIFQ.js";
|
|
13
|
+
|
|
14
|
+
// src/scanner/index.ts
|
|
15
|
+
import { resolve } from "path";
|
|
16
|
+
|
|
17
|
+
// src/scanner/detectFramework.ts
|
|
18
|
+
import { existsSync, readFileSync } from "fs";
|
|
19
|
+
import { join } from "path";
|
|
20
|
+
var FRAMEWORK_SIGNATURES = {
|
|
21
|
+
nuxt: {
|
|
22
|
+
packages: ["nuxt"],
|
|
23
|
+
configFiles: ["nuxt.config.ts", "nuxt.config.js", "nuxt.config.mjs"]
|
|
24
|
+
},
|
|
25
|
+
next: {
|
|
26
|
+
packages: ["next"],
|
|
27
|
+
configFiles: ["next.config.js", "next.config.mjs", "next.config.ts"]
|
|
28
|
+
},
|
|
29
|
+
remix: {
|
|
30
|
+
packages: ["@remix-run/react", "@remix-run/node", "@remix-run/dev"],
|
|
31
|
+
configFiles: ["remix.config.js", "remix.config.ts"]
|
|
32
|
+
},
|
|
33
|
+
astro: {
|
|
34
|
+
packages: ["astro"],
|
|
35
|
+
configFiles: ["astro.config.mjs", "astro.config.ts", "astro.config.js"]
|
|
36
|
+
},
|
|
37
|
+
sveltekit: {
|
|
38
|
+
packages: ["@sveltejs/kit"],
|
|
39
|
+
configFiles: ["svelte.config.js", "svelte.config.ts"]
|
|
40
|
+
},
|
|
41
|
+
hono: {
|
|
42
|
+
packages: ["hono"],
|
|
43
|
+
configFiles: []
|
|
44
|
+
},
|
|
45
|
+
fastify: {
|
|
46
|
+
packages: ["fastify"],
|
|
47
|
+
configFiles: []
|
|
48
|
+
},
|
|
49
|
+
express: {
|
|
50
|
+
packages: ["express"],
|
|
51
|
+
configFiles: []
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
var DETECTION_ORDER = [
|
|
55
|
+
"nuxt",
|
|
56
|
+
"next",
|
|
57
|
+
"remix",
|
|
58
|
+
"astro",
|
|
59
|
+
"sveltekit",
|
|
60
|
+
"hono",
|
|
61
|
+
"fastify",
|
|
62
|
+
"express"
|
|
63
|
+
];
|
|
64
|
+
function readPackageJson(root) {
|
|
65
|
+
const pkgPath = join(root, "package.json");
|
|
66
|
+
if (!existsSync(pkgPath)) return null;
|
|
67
|
+
try {
|
|
68
|
+
const raw = readFileSync(pkgPath, "utf-8");
|
|
69
|
+
const pkg = JSON.parse(raw);
|
|
70
|
+
return {
|
|
71
|
+
dependencies: pkg.dependencies ?? {},
|
|
72
|
+
devDependencies: pkg.devDependencies ?? {}
|
|
73
|
+
};
|
|
74
|
+
} catch {
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function getVersionFromPkg(allDeps, packages) {
|
|
79
|
+
for (const pkg of packages) {
|
|
80
|
+
if (allDeps[pkg]) return allDeps[pkg];
|
|
81
|
+
}
|
|
82
|
+
return "";
|
|
83
|
+
}
|
|
84
|
+
function detectFramework(root) {
|
|
85
|
+
const pkg = readPackageJson(root);
|
|
86
|
+
const allDeps = {
|
|
87
|
+
...pkg?.dependencies ?? {},
|
|
88
|
+
...pkg?.devDependencies ?? {}
|
|
89
|
+
};
|
|
90
|
+
for (const name of DETECTION_ORDER) {
|
|
91
|
+
const sig = FRAMEWORK_SIGNATURES[name];
|
|
92
|
+
const hasPackage = sig.packages.some((p) => p in allDeps);
|
|
93
|
+
const configFile = sig.configFiles.find((f) => existsSync(join(root, f))) ?? null;
|
|
94
|
+
if (hasPackage || configFile) {
|
|
95
|
+
let resolvedName = name;
|
|
96
|
+
const version = getVersionFromPkg(allDeps, sig.packages);
|
|
97
|
+
if (name === "nuxt") {
|
|
98
|
+
const majorVersion = parseMajorVersion(version);
|
|
99
|
+
if (majorVersion !== null && majorVersion < 3) {
|
|
100
|
+
resolvedName = "nuxt2";
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return {
|
|
104
|
+
name: resolvedName,
|
|
105
|
+
version,
|
|
106
|
+
configFile
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return { name: "unknown", version: "", configFile: null };
|
|
111
|
+
}
|
|
112
|
+
function parseMajorVersion(versionRange) {
|
|
113
|
+
const cleaned = versionRange.replace(/^[\^~>=<\s]+/, "");
|
|
114
|
+
const major = parseInt(cleaned, 10);
|
|
115
|
+
return Number.isFinite(major) ? major : null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
// src/scanner/detectCms.ts
|
|
119
|
+
import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
|
|
120
|
+
import { join as join2, relative } from "path";
|
|
121
|
+
import fg from "fast-glob";
|
|
122
|
+
var CMS_SIGNATURES = {
|
|
123
|
+
prismic: {
|
|
124
|
+
packages: [
|
|
125
|
+
"@prismicio/client",
|
|
126
|
+
"@prismicio/vue",
|
|
127
|
+
"@prismicio/react",
|
|
128
|
+
"@prismicio/next",
|
|
129
|
+
"@prismicio/svelte",
|
|
130
|
+
"@nuxtjs/prismic"
|
|
131
|
+
],
|
|
132
|
+
urlPatterns: [
|
|
133
|
+
/https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/gi,
|
|
134
|
+
/https?:\/\/images\.prismic\.io\/([a-z0-9-]+)/gi
|
|
135
|
+
],
|
|
136
|
+
paramExtractors: {
|
|
137
|
+
repository: (match) => {
|
|
138
|
+
const m1 = match.match(/https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/);
|
|
139
|
+
if (m1) return m1[1];
|
|
140
|
+
const m2 = match.match(/https?:\/\/images\.prismic\.io\/([a-z0-9-]+)/);
|
|
141
|
+
if (m2) return m2[1];
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
contentful: {
|
|
147
|
+
packages: ["contentful"],
|
|
148
|
+
urlPatterns: [
|
|
149
|
+
/https?:\/\/images\.ctfassets\.net\/([a-z0-9]+)/gi,
|
|
150
|
+
/https?:\/\/videos\.ctfassets\.net\/([a-z0-9]+)/gi,
|
|
151
|
+
/https?:\/\/cdn\.contentful\.com\/spaces\/([a-z0-9]+)/gi
|
|
152
|
+
],
|
|
153
|
+
paramExtractors: {
|
|
154
|
+
spaceId: (match) => {
|
|
155
|
+
const m = match.match(/ctfassets\.net\/([a-z0-9]+)/) || match.match(/spaces\/([a-z0-9]+)/);
|
|
156
|
+
return m?.[1] ?? null;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
},
|
|
160
|
+
sanity: {
|
|
161
|
+
packages: ["@sanity/client", "next-sanity", "@nuxtjs/sanity", "sanity"],
|
|
162
|
+
urlPatterns: [
|
|
163
|
+
/https?:\/\/cdn\.sanity\.io\/(images|files)\/([a-z0-9]+)\/([a-z0-9-]+)/gi
|
|
164
|
+
],
|
|
165
|
+
paramExtractors: {
|
|
166
|
+
projectId: (match) => {
|
|
167
|
+
const m = match.match(/cdn\.sanity\.io\/(?:images|files)\/([a-z0-9]+)/);
|
|
168
|
+
return m?.[1] ?? null;
|
|
169
|
+
},
|
|
170
|
+
dataset: (match) => {
|
|
171
|
+
const m = match.match(
|
|
172
|
+
/cdn\.sanity\.io\/(?:images|files)\/[a-z0-9]+\/([a-z0-9-]+)/
|
|
173
|
+
);
|
|
174
|
+
return m?.[1] ?? null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
},
|
|
178
|
+
shopify: {
|
|
179
|
+
packages: [
|
|
180
|
+
"@shopify/storefront-api-client",
|
|
181
|
+
"@shopify/hydrogen",
|
|
182
|
+
"@shopify/shopify-api"
|
|
183
|
+
],
|
|
184
|
+
urlPatterns: [
|
|
185
|
+
/https?:\/\/([a-z0-9-]+)\.myshopify\.com\/cdn\//gi,
|
|
186
|
+
/https?:\/\/([a-z0-9-]+)\.myshopify\.com\/api\//gi
|
|
187
|
+
],
|
|
188
|
+
paramExtractors: {
|
|
189
|
+
storeDomain: (match) => {
|
|
190
|
+
const m = match.match(/https?:\/\/([a-z0-9-]+\.myshopify\.com)/);
|
|
191
|
+
return m?.[1] ?? null;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
},
|
|
195
|
+
cloudinary: {
|
|
196
|
+
packages: ["cloudinary", "@cloudinary/url-gen", "@cloudinary/react"],
|
|
197
|
+
urlPatterns: [/https?:\/\/res\.cloudinary\.com\/([a-z0-9_-]+)/gi],
|
|
198
|
+
paramExtractors: {
|
|
199
|
+
cloudName: (match) => {
|
|
200
|
+
const m = match.match(/res\.cloudinary\.com\/([a-z0-9_-]+)/);
|
|
201
|
+
return m?.[1] ?? null;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
},
|
|
205
|
+
imgix: {
|
|
206
|
+
packages: ["@imgix/js-core", "react-imgix", "vue-imgix"],
|
|
207
|
+
urlPatterns: [/https?:\/\/([a-z0-9-]+)\.imgix\.net/gi],
|
|
208
|
+
paramExtractors: {
|
|
209
|
+
imgixDomain: (match) => {
|
|
210
|
+
const m = match.match(/https?:\/\/([a-z0-9-]+\.imgix\.net)/);
|
|
211
|
+
return m?.[1] ?? null;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
};
|
|
216
|
+
var CMS_DETECTION_ORDER = [
|
|
217
|
+
"prismic",
|
|
218
|
+
"contentful",
|
|
219
|
+
"sanity",
|
|
220
|
+
"shopify",
|
|
221
|
+
"cloudinary",
|
|
222
|
+
"imgix"
|
|
223
|
+
];
|
|
224
|
+
var SOURCE_GLOBS = [
|
|
225
|
+
"**/*.ts",
|
|
226
|
+
"**/*.tsx",
|
|
227
|
+
"**/*.js",
|
|
228
|
+
"**/*.jsx",
|
|
229
|
+
"**/*.vue",
|
|
230
|
+
"**/*.svelte",
|
|
231
|
+
"**/*.astro",
|
|
232
|
+
"**/*.mjs",
|
|
233
|
+
"**/*.mts"
|
|
234
|
+
];
|
|
235
|
+
var IGNORE_DIRS = [
|
|
236
|
+
"node_modules",
|
|
237
|
+
".nuxt",
|
|
238
|
+
".next",
|
|
239
|
+
".output",
|
|
240
|
+
".svelte-kit",
|
|
241
|
+
"dist",
|
|
242
|
+
"build",
|
|
243
|
+
".git",
|
|
244
|
+
"coverage",
|
|
245
|
+
".cache"
|
|
246
|
+
];
|
|
247
|
+
function detectCms(root) {
|
|
248
|
+
const pkgPath = join2(root, "package.json");
|
|
249
|
+
let allDeps = {};
|
|
250
|
+
if (existsSync2(pkgPath)) {
|
|
251
|
+
try {
|
|
252
|
+
const pkg = JSON.parse(readFileSync2(pkgPath, "utf-8"));
|
|
253
|
+
allDeps = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
|
|
254
|
+
} catch {
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
for (const cmsName of CMS_DETECTION_ORDER) {
|
|
258
|
+
const sig = CMS_SIGNATURES[cmsName];
|
|
259
|
+
if (sig.packages.some((p) => p in allDeps)) {
|
|
260
|
+
const params = extractParamsFromSource(root, cmsName);
|
|
261
|
+
return {
|
|
262
|
+
type: cmsName,
|
|
263
|
+
params,
|
|
264
|
+
detectedFrom: ["package.json"]
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const sourceFiles = fg.sync(SOURCE_GLOBS, {
|
|
269
|
+
cwd: root,
|
|
270
|
+
ignore: IGNORE_DIRS.map((d) => `${d}/**`),
|
|
271
|
+
absolute: true,
|
|
272
|
+
onlyFiles: true,
|
|
273
|
+
deep: 6
|
|
274
|
+
});
|
|
275
|
+
for (const cmsName of CMS_DETECTION_ORDER) {
|
|
276
|
+
const sig = CMS_SIGNATURES[cmsName];
|
|
277
|
+
const matchingFiles = [];
|
|
278
|
+
const foundParams = {};
|
|
279
|
+
for (const file of sourceFiles) {
|
|
280
|
+
let content;
|
|
281
|
+
try {
|
|
282
|
+
content = readFileSync2(file, "utf-8");
|
|
283
|
+
} catch {
|
|
284
|
+
continue;
|
|
285
|
+
}
|
|
286
|
+
for (const pattern of sig.urlPatterns) {
|
|
287
|
+
pattern.lastIndex = 0;
|
|
288
|
+
const matches = content.match(pattern);
|
|
289
|
+
if (matches && matches.length > 0) {
|
|
290
|
+
matchingFiles.push(relative(root, file));
|
|
291
|
+
for (const m of matches) {
|
|
292
|
+
for (const [paramName, extractor] of Object.entries(sig.paramExtractors)) {
|
|
293
|
+
if (!foundParams[paramName]) {
|
|
294
|
+
const val = extractor(m);
|
|
295
|
+
if (val) foundParams[paramName] = val;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
if (matchingFiles.length > 0) {
|
|
303
|
+
return {
|
|
304
|
+
type: cmsName,
|
|
305
|
+
params: foundParams,
|
|
306
|
+
detectedFrom: [...new Set(matchingFiles)]
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
const genericPatterns = [
|
|
311
|
+
/https?:\/\/[a-z0-9-]+\.s3[.-][a-z0-9-]*\.amazonaws\.com/gi,
|
|
312
|
+
/https?:\/\/storage\.googleapis\.com\/[a-z0-9-]+/gi,
|
|
313
|
+
/https?:\/\/[a-z0-9-]+\.r2\.cloudflarestorage\.com/gi
|
|
314
|
+
];
|
|
315
|
+
for (const file of sourceFiles) {
|
|
316
|
+
let content;
|
|
317
|
+
try {
|
|
318
|
+
content = readFileSync2(file, "utf-8");
|
|
319
|
+
} catch {
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
for (const pattern of genericPatterns) {
|
|
323
|
+
pattern.lastIndex = 0;
|
|
324
|
+
const m = content.match(pattern);
|
|
325
|
+
if (m && m.length > 0) {
|
|
326
|
+
return {
|
|
327
|
+
type: "generic",
|
|
328
|
+
params: { originUrl: m[0] },
|
|
329
|
+
detectedFrom: [relative(root, file)]
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
return { type: "unknown", params: {}, detectedFrom: [] };
|
|
335
|
+
}
|
|
336
|
+
var CONFIG_FILES = [
|
|
337
|
+
"slicemachine.config.json",
|
|
338
|
+
"prismicio.config.ts",
|
|
339
|
+
"prismicio.config.js",
|
|
340
|
+
"sm.json",
|
|
341
|
+
".slicemachine.config.json",
|
|
342
|
+
"nuxt.config.ts",
|
|
343
|
+
"nuxt.config.js",
|
|
344
|
+
"next.config.js",
|
|
345
|
+
"next.config.mjs",
|
|
346
|
+
"next.config.ts",
|
|
347
|
+
"sanity.config.ts",
|
|
348
|
+
"sanity.config.js",
|
|
349
|
+
"sanity.cli.ts",
|
|
350
|
+
"sanity.cli.js"
|
|
351
|
+
];
|
|
352
|
+
var CONFIG_PARAM_PATTERNS = {
|
|
353
|
+
prismic: [
|
|
354
|
+
{ param: "repository", patterns: [
|
|
355
|
+
/["']?repositoryName["']?\s*[:=]\s*["']([a-z0-9-]+)["']/i,
|
|
356
|
+
/https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/i,
|
|
357
|
+
/["']?apiEndpoint["']?\s*[:=]\s*["']https?:\/\/([a-z0-9-]+)\.cdn\.prismic\.io/i
|
|
358
|
+
] }
|
|
359
|
+
],
|
|
360
|
+
contentful: [
|
|
361
|
+
{ param: "spaceId", patterns: [
|
|
362
|
+
/["']?space["']?\s*[:=]\s*["']([a-z0-9]+)["']/i,
|
|
363
|
+
/["']?spaceId["']?\s*[:=]\s*["']([a-z0-9]+)["']/i
|
|
364
|
+
] }
|
|
365
|
+
],
|
|
366
|
+
sanity: [
|
|
367
|
+
{ param: "projectId", patterns: [
|
|
368
|
+
/["']?projectId["']?\s*[:=]\s*["']([a-z0-9]+)["']/i
|
|
369
|
+
] },
|
|
370
|
+
{ param: "dataset", patterns: [
|
|
371
|
+
/["']?dataset["']?\s*[:=]\s*["']([a-z0-9-]+)["']/i
|
|
372
|
+
] }
|
|
373
|
+
],
|
|
374
|
+
shopify: [
|
|
375
|
+
{ param: "storeDomain", patterns: [
|
|
376
|
+
/["']?storeDomain["']?\s*[:=]\s*["']([a-z0-9-]+\.myshopify\.com)["']/i
|
|
377
|
+
] }
|
|
378
|
+
],
|
|
379
|
+
cloudinary: [
|
|
380
|
+
{ param: "cloudName", patterns: [
|
|
381
|
+
/["']?cloud_name["']?\s*[:=]\s*["']([a-z0-9_-]+)["']/i,
|
|
382
|
+
/["']?cloudName["']?\s*[:=]\s*["']([a-z0-9_-]+)["']/i
|
|
383
|
+
] }
|
|
384
|
+
],
|
|
385
|
+
imgix: [
|
|
386
|
+
{ param: "imgixDomain", patterns: [
|
|
387
|
+
/["']?domain["']?\s*[:=]\s*["']([a-z0-9-]+\.imgix\.net)["']/i
|
|
388
|
+
] }
|
|
389
|
+
]
|
|
390
|
+
};
|
|
391
|
+
function extractParamsFromSource(root, cmsName) {
|
|
392
|
+
const sig = CMS_SIGNATURES[cmsName];
|
|
393
|
+
if (!sig) return {};
|
|
394
|
+
const params = {};
|
|
395
|
+
const configPatterns = CONFIG_PARAM_PATTERNS[cmsName];
|
|
396
|
+
if (configPatterns) {
|
|
397
|
+
for (const cfgFile of CONFIG_FILES) {
|
|
398
|
+
const cfgPath = join2(root, cfgFile);
|
|
399
|
+
if (!existsSync2(cfgPath)) continue;
|
|
400
|
+
let content;
|
|
401
|
+
try {
|
|
402
|
+
content = readFileSync2(cfgPath, "utf-8");
|
|
403
|
+
} catch {
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
for (const { param, patterns } of configPatterns) {
|
|
407
|
+
if (params[param]) continue;
|
|
408
|
+
for (const pattern of patterns) {
|
|
409
|
+
const m = content.match(pattern);
|
|
410
|
+
if (m?.[1]) {
|
|
411
|
+
params[param] = m[1];
|
|
412
|
+
break;
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
if (Object.keys(params).length === Object.keys(sig.paramExtractors).length) {
|
|
418
|
+
return params;
|
|
419
|
+
}
|
|
420
|
+
}
|
|
421
|
+
const sourceFiles = fg.sync(SOURCE_GLOBS, {
|
|
422
|
+
cwd: root,
|
|
423
|
+
ignore: IGNORE_DIRS.map((d) => `${d}/**`),
|
|
424
|
+
absolute: true,
|
|
425
|
+
onlyFiles: true,
|
|
426
|
+
deep: 6
|
|
427
|
+
});
|
|
428
|
+
for (const file of sourceFiles) {
|
|
429
|
+
let content;
|
|
430
|
+
try {
|
|
431
|
+
content = readFileSync2(file, "utf-8");
|
|
432
|
+
} catch {
|
|
433
|
+
continue;
|
|
434
|
+
}
|
|
435
|
+
for (const pattern of sig.urlPatterns) {
|
|
436
|
+
pattern.lastIndex = 0;
|
|
437
|
+
const matches = content.match(pattern);
|
|
438
|
+
if (!matches) continue;
|
|
439
|
+
for (const m of matches) {
|
|
440
|
+
for (const [paramName, extractor] of Object.entries(sig.paramExtractors)) {
|
|
441
|
+
if (!params[paramName]) {
|
|
442
|
+
const val = extractor(m);
|
|
443
|
+
if (val) params[paramName] = val;
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
if (Object.keys(params).length === Object.keys(sig.paramExtractors).length) {
|
|
449
|
+
break;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
return params;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
// src/scanner/detectPackageManager.ts
|
|
456
|
+
import { existsSync as existsSync3 } from "fs";
|
|
457
|
+
import { join as join3 } from "path";
|
|
458
|
+
var LOCKFILE_MAP = [
|
|
459
|
+
["bun.lockb", "bun"],
|
|
460
|
+
["bun.lock", "bun"],
|
|
461
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
462
|
+
["yarn.lock", "yarn"],
|
|
463
|
+
["package-lock.json", "npm"]
|
|
464
|
+
];
|
|
465
|
+
function detectPackageManager(root) {
|
|
466
|
+
for (const [lockfile, pm] of LOCKFILE_MAP) {
|
|
467
|
+
if (existsSync3(join3(root, lockfile))) return pm;
|
|
468
|
+
}
|
|
469
|
+
return "npm";
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
// src/scanner/index.ts
|
|
473
|
+
function scan(projectRoot) {
|
|
474
|
+
const root = resolve(projectRoot ?? process.cwd());
|
|
475
|
+
const framework = detectFramework(root);
|
|
476
|
+
const cms = detectCms(root);
|
|
477
|
+
const packageManager = detectPackageManager(root);
|
|
478
|
+
const injectionPoints = findInjectionPoints(root, framework.name, cms);
|
|
479
|
+
return {
|
|
480
|
+
framework,
|
|
481
|
+
cms,
|
|
482
|
+
injectionPoints,
|
|
483
|
+
packageManager,
|
|
484
|
+
projectRoot: root
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// src/planner/index.ts
|
|
489
|
+
import { existsSync as existsSync4 } from "fs";
|
|
490
|
+
import { join as join4 } from "path";
|
|
491
|
+
function resolveInstallCommand(scan2) {
|
|
492
|
+
const pkg = "@synchronized-studio/response-transformer";
|
|
493
|
+
switch (scan2.packageManager) {
|
|
494
|
+
case "pnpm":
|
|
495
|
+
return `pnpm add ${pkg}`;
|
|
496
|
+
case "yarn":
|
|
497
|
+
return `yarn add ${pkg}`;
|
|
498
|
+
case "bun":
|
|
499
|
+
return `bun add ${pkg}`;
|
|
500
|
+
default:
|
|
501
|
+
return `npm install ${pkg}`;
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
function resolveEnvFiles(root) {
|
|
505
|
+
const candidates = [".env", ".env.local", ".env.example", ".env.development"];
|
|
506
|
+
return candidates.filter((f) => existsSync4(join4(root, f)));
|
|
507
|
+
}
|
|
508
|
+
function createPlan(scan2) {
|
|
509
|
+
const patches = [];
|
|
510
|
+
for (const candidate of scan2.injectionPoints) {
|
|
511
|
+
const template = WRAP_TEMPLATES[candidate.type];
|
|
512
|
+
if (!template) continue;
|
|
513
|
+
const importStatement = getImportStatement(scan2.cms.type);
|
|
514
|
+
const originalCode = candidate.targetCode;
|
|
515
|
+
if (!originalCode) continue;
|
|
516
|
+
if (/\.push\s*\(/.test(originalCode.trim())) continue;
|
|
517
|
+
const transformedCode = template.transform(
|
|
518
|
+
originalCode,
|
|
519
|
+
scan2.cms.type,
|
|
520
|
+
scan2.cms.params
|
|
521
|
+
);
|
|
522
|
+
if (transformedCode === originalCode) continue;
|
|
523
|
+
patches.push({
|
|
524
|
+
filePath: candidate.filePath,
|
|
525
|
+
description: template.description(scan2.cms.type),
|
|
526
|
+
importToAdd: importStatement,
|
|
527
|
+
wrapTarget: {
|
|
528
|
+
line: candidate.line,
|
|
529
|
+
originalCode,
|
|
530
|
+
transformedCode
|
|
531
|
+
},
|
|
532
|
+
confidence: candidate.confidence,
|
|
533
|
+
reasons: candidate.reasons
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
const envFiles = resolveEnvFiles(scan2.projectRoot);
|
|
537
|
+
return {
|
|
538
|
+
schemaVersion: "1.0",
|
|
539
|
+
scan: scan2,
|
|
540
|
+
install: {
|
|
541
|
+
package: "@synchronized-studio/response-transformer",
|
|
542
|
+
command: resolveInstallCommand(scan2)
|
|
543
|
+
},
|
|
544
|
+
env: {
|
|
545
|
+
key: "CMS_ASSETS_URL",
|
|
546
|
+
placeholder: "https://YOUR-SLUG.cmsassets.com",
|
|
547
|
+
files: envFiles
|
|
548
|
+
},
|
|
549
|
+
patches,
|
|
550
|
+
policies: {
|
|
551
|
+
maxFilesAutoApply: 20,
|
|
552
|
+
allowLlmFallback: false,
|
|
553
|
+
llmFallbackForAll: false,
|
|
554
|
+
llmOnly: false,
|
|
555
|
+
verifyProfile: "quick"
|
|
556
|
+
}
|
|
557
|
+
};
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// src/patcher/index.ts
|
|
561
|
+
import { appendFileSync, existsSync as existsSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync3 } from "fs";
|
|
562
|
+
import { join as join10 } from "path";
|
|
563
|
+
import consola from "consola";
|
|
564
|
+
|
|
565
|
+
// src/patcher/astPatcher.ts
|
|
566
|
+
import { Project as Project2, SyntaxKind as SyntaxKind2 } from "ts-morph";
|
|
567
|
+
import { readFileSync as readFileSync4, writeFileSync } from "fs";
|
|
568
|
+
import { join as join6, extname as extname2 } from "path";
|
|
569
|
+
|
|
570
|
+
// src/patcher/structuralValidator.ts
|
|
571
|
+
import { Project, SyntaxKind, ScriptKind } from "ts-morph";
|
|
572
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
573
|
+
import { join as join5, extname } from "path";
|
|
574
|
+
var TRANSFORMER_PKG = "@synchronized-studio/response-transformer";
|
|
575
|
+
function takeSnapshot(root, filePath) {
|
|
576
|
+
const absPath = join5(root, filePath);
|
|
577
|
+
const ext = extname(filePath);
|
|
578
|
+
let content;
|
|
579
|
+
try {
|
|
580
|
+
content = readFileSync3(absPath, "utf-8");
|
|
581
|
+
} catch {
|
|
582
|
+
return { exports: [], functions: [], variables: [], imports: [], content: "", syntaxValid: false };
|
|
583
|
+
}
|
|
584
|
+
if ([".vue", ".svelte", ".astro"].includes(ext)) {
|
|
585
|
+
return takeSnapshotFromString(content, ext);
|
|
586
|
+
}
|
|
587
|
+
return takeSnapshotFromAst(content, filePath);
|
|
588
|
+
}
|
|
589
|
+
function takeSnapshotFromAst(content, filePath) {
|
|
590
|
+
try {
|
|
591
|
+
const project = new Project({ useInMemoryFileSystem: true });
|
|
592
|
+
const ext = extname(filePath);
|
|
593
|
+
const scriptKind = ext === ".tsx" || ext === ".jsx" ? ScriptKind.TSX : ScriptKind.TS;
|
|
594
|
+
const sourceFile = project.createSourceFile("__snapshot__.tsx", content, { scriptKind });
|
|
595
|
+
const exports = sourceFile.getExportedDeclarations();
|
|
596
|
+
const exportNames = [...exports.keys()];
|
|
597
|
+
const functions = sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration).map((f) => f.getName()).filter((n) => !!n);
|
|
598
|
+
const arrowFunctions = sourceFile.getDescendantsOfKind(SyntaxKind.VariableDeclaration).filter((v) => v.getInitializerIfKind(SyntaxKind.ArrowFunction)).map((v) => v.getName());
|
|
599
|
+
const allFunctions = [.../* @__PURE__ */ new Set([...functions, ...arrowFunctions])];
|
|
600
|
+
const variables = sourceFile.getVariableDeclarations().map((v) => v.getName()).filter((name) => !allFunctions.includes(name));
|
|
601
|
+
const imports = sourceFile.getImportDeclarations().map((i) => i.getModuleSpecifierValue());
|
|
602
|
+
return {
|
|
603
|
+
exports: exportNames,
|
|
604
|
+
functions: allFunctions,
|
|
605
|
+
variables,
|
|
606
|
+
imports,
|
|
607
|
+
content,
|
|
608
|
+
syntaxValid: true
|
|
609
|
+
};
|
|
610
|
+
} catch {
|
|
611
|
+
return {
|
|
612
|
+
exports: [],
|
|
613
|
+
functions: [],
|
|
614
|
+
variables: [],
|
|
615
|
+
imports: [],
|
|
616
|
+
content,
|
|
617
|
+
syntaxValid: false
|
|
618
|
+
};
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
function takeSnapshotFromString(content, ext) {
|
|
622
|
+
const scriptContent = extractScriptBlock(content, ext);
|
|
623
|
+
if (!scriptContent) {
|
|
624
|
+
return { exports: [], functions: [], variables: [], imports: [], content, syntaxValid: true };
|
|
625
|
+
}
|
|
626
|
+
const exports = extractPatterns(scriptContent, /export\s+(?:default\s+)?(?:async\s+)?(?:function|const|let|var|class)\s+(\w+)/g);
|
|
627
|
+
const functions = extractPatterns(scriptContent, /(?:async\s+)?function\s+(\w+)\s*\(/g);
|
|
628
|
+
const arrowFns = extractPatterns(scriptContent, /(?:const|let)\s+(\w+)\s*=\s*(?:async\s+)?\([^)]*\)\s*=>/g);
|
|
629
|
+
const variables = extractPatterns(scriptContent, /(?:const|let|var)\s+(\w+)\s*=/g).filter((v) => !functions.includes(v) && !arrowFns.includes(v));
|
|
630
|
+
const imports = extractPatterns(scriptContent, /from\s+['"]([^'"]+)['"]/g);
|
|
631
|
+
return {
|
|
632
|
+
exports,
|
|
633
|
+
functions: [.../* @__PURE__ */ new Set([...functions, ...arrowFns])],
|
|
634
|
+
variables,
|
|
635
|
+
imports,
|
|
636
|
+
content,
|
|
637
|
+
syntaxValid: true
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function extractScriptBlock(content, ext) {
|
|
641
|
+
if (ext === ".astro") {
|
|
642
|
+
const match2 = content.match(/^---\n([\s\S]*?)\n---/);
|
|
643
|
+
return match2?.[1] ?? null;
|
|
644
|
+
}
|
|
645
|
+
const match = content.match(/<script[^>]*>([\s\S]*?)<\/script>/);
|
|
646
|
+
return match?.[1] ?? null;
|
|
647
|
+
}
|
|
648
|
+
function extractPatterns(content, pattern) {
|
|
649
|
+
const names = [];
|
|
650
|
+
let m;
|
|
651
|
+
while ((m = pattern.exec(content)) !== null) {
|
|
652
|
+
if (m[1]) names.push(m[1]);
|
|
653
|
+
}
|
|
654
|
+
return names;
|
|
655
|
+
}
|
|
656
|
+
function checkFunctionValueWrapping(originalCode, snapshot) {
|
|
657
|
+
const match = originalCode.match(/^return\s+\{([^}]+)\}\s*;?\s*$/);
|
|
658
|
+
if (!match) return { valid: true, errors: [] };
|
|
659
|
+
const inner = match[1].trim();
|
|
660
|
+
const parts = inner.split(",").map((p) => p.trim()).filter(Boolean);
|
|
661
|
+
const shorthandNames = [];
|
|
662
|
+
for (const part of parts) {
|
|
663
|
+
if (/^\w+$/.test(part)) {
|
|
664
|
+
shorthandNames.push(part);
|
|
665
|
+
} else {
|
|
666
|
+
return { valid: true, errors: [] };
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
if (shorthandNames.length === 0) return { valid: true, errors: [] };
|
|
670
|
+
const functionProps = shorthandNames.filter(
|
|
671
|
+
(name) => snapshot.functions.includes(name)
|
|
672
|
+
);
|
|
673
|
+
if (functionProps.length > 0) {
|
|
674
|
+
return {
|
|
675
|
+
valid: false,
|
|
676
|
+
errors: [
|
|
677
|
+
`Wrapping object containing function references (${functionProps.join(", ")}) with JSON-serializing transform would destroy them at runtime`
|
|
678
|
+
]
|
|
679
|
+
};
|
|
680
|
+
}
|
|
681
|
+
return { valid: true, errors: [] };
|
|
682
|
+
}
|
|
683
|
+
function validateContentAgainstSnapshot(newContent, filePath, snapshot) {
|
|
684
|
+
const ext = extname(filePath);
|
|
685
|
+
const errors = [];
|
|
686
|
+
let newSnapshot;
|
|
687
|
+
if ([".vue", ".svelte", ".astro"].includes(ext)) {
|
|
688
|
+
newSnapshot = takeSnapshotFromString(newContent, ext);
|
|
689
|
+
} else {
|
|
690
|
+
newSnapshot = takeSnapshotFromAst(newContent, filePath);
|
|
691
|
+
}
|
|
692
|
+
if (!newSnapshot.syntaxValid) {
|
|
693
|
+
errors.push("Patched file has syntax errors and cannot be parsed");
|
|
694
|
+
return { valid: false, errors };
|
|
695
|
+
}
|
|
696
|
+
const missingExports = snapshot.exports.filter((e) => !newSnapshot.exports.includes(e));
|
|
697
|
+
if (missingExports.length > 0) {
|
|
698
|
+
errors.push(`Missing exports after patch: ${missingExports.join(", ")}`);
|
|
699
|
+
}
|
|
700
|
+
const missingFunctions = snapshot.functions.filter((f) => !newSnapshot.functions.includes(f));
|
|
701
|
+
if (missingFunctions.length > 0) {
|
|
702
|
+
errors.push(`Missing functions after patch: ${missingFunctions.join(", ")}`);
|
|
703
|
+
}
|
|
704
|
+
const missingVariables = snapshot.variables.filter((v) => !newSnapshot.variables.includes(v));
|
|
705
|
+
if (missingVariables.length > 0) {
|
|
706
|
+
errors.push(`Missing variables after patch: ${missingVariables.join(", ")}`);
|
|
707
|
+
}
|
|
708
|
+
const removedImports = snapshot.imports.filter(
|
|
709
|
+
(i) => i !== TRANSFORMER_PKG && !newSnapshot.imports.includes(i)
|
|
710
|
+
);
|
|
711
|
+
if (removedImports.length > 0) {
|
|
712
|
+
errors.push(`Removed imports after patch: ${removedImports.join(", ")}`);
|
|
713
|
+
}
|
|
714
|
+
const addedImports = newSnapshot.imports.filter((i) => !snapshot.imports.includes(i));
|
|
715
|
+
const unexpectedImports = addedImports.filter((i) => i !== TRANSFORMER_PKG);
|
|
716
|
+
if (unexpectedImports.length > 0) {
|
|
717
|
+
errors.push(`Unexpected new imports: ${unexpectedImports.join(", ")}`);
|
|
718
|
+
}
|
|
719
|
+
return { valid: errors.length === 0, errors };
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// src/patcher/astPatcher.ts
|
|
723
|
+
function applyAstPatch(root, patch, dryRun, snapshot) {
|
|
724
|
+
const absPath = join6(root, patch.filePath);
|
|
725
|
+
const ext = extname2(patch.filePath);
|
|
726
|
+
if ([".vue", ".svelte", ".astro"].includes(ext)) {
|
|
727
|
+
return applyStringPatch(root, patch, dryRun, snapshot);
|
|
728
|
+
}
|
|
729
|
+
try {
|
|
730
|
+
const project = new Project2({ useInMemoryFileSystem: false });
|
|
731
|
+
const sourceFile = project.addSourceFileAtPath(absPath);
|
|
732
|
+
const originalText = sourceFile.getFullText();
|
|
733
|
+
const targetLine = patch.wrapTarget.line;
|
|
734
|
+
const original = patch.wrapTarget.originalCode.trim();
|
|
735
|
+
const transformed = patch.wrapTarget.transformedCode.trim();
|
|
736
|
+
if (original && transformed && original !== transformed) {
|
|
737
|
+
let patched = false;
|
|
738
|
+
const returnStatements = sourceFile.getDescendantsOfKind(
|
|
739
|
+
SyntaxKind2.ReturnStatement
|
|
740
|
+
);
|
|
741
|
+
for (const ret of returnStatements) {
|
|
742
|
+
const retLine = ret.getStartLineNumber();
|
|
743
|
+
if (retLine !== targetLine) continue;
|
|
744
|
+
const retText = ret.getText().trim();
|
|
745
|
+
if (retText.includes(original) || original.startsWith("return") && retText.startsWith("return") && normalizeReturnExpr(retText) === normalizeReturnExpr(original)) {
|
|
746
|
+
ret.replaceWithText(transformed);
|
|
747
|
+
patched = true;
|
|
748
|
+
break;
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
if (!patched) {
|
|
752
|
+
const expressions = sourceFile.getDescendantsOfKind(
|
|
753
|
+
SyntaxKind2.ExpressionStatement
|
|
754
|
+
);
|
|
755
|
+
for (const expr of expressions) {
|
|
756
|
+
const exprLine = expr.getStartLineNumber();
|
|
757
|
+
if (exprLine !== targetLine) continue;
|
|
758
|
+
const exprText = expr.getText().trim();
|
|
759
|
+
if (exprText.includes("res.json") || exprText.includes("c.json")) {
|
|
760
|
+
expr.replaceWithText(transformed);
|
|
761
|
+
patched = true;
|
|
762
|
+
break;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
if (!patched) {
|
|
767
|
+
for (const ret of returnStatements) {
|
|
768
|
+
const retLine = ret.getStartLineNumber();
|
|
769
|
+
if (Math.abs(retLine - targetLine) > 1) continue;
|
|
770
|
+
const retText = ret.getText().trim();
|
|
771
|
+
if (original.startsWith("return") && retText.startsWith("return")) {
|
|
772
|
+
if (normalizeReturnExpr(retText) !== normalizeReturnExpr(original)) continue;
|
|
773
|
+
ret.replaceWithText(transformed);
|
|
774
|
+
patched = true;
|
|
775
|
+
break;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
if (!patched) {
|
|
780
|
+
const currentText = sourceFile.getFullText();
|
|
781
|
+
const lines = currentText.split("\n");
|
|
782
|
+
const targetLineContent = lines[targetLine - 1];
|
|
783
|
+
if (targetLineContent && targetLineContent.trim() === original) {
|
|
784
|
+
const indent = targetLineContent.match(/^(\s*)/)?.[1] ?? "";
|
|
785
|
+
const newContent = currentText.replace(
|
|
786
|
+
targetLineContent,
|
|
787
|
+
indent + transformed
|
|
788
|
+
);
|
|
789
|
+
if (newContent !== currentText) {
|
|
790
|
+
sourceFile.replaceWithText(newContent);
|
|
791
|
+
patched = true;
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
if (!patched) {
|
|
796
|
+
const currentText = sourceFile.getFullText();
|
|
797
|
+
const lines = currentText.split("\n");
|
|
798
|
+
const targetIdx = Math.max(0, targetLine - 1);
|
|
799
|
+
const start = Math.max(0, targetIdx - 5);
|
|
800
|
+
const end = Math.min(lines.length - 1, targetIdx + 5);
|
|
801
|
+
for (let idx = start; idx <= end; idx++) {
|
|
802
|
+
const line = lines[idx];
|
|
803
|
+
const trimmed = line.trim();
|
|
804
|
+
if (trimmed === original || trimmed === original.replace(/;\s*$/, "")) {
|
|
805
|
+
const indent = line.match(/^(\s*)/)?.[1] ?? "";
|
|
806
|
+
lines[idx] = indent + transformed;
|
|
807
|
+
sourceFile.replaceWithText(lines.join("\n"));
|
|
808
|
+
patched = true;
|
|
809
|
+
break;
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
if (!patched) {
|
|
814
|
+
return { applied: false, reason: `Could not locate target code at line ${targetLine}` };
|
|
815
|
+
}
|
|
816
|
+
}
|
|
817
|
+
const existingImports = sourceFile.getImportDeclarations();
|
|
818
|
+
const hasImport = existingImports.some(
|
|
819
|
+
(i) => i.getModuleSpecifierValue() === "@synchronized-studio/response-transformer"
|
|
820
|
+
);
|
|
821
|
+
if (!hasImport && patch.importToAdd) {
|
|
822
|
+
const importMatch = patch.importToAdd.match(
|
|
823
|
+
/import\s*\{([^}]+)\}\s*from\s*['"]([^'"]+)['"]/
|
|
824
|
+
);
|
|
825
|
+
if (importMatch) {
|
|
826
|
+
const namedImports = importMatch[1].split(",").map((s) => s.trim()).filter(Boolean);
|
|
827
|
+
sourceFile.addImportDeclaration({
|
|
828
|
+
moduleSpecifier: importMatch[2],
|
|
829
|
+
namedImports
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
const newText = sourceFile.getFullText();
|
|
834
|
+
if (newText === originalText) {
|
|
835
|
+
return { applied: false, reason: "No changes needed (idempotent)" };
|
|
836
|
+
}
|
|
837
|
+
if (snapshot) {
|
|
838
|
+
const validation = validateContentAgainstSnapshot(newText, patch.filePath, snapshot);
|
|
839
|
+
if (!validation.valid) {
|
|
840
|
+
return {
|
|
841
|
+
applied: false,
|
|
842
|
+
validationFailed: true,
|
|
843
|
+
reason: `Structural validation failed: ${validation.errors.join("; ")}`
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (!dryRun) {
|
|
848
|
+
sourceFile.saveSync();
|
|
849
|
+
}
|
|
850
|
+
return { applied: true };
|
|
851
|
+
} catch (err) {
|
|
852
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
853
|
+
return { applied: false, reason: `AST patch failed: ${msg}` };
|
|
854
|
+
}
|
|
855
|
+
}
|
|
856
|
+
function normalizeReturnExpr(value) {
|
|
857
|
+
return value.replace(/^return\s+/, "").replace(/;$/, "").replace(/\s+/g, " ").trim();
|
|
858
|
+
}
|
|
859
|
+
function applyStringPatch(root, patch, dryRun, snapshot) {
|
|
860
|
+
const absPath = join6(root, patch.filePath);
|
|
861
|
+
let content;
|
|
862
|
+
try {
|
|
863
|
+
content = readFileSync4(absPath, "utf-8");
|
|
864
|
+
} catch (err) {
|
|
865
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
866
|
+
return { applied: false, reason: `Cannot read file: ${msg}` };
|
|
867
|
+
}
|
|
868
|
+
const originalContent = content;
|
|
869
|
+
const { originalCode, transformedCode } = patch.wrapTarget;
|
|
870
|
+
if (originalCode && transformedCode && originalCode !== transformedCode) {
|
|
871
|
+
if (content.includes(originalCode.trim())) {
|
|
872
|
+
content = content.replace(originalCode.trim(), transformedCode.trim());
|
|
873
|
+
} else {
|
|
874
|
+
return {
|
|
875
|
+
applied: false,
|
|
876
|
+
reason: "Original code not found in file (string match)"
|
|
877
|
+
};
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
if (patch.importToAdd && !content.includes("@synchronized-studio/response-transformer")) {
|
|
881
|
+
const scriptMatch = content.match(
|
|
882
|
+
/(<script[^>]*>)\s*\n/
|
|
883
|
+
);
|
|
884
|
+
if (scriptMatch) {
|
|
885
|
+
const insertAfter = scriptMatch[0];
|
|
886
|
+
content = content.replace(
|
|
887
|
+
insertAfter,
|
|
888
|
+
`${insertAfter}${patch.importToAdd}
|
|
889
|
+
`
|
|
890
|
+
);
|
|
891
|
+
} else if (patch.filePath.endsWith(".astro")) {
|
|
892
|
+
const fmMatch = content.match(/^(---\n)/);
|
|
893
|
+
if (fmMatch) {
|
|
894
|
+
content = content.replace(
|
|
895
|
+
"---\n",
|
|
896
|
+
`---
|
|
897
|
+
${patch.importToAdd}
|
|
898
|
+
`
|
|
899
|
+
);
|
|
900
|
+
}
|
|
901
|
+
}
|
|
902
|
+
}
|
|
903
|
+
if (content === originalContent) {
|
|
904
|
+
return { applied: false, reason: "No changes needed (idempotent)" };
|
|
905
|
+
}
|
|
906
|
+
if (snapshot) {
|
|
907
|
+
const validation = validateContentAgainstSnapshot(content, patch.filePath, snapshot);
|
|
908
|
+
if (!validation.valid) {
|
|
909
|
+
return {
|
|
910
|
+
applied: false,
|
|
911
|
+
validationFailed: true,
|
|
912
|
+
reason: `Structural validation failed: ${validation.errors.join("; ")}`
|
|
913
|
+
};
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
if (!dryRun) {
|
|
917
|
+
writeFileSync(absPath, content, "utf-8");
|
|
918
|
+
}
|
|
919
|
+
return { applied: true };
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
// src/patcher/llmFallback.ts
|
|
923
|
+
import { readFileSync as readFileSync5 } from "fs";
|
|
924
|
+
import { join as join7 } from "path";
|
|
925
|
+
function buildPrompt(fileContent, filePath, cms, framework) {
|
|
926
|
+
const fn = getTransformFunctionName(cms.type);
|
|
927
|
+
const opts = buildCmsOptions(cms.type, cms.params);
|
|
928
|
+
return `You are a code integration agent. Given the following file, add the
|
|
929
|
+
@synchronized-studio/response-transformer to transform CMS asset URLs.
|
|
930
|
+
|
|
931
|
+
CMS: ${cms.type}
|
|
932
|
+
Transform function: ${fn}
|
|
933
|
+
Options: ${opts}
|
|
934
|
+
Framework: ${framework}
|
|
935
|
+
|
|
936
|
+
File: ${filePath}
|
|
937
|
+
\`\`\`
|
|
938
|
+
${fileContent}
|
|
939
|
+
\`\`\`
|
|
940
|
+
|
|
941
|
+
Return ONLY a unified diff that:
|
|
942
|
+
1. Adds the import: import { ${fn} } from '@synchronized-studio/response-transformer'
|
|
943
|
+
2. Wraps the CMS data return/assignment with ${fn}(data, ${opts})
|
|
944
|
+
3. Does NOT change any other code
|
|
945
|
+
|
|
946
|
+
Output ONLY the diff, nothing else.`;
|
|
947
|
+
}
|
|
948
|
+
async function applyLlmPatch(root, patch, cms, framework) {
|
|
949
|
+
const absPath = join7(root, patch.filePath);
|
|
950
|
+
let fileContent;
|
|
951
|
+
try {
|
|
952
|
+
fileContent = readFileSync5(absPath, "utf-8");
|
|
953
|
+
} catch (err) {
|
|
954
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
955
|
+
return { applied: false, reason: `Cannot read file: ${msg}`, requiresReview: true };
|
|
956
|
+
}
|
|
957
|
+
const prompt = buildPrompt(fileContent, patch.filePath, cms, framework);
|
|
958
|
+
const result = await chatCompletion(prompt, { model: "gpt-4o-mini", maxTokens: 2e3 });
|
|
959
|
+
if (isOpenAiError(result)) {
|
|
960
|
+
return { applied: false, reason: result.error, requiresReview: true };
|
|
961
|
+
}
|
|
962
|
+
const diff = result.content;
|
|
963
|
+
if (!diff) {
|
|
964
|
+
return { applied: false, reason: "LLM returned empty response", requiresReview: true };
|
|
965
|
+
}
|
|
966
|
+
const validation = validateDiff(diff, [patch.filePath]);
|
|
967
|
+
if (!validation.valid) {
|
|
968
|
+
return {
|
|
969
|
+
applied: false,
|
|
970
|
+
reason: `LLM diff failed validation: ${validation.errors.join("; ")}`,
|
|
971
|
+
diff,
|
|
972
|
+
requiresReview: true
|
|
973
|
+
};
|
|
974
|
+
}
|
|
975
|
+
return {
|
|
976
|
+
applied: false,
|
|
977
|
+
reason: "LLM patch generated, requires manual review before applying",
|
|
978
|
+
diff,
|
|
979
|
+
requiresReview: true
|
|
980
|
+
};
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
// src/patcher/llmCompletePatch.ts
|
|
984
|
+
import { readFileSync as readFileSync6, writeFileSync as writeFileSync2 } from "fs";
|
|
985
|
+
import { join as join8 } from "path";
|
|
986
|
+
function buildPrompt2(fileContent, filePath, patch, cms, framework) {
|
|
987
|
+
const fn = getTransformFunctionName(cms.type);
|
|
988
|
+
const opts = buildCmsOptions(cms.type, cms.params);
|
|
989
|
+
const importStatement = `import { ${fn} } from '@synchronized-studio/response-transformer'`;
|
|
990
|
+
return `You are a precise code integration agent. Your task is to make EXACTLY TWO changes to the file below:
|
|
991
|
+
|
|
992
|
+
1. Add this import at the top (with the other imports):
|
|
993
|
+
${importStatement}
|
|
994
|
+
|
|
995
|
+
2. Wrap the target code near line ${patch.wrapTarget.line}:
|
|
996
|
+
BEFORE: ${patch.wrapTarget.originalCode}
|
|
997
|
+
AFTER: ${patch.wrapTarget.transformedCode}
|
|
998
|
+
|
|
999
|
+
CRITICAL RULES:
|
|
1000
|
+
- Return the COMPLETE modified file \u2014 every single line
|
|
1001
|
+
- Do NOT change, remove, rename, or restructure ANY other code
|
|
1002
|
+
- Do NOT add comments explaining your changes
|
|
1003
|
+
- Do NOT change formatting, indentation, or whitespace of untouched lines
|
|
1004
|
+
- Every function, variable, export, and import that exists in the original MUST remain
|
|
1005
|
+
- If unsure about a change, do NOT make it \u2014 only make the two changes above
|
|
1006
|
+
|
|
1007
|
+
CMS: ${cms.type}
|
|
1008
|
+
Framework: ${framework}
|
|
1009
|
+
|
|
1010
|
+
File: ${filePath}
|
|
1011
|
+
\`\`\`
|
|
1012
|
+
${fileContent}
|
|
1013
|
+
\`\`\`
|
|
1014
|
+
|
|
1015
|
+
Return ONLY the complete modified file content. No markdown fences, no explanation \u2014 just the raw file content.`;
|
|
1016
|
+
}
|
|
1017
|
+
async function applyLlmCompletePatch(root, patch, cms, framework, snapshot) {
|
|
1018
|
+
const absPath = join8(root, patch.filePath);
|
|
1019
|
+
let fileContent;
|
|
1020
|
+
try {
|
|
1021
|
+
fileContent = readFileSync6(absPath, "utf-8");
|
|
1022
|
+
} catch (err) {
|
|
1023
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1024
|
+
return { applied: false, reason: `Cannot read file: ${msg}` };
|
|
1025
|
+
}
|
|
1026
|
+
const prompt = buildPrompt2(fileContent, patch.filePath, patch, cms, framework);
|
|
1027
|
+
const result = await chatCompletion(prompt, {
|
|
1028
|
+
model: "gpt-4o",
|
|
1029
|
+
maxTokens: 16e3,
|
|
1030
|
+
temperature: 0
|
|
1031
|
+
});
|
|
1032
|
+
if (isOpenAiError(result)) {
|
|
1033
|
+
return { applied: false, reason: result.error };
|
|
1034
|
+
}
|
|
1035
|
+
let newContent = result.content;
|
|
1036
|
+
if (!newContent) {
|
|
1037
|
+
return { applied: false, reason: "LLM returned empty response" };
|
|
1038
|
+
}
|
|
1039
|
+
newContent = stripCodeFences(newContent);
|
|
1040
|
+
if (newContent.trim() === fileContent.trim()) {
|
|
1041
|
+
return { applied: false, reason: "LLM returned unchanged file" };
|
|
1042
|
+
}
|
|
1043
|
+
const fn = getTransformFunctionName(cms.type);
|
|
1044
|
+
if (!newContent.includes(fn)) {
|
|
1045
|
+
return { applied: false, reason: "LLM output missing transform function call" };
|
|
1046
|
+
}
|
|
1047
|
+
if (!newContent.includes("@synchronized-studio/response-transformer")) {
|
|
1048
|
+
return { applied: false, reason: "LLM output missing transformer import" };
|
|
1049
|
+
}
|
|
1050
|
+
const validation = validateContentAgainstSnapshot(newContent, patch.filePath, snapshot);
|
|
1051
|
+
if (!validation.valid) {
|
|
1052
|
+
return {
|
|
1053
|
+
applied: false,
|
|
1054
|
+
validationFailed: true,
|
|
1055
|
+
reason: `LLM output failed structural validation: ${validation.errors.join("; ")}`
|
|
1056
|
+
};
|
|
1057
|
+
}
|
|
1058
|
+
writeFileSync2(absPath, newContent, "utf-8");
|
|
1059
|
+
return { applied: true };
|
|
1060
|
+
}
|
|
1061
|
+
function stripCodeFences(content) {
|
|
1062
|
+
const fenceStart = /^```\w*\n/;
|
|
1063
|
+
const fenceEnd = /\n```\s*$/;
|
|
1064
|
+
if (fenceStart.test(content) && fenceEnd.test(content)) {
|
|
1065
|
+
return content.replace(fenceStart, "").replace(fenceEnd, "");
|
|
1066
|
+
}
|
|
1067
|
+
return content;
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// src/patcher/idempotency.ts
|
|
1071
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
1072
|
+
import { join as join9 } from "path";
|
|
1073
|
+
var TRANSFORMER_IMPORTS = [
|
|
1074
|
+
"@synchronized-studio/response-transformer",
|
|
1075
|
+
"transformCmsAssetUrls",
|
|
1076
|
+
"transformPrismicAssetUrls",
|
|
1077
|
+
"transformContentfulAssetUrls",
|
|
1078
|
+
"transformSanityAssetUrls",
|
|
1079
|
+
"transformShopifyAssetUrls",
|
|
1080
|
+
"transformCloudinaryAssetUrls",
|
|
1081
|
+
"transformImgixAssetUrls",
|
|
1082
|
+
"transformGenericAssetUrls"
|
|
1083
|
+
];
|
|
1084
|
+
function isAlreadyTransformed(root, filePath) {
|
|
1085
|
+
const absPath = join9(root, filePath);
|
|
1086
|
+
let content;
|
|
1087
|
+
try {
|
|
1088
|
+
content = readFileSync7(absPath, "utf-8");
|
|
1089
|
+
} catch {
|
|
1090
|
+
return false;
|
|
1091
|
+
}
|
|
1092
|
+
return TRANSFORMER_IMPORTS.some((sig) => content.includes(sig));
|
|
1093
|
+
}
|
|
1094
|
+
function isTestOrFixtureFile(filePath) {
|
|
1095
|
+
return /\.(test|spec)\.[jt]sx?$/.test(filePath) || /__tests__\//.test(filePath) || /(^|\/)tests?\//.test(filePath) || /(^|\/)fixtures?\//.test(filePath) || /(^|\/)mocks?\//.test(filePath) || /\.stories\.[jt]sx?$/.test(filePath);
|
|
1096
|
+
}
|
|
1097
|
+
function isGeneratedFile(filePath) {
|
|
1098
|
+
return /\.generated\.[jt]sx?$/.test(filePath) || /\.g\.[jt]sx?$/.test(filePath) || /(^|\/)\.nuxt\//.test(filePath) || /(^|\/)\.next\//.test(filePath) || /(^|\/)\.svelte-kit\//.test(filePath) || /(^|\/)dist\//.test(filePath) || /(^|\/)build\//.test(filePath);
|
|
1099
|
+
}
|
|
1100
|
+
|
|
1101
|
+
// src/patcher/index.ts
|
|
1102
|
+
async function applyPlan(plan, opts = {}) {
|
|
1103
|
+
const startTime = Date.now();
|
|
1104
|
+
const root = plan.scan.projectRoot;
|
|
1105
|
+
const dryRun = opts.dryRun ?? false;
|
|
1106
|
+
const includeTests = opts.includeTests ?? false;
|
|
1107
|
+
const maxFiles = opts.maxFiles ?? plan.policies.maxFilesAutoApply;
|
|
1108
|
+
const files = [];
|
|
1109
|
+
let appliedCount = 0;
|
|
1110
|
+
const patchedFiles = /* @__PURE__ */ new Set();
|
|
1111
|
+
const alreadyTransformedAtStart = new Set(
|
|
1112
|
+
plan.patches.map((patch) => patch.filePath).filter((filePath, index, all) => all.indexOf(filePath) === index).filter((filePath) => isAlreadyTransformed(root, filePath))
|
|
1113
|
+
);
|
|
1114
|
+
for (const patch of plan.patches) {
|
|
1115
|
+
const fileStart = Date.now();
|
|
1116
|
+
if (alreadyTransformedAtStart.has(patch.filePath)) {
|
|
1117
|
+
files.push({
|
|
1118
|
+
filePath: patch.filePath,
|
|
1119
|
+
applied: false,
|
|
1120
|
+
method: "skipped",
|
|
1121
|
+
reason: "Transformer already present in file",
|
|
1122
|
+
durationMs: Date.now() - fileStart
|
|
1123
|
+
});
|
|
1124
|
+
continue;
|
|
1125
|
+
}
|
|
1126
|
+
if (!includeTests && isTestOrFixtureFile(patch.filePath)) {
|
|
1127
|
+
files.push({
|
|
1128
|
+
filePath: patch.filePath,
|
|
1129
|
+
applied: false,
|
|
1130
|
+
method: "skipped",
|
|
1131
|
+
reason: "Test/fixture file excluded (use --include-tests to include)",
|
|
1132
|
+
durationMs: Date.now() - fileStart
|
|
1133
|
+
});
|
|
1134
|
+
continue;
|
|
1135
|
+
}
|
|
1136
|
+
if (isGeneratedFile(patch.filePath)) {
|
|
1137
|
+
files.push({
|
|
1138
|
+
filePath: patch.filePath,
|
|
1139
|
+
applied: false,
|
|
1140
|
+
method: "skipped",
|
|
1141
|
+
reason: "Generated file excluded",
|
|
1142
|
+
durationMs: Date.now() - fileStart
|
|
1143
|
+
});
|
|
1144
|
+
continue;
|
|
1145
|
+
}
|
|
1146
|
+
if (!patchedFiles.has(patch.filePath) && appliedCount >= maxFiles) {
|
|
1147
|
+
files.push({
|
|
1148
|
+
filePath: patch.filePath,
|
|
1149
|
+
applied: false,
|
|
1150
|
+
method: "skipped",
|
|
1151
|
+
reason: `Max files threshold reached (${maxFiles})`,
|
|
1152
|
+
durationMs: Date.now() - fileStart
|
|
1153
|
+
});
|
|
1154
|
+
continue;
|
|
1155
|
+
}
|
|
1156
|
+
const snapshot = takeSnapshot(root, patch.filePath);
|
|
1157
|
+
const fnGuard = checkFunctionValueWrapping(patch.wrapTarget.originalCode, snapshot);
|
|
1158
|
+
if (!fnGuard.valid) {
|
|
1159
|
+
consola.warn(`Skipping ${patch.filePath}: ${fnGuard.errors[0]}`);
|
|
1160
|
+
files.push({
|
|
1161
|
+
filePath: patch.filePath,
|
|
1162
|
+
applied: false,
|
|
1163
|
+
method: "skipped",
|
|
1164
|
+
reason: fnGuard.errors[0],
|
|
1165
|
+
durationMs: Date.now() - fileStart
|
|
1166
|
+
});
|
|
1167
|
+
continue;
|
|
1168
|
+
}
|
|
1169
|
+
if (plan.policies.llmOnly && plan.policies.allowLlmFallback) {
|
|
1170
|
+
consola.info(`LLM-only mode: ${patch.filePath}...`);
|
|
1171
|
+
const llmResult = await applyLlmCompletePatch(
|
|
1172
|
+
root,
|
|
1173
|
+
patch,
|
|
1174
|
+
plan.scan.cms,
|
|
1175
|
+
plan.scan.framework.name,
|
|
1176
|
+
snapshot
|
|
1177
|
+
);
|
|
1178
|
+
files.push({
|
|
1179
|
+
filePath: patch.filePath,
|
|
1180
|
+
applied: llmResult.applied,
|
|
1181
|
+
method: llmResult.applied ? "llm-complete" : "skipped",
|
|
1182
|
+
reason: llmResult.reason,
|
|
1183
|
+
durationMs: Date.now() - fileStart
|
|
1184
|
+
});
|
|
1185
|
+
if (llmResult.applied && !patchedFiles.has(patch.filePath)) {
|
|
1186
|
+
patchedFiles.add(patch.filePath);
|
|
1187
|
+
appliedCount++;
|
|
1188
|
+
}
|
|
1189
|
+
continue;
|
|
1190
|
+
}
|
|
1191
|
+
const astResult = applyAstPatch(root, patch, dryRun, snapshot);
|
|
1192
|
+
if (astResult.applied) {
|
|
1193
|
+
if (!patchedFiles.has(patch.filePath)) {
|
|
1194
|
+
patchedFiles.add(patch.filePath);
|
|
1195
|
+
appliedCount++;
|
|
1196
|
+
}
|
|
1197
|
+
files.push({
|
|
1198
|
+
filePath: patch.filePath,
|
|
1199
|
+
applied: true,
|
|
1200
|
+
method: "ast",
|
|
1201
|
+
durationMs: Date.now() - fileStart
|
|
1202
|
+
});
|
|
1203
|
+
continue;
|
|
1204
|
+
}
|
|
1205
|
+
const shouldTryLlmComplete = astResult.validationFailed || plan.policies.allowLlmFallback && (plan.policies.llmFallbackForAll || patch.confidence === "low");
|
|
1206
|
+
if (shouldTryLlmComplete) {
|
|
1207
|
+
const reason = astResult.validationFailed ? "AST validation failed" : "AST patch failed";
|
|
1208
|
+
consola.info(`${reason} for ${patch.filePath}, trying LLM complete-file fallback...`);
|
|
1209
|
+
if (snapshot.content) {
|
|
1210
|
+
const absPath = join10(root, patch.filePath);
|
|
1211
|
+
try {
|
|
1212
|
+
const currentContent = readFileSync8(absPath, "utf-8");
|
|
1213
|
+
if (currentContent !== snapshot.content) {
|
|
1214
|
+
writeFileSync3(absPath, snapshot.content, "utf-8");
|
|
1215
|
+
}
|
|
1216
|
+
} catch {
|
|
1217
|
+
}
|
|
1218
|
+
}
|
|
1219
|
+
const llmResult = await applyLlmCompletePatch(
|
|
1220
|
+
root,
|
|
1221
|
+
patch,
|
|
1222
|
+
plan.scan.cms,
|
|
1223
|
+
plan.scan.framework.name,
|
|
1224
|
+
snapshot
|
|
1225
|
+
);
|
|
1226
|
+
if (llmResult.applied) {
|
|
1227
|
+
if (!patchedFiles.has(patch.filePath)) {
|
|
1228
|
+
patchedFiles.add(patch.filePath);
|
|
1229
|
+
appliedCount++;
|
|
1230
|
+
}
|
|
1231
|
+
files.push({
|
|
1232
|
+
filePath: patch.filePath,
|
|
1233
|
+
applied: true,
|
|
1234
|
+
method: "llm-complete",
|
|
1235
|
+
durationMs: Date.now() - fileStart
|
|
1236
|
+
});
|
|
1237
|
+
continue;
|
|
1238
|
+
}
|
|
1239
|
+
if (plan.policies.allowLlmFallback) {
|
|
1240
|
+
const legacyResult = await applyLlmPatch(
|
|
1241
|
+
root,
|
|
1242
|
+
patch,
|
|
1243
|
+
plan.scan.cms,
|
|
1244
|
+
plan.scan.framework.name
|
|
1245
|
+
);
|
|
1246
|
+
files.push({
|
|
1247
|
+
filePath: patch.filePath,
|
|
1248
|
+
applied: legacyResult.applied,
|
|
1249
|
+
method: legacyResult.applied ? "llm" : "skipped",
|
|
1250
|
+
reason: legacyResult.reason,
|
|
1251
|
+
durationMs: Date.now() - fileStart
|
|
1252
|
+
});
|
|
1253
|
+
if (legacyResult.applied && !patchedFiles.has(patch.filePath)) {
|
|
1254
|
+
patchedFiles.add(patch.filePath);
|
|
1255
|
+
appliedCount++;
|
|
1256
|
+
}
|
|
1257
|
+
continue;
|
|
1258
|
+
}
|
|
1259
|
+
files.push({
|
|
1260
|
+
filePath: patch.filePath,
|
|
1261
|
+
applied: false,
|
|
1262
|
+
method: "skipped",
|
|
1263
|
+
reason: llmResult.reason ?? "Both AST and LLM complete-file patch failed",
|
|
1264
|
+
durationMs: Date.now() - fileStart
|
|
1265
|
+
});
|
|
1266
|
+
continue;
|
|
1267
|
+
}
|
|
1268
|
+
files.push({
|
|
1269
|
+
filePath: patch.filePath,
|
|
1270
|
+
applied: false,
|
|
1271
|
+
method: "skipped",
|
|
1272
|
+
reason: astResult.reason ?? "AST patch could not be applied",
|
|
1273
|
+
durationMs: Date.now() - fileStart
|
|
1274
|
+
});
|
|
1275
|
+
}
|
|
1276
|
+
let envUpdated = false;
|
|
1277
|
+
if (!dryRun) {
|
|
1278
|
+
for (const envFile of plan.env.files) {
|
|
1279
|
+
const envPath = join10(root, envFile);
|
|
1280
|
+
if (existsSync5(envPath)) {
|
|
1281
|
+
const content = readFileSync8(envPath, "utf-8");
|
|
1282
|
+
if (!content.includes(plan.env.key)) {
|
|
1283
|
+
appendFileSync(envPath, `
|
|
1284
|
+
${plan.env.key}=${plan.env.placeholder}
|
|
1285
|
+
`);
|
|
1286
|
+
envUpdated = true;
|
|
1287
|
+
}
|
|
1288
|
+
}
|
|
1289
|
+
}
|
|
1290
|
+
if (plan.env.files.length === 0) {
|
|
1291
|
+
const envExamplePath = join10(root, ".env.example");
|
|
1292
|
+
writeFileSync3(
|
|
1293
|
+
envExamplePath,
|
|
1294
|
+
`${plan.env.key}=${plan.env.placeholder}
|
|
1295
|
+
`,
|
|
1296
|
+
"utf-8"
|
|
1297
|
+
);
|
|
1298
|
+
envUpdated = true;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
return {
|
|
1302
|
+
schemaVersion: "1.0",
|
|
1303
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1304
|
+
projectRoot: root,
|
|
1305
|
+
gitBranch: null,
|
|
1306
|
+
gitCommit: null,
|
|
1307
|
+
installed: false,
|
|
1308
|
+
envUpdated,
|
|
1309
|
+
files,
|
|
1310
|
+
totalDurationMs: Date.now() - startTime
|
|
1311
|
+
};
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
// src/types.ts
|
|
1315
|
+
import { z } from "zod/v3";
|
|
1316
|
+
var FrameworkName = z.enum([
|
|
1317
|
+
"nuxt",
|
|
1318
|
+
"nuxt2",
|
|
1319
|
+
"next",
|
|
1320
|
+
"remix",
|
|
1321
|
+
"astro",
|
|
1322
|
+
"sveltekit",
|
|
1323
|
+
"express",
|
|
1324
|
+
"hono",
|
|
1325
|
+
"fastify",
|
|
1326
|
+
"unknown"
|
|
1327
|
+
]);
|
|
1328
|
+
var CmsType = z.enum([
|
|
1329
|
+
"prismic",
|
|
1330
|
+
"contentful",
|
|
1331
|
+
"sanity",
|
|
1332
|
+
"shopify",
|
|
1333
|
+
"cloudinary",
|
|
1334
|
+
"imgix",
|
|
1335
|
+
"generic",
|
|
1336
|
+
"unknown"
|
|
1337
|
+
]);
|
|
1338
|
+
var PackageManager = z.enum(["npm", "yarn", "pnpm", "bun"]);
|
|
1339
|
+
var Confidence = z.enum(["high", "medium", "low"]);
|
|
1340
|
+
var InjectionType = z.enum([
|
|
1341
|
+
"return",
|
|
1342
|
+
"res.json",
|
|
1343
|
+
"assignment",
|
|
1344
|
+
"useFetch-transform",
|
|
1345
|
+
"useAsyncData-transform",
|
|
1346
|
+
"loader-return",
|
|
1347
|
+
"getServerSideProps-return",
|
|
1348
|
+
"getStaticProps-return",
|
|
1349
|
+
"load-return",
|
|
1350
|
+
"frontmatter-assignment",
|
|
1351
|
+
"asyncData-return",
|
|
1352
|
+
"vuex-action-return"
|
|
1353
|
+
]);
|
|
1354
|
+
var VerifyProfile = z.enum(["quick", "full"]);
|
|
1355
|
+
var FrameworkInfo = z.object({
|
|
1356
|
+
name: FrameworkName,
|
|
1357
|
+
version: z.string(),
|
|
1358
|
+
configFile: z.string().nullable()
|
|
1359
|
+
});
|
|
1360
|
+
var CmsInfo = z.object({
|
|
1361
|
+
type: CmsType,
|
|
1362
|
+
params: z.record(z.string()),
|
|
1363
|
+
detectedFrom: z.array(z.string())
|
|
1364
|
+
});
|
|
1365
|
+
var InjectionCandidate = z.object({
|
|
1366
|
+
filePath: z.string(),
|
|
1367
|
+
line: z.number(),
|
|
1368
|
+
type: InjectionType,
|
|
1369
|
+
score: z.number().min(0).max(100),
|
|
1370
|
+
confidence: Confidence,
|
|
1371
|
+
targetCode: z.string(),
|
|
1372
|
+
context: z.string(),
|
|
1373
|
+
reasons: z.array(z.string())
|
|
1374
|
+
});
|
|
1375
|
+
var ScanResult = z.object({
|
|
1376
|
+
framework: FrameworkInfo,
|
|
1377
|
+
cms: CmsInfo,
|
|
1378
|
+
injectionPoints: z.array(InjectionCandidate),
|
|
1379
|
+
packageManager: PackageManager,
|
|
1380
|
+
projectRoot: z.string()
|
|
1381
|
+
});
|
|
1382
|
+
var FilePatch = z.object({
|
|
1383
|
+
filePath: z.string(),
|
|
1384
|
+
description: z.string(),
|
|
1385
|
+
importToAdd: z.string(),
|
|
1386
|
+
wrapTarget: z.object({
|
|
1387
|
+
line: z.number(),
|
|
1388
|
+
originalCode: z.string(),
|
|
1389
|
+
transformedCode: z.string()
|
|
1390
|
+
}),
|
|
1391
|
+
confidence: Confidence,
|
|
1392
|
+
reasons: z.array(z.string())
|
|
1393
|
+
});
|
|
1394
|
+
var PatchPlan = z.object({
|
|
1395
|
+
schemaVersion: z.literal("1.0"),
|
|
1396
|
+
scan: ScanResult,
|
|
1397
|
+
install: z.object({
|
|
1398
|
+
package: z.literal("@synchronized-studio/response-transformer"),
|
|
1399
|
+
command: z.string()
|
|
1400
|
+
}),
|
|
1401
|
+
env: z.object({
|
|
1402
|
+
key: z.literal("CMS_ASSETS_URL"),
|
|
1403
|
+
placeholder: z.string(),
|
|
1404
|
+
files: z.array(z.string())
|
|
1405
|
+
}),
|
|
1406
|
+
patches: z.array(FilePatch),
|
|
1407
|
+
policies: z.object({
|
|
1408
|
+
maxFilesAutoApply: z.number().default(20),
|
|
1409
|
+
allowLlmFallback: z.boolean().default(false),
|
|
1410
|
+
/** When true, try LLM for any failed AST patch (not just low confidence). Useful for testing. */
|
|
1411
|
+
llmFallbackForAll: z.boolean().default(false),
|
|
1412
|
+
/** When true, skip AST entirely and use LLM for all patches (testing only). */
|
|
1413
|
+
llmOnly: z.boolean().default(false),
|
|
1414
|
+
verifyProfile: VerifyProfile.default("quick")
|
|
1415
|
+
})
|
|
1416
|
+
});
|
|
1417
|
+
var PatchedFileReport = z.object({
|
|
1418
|
+
filePath: z.string(),
|
|
1419
|
+
applied: z.boolean(),
|
|
1420
|
+
method: z.enum(["ast", "llm", "llm-complete", "skipped"]),
|
|
1421
|
+
reason: z.string().optional(),
|
|
1422
|
+
durationMs: z.number()
|
|
1423
|
+
});
|
|
1424
|
+
var ApplyReport = z.object({
|
|
1425
|
+
schemaVersion: z.literal("1.0"),
|
|
1426
|
+
timestamp: z.string(),
|
|
1427
|
+
projectRoot: z.string(),
|
|
1428
|
+
gitBranch: z.string().nullable(),
|
|
1429
|
+
gitCommit: z.string().nullable(),
|
|
1430
|
+
installed: z.boolean(),
|
|
1431
|
+
envUpdated: z.boolean(),
|
|
1432
|
+
files: z.array(PatchedFileReport),
|
|
1433
|
+
totalDurationMs: z.number()
|
|
1434
|
+
});
|
|
1435
|
+
var VerifyReport = z.object({
|
|
1436
|
+
schemaVersion: z.literal("1.0"),
|
|
1437
|
+
profile: VerifyProfile,
|
|
1438
|
+
lintPassed: z.boolean().nullable(),
|
|
1439
|
+
buildPassed: z.boolean().nullable(),
|
|
1440
|
+
testsPassed: z.boolean().nullable(),
|
|
1441
|
+
patchedFiles: z.array(z.string()),
|
|
1442
|
+
warnings: z.array(z.string()),
|
|
1443
|
+
durationMs: z.number()
|
|
1444
|
+
});
|
|
1445
|
+
var AiFileResult = z.object({
|
|
1446
|
+
filePath: z.string(),
|
|
1447
|
+
passed: z.boolean(),
|
|
1448
|
+
issues: z.array(z.string()),
|
|
1449
|
+
fixAttempted: z.boolean(),
|
|
1450
|
+
fixApplied: z.boolean(),
|
|
1451
|
+
iterations: z.number()
|
|
1452
|
+
});
|
|
1453
|
+
var AiReviewReport = z.object({
|
|
1454
|
+
schemaVersion: z.literal("1.0"),
|
|
1455
|
+
filesReviewed: z.number(),
|
|
1456
|
+
filesPassed: z.number(),
|
|
1457
|
+
filesFixed: z.number(),
|
|
1458
|
+
filesFailed: z.number(),
|
|
1459
|
+
results: z.array(AiFileResult),
|
|
1460
|
+
totalDurationMs: z.number(),
|
|
1461
|
+
tokensUsed: z.number()
|
|
1462
|
+
});
|
|
1463
|
+
|
|
1464
|
+
// src/reporting/index.ts
|
|
1465
|
+
import { readFileSync as readFileSync9, writeFileSync as writeFileSync4, existsSync as existsSync6, mkdirSync } from "fs";
|
|
1466
|
+
import { join as join11 } from "path";
|
|
1467
|
+
import consola2 from "consola";
|
|
1468
|
+
function createReport(parts) {
|
|
1469
|
+
return {
|
|
1470
|
+
version: "1.0",
|
|
1471
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1472
|
+
...parts
|
|
1473
|
+
};
|
|
1474
|
+
}
|
|
1475
|
+
function saveReport(root, report) {
|
|
1476
|
+
const dir = join11(root, ".cmsassets-agent");
|
|
1477
|
+
if (!existsSync6(dir)) {
|
|
1478
|
+
mkdirSync(dir, { recursive: true });
|
|
1479
|
+
}
|
|
1480
|
+
const filename = `report-${Date.now()}.json`;
|
|
1481
|
+
const filePath = join11(dir, filename);
|
|
1482
|
+
writeFileSync4(filePath, JSON.stringify(report, null, 2), "utf-8");
|
|
1483
|
+
consola2.info(`Report saved to ${filePath}`);
|
|
1484
|
+
return filePath;
|
|
1485
|
+
}
|
|
1486
|
+
function savePlanFile(root, plan) {
|
|
1487
|
+
const filePath = join11(root, "cmsassets-agent.plan.json");
|
|
1488
|
+
writeFileSync4(filePath, JSON.stringify(plan, null, 2), "utf-8");
|
|
1489
|
+
consola2.info(`Plan saved to ${filePath}`);
|
|
1490
|
+
return filePath;
|
|
1491
|
+
}
|
|
1492
|
+
function loadPlanFile(filePath) {
|
|
1493
|
+
try {
|
|
1494
|
+
const raw = JSON.parse(readFileSync9(filePath, "utf-8"));
|
|
1495
|
+
const result = PatchPlan.safeParse(raw);
|
|
1496
|
+
if (result.success) return result.data;
|
|
1497
|
+
consola2.error("Plan file validation failed:", result.error.issues);
|
|
1498
|
+
return null;
|
|
1499
|
+
} catch (err) {
|
|
1500
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
1501
|
+
consola2.error(`Failed to load plan file: ${msg}`);
|
|
1502
|
+
return null;
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
// src/git/index.ts
|
|
1507
|
+
import { execSync } from "child_process";
|
|
1508
|
+
import consola3 from "consola";
|
|
1509
|
+
function exec(cmd, cwd) {
|
|
1510
|
+
try {
|
|
1511
|
+
return execSync(cmd, { cwd, encoding: "utf-8", stdio: "pipe" }).trim();
|
|
1512
|
+
} catch {
|
|
1513
|
+
return "";
|
|
1514
|
+
}
|
|
1515
|
+
}
|
|
1516
|
+
var gitOps = {
|
|
1517
|
+
isGitRepo(cwd) {
|
|
1518
|
+
return exec("git rev-parse --is-inside-work-tree", cwd) === "true";
|
|
1519
|
+
},
|
|
1520
|
+
isClean(cwd) {
|
|
1521
|
+
return exec("git diff --quiet && git diff --cached --quiet && echo clean", cwd) === "clean";
|
|
1522
|
+
},
|
|
1523
|
+
getCurrentBranch(cwd) {
|
|
1524
|
+
const branch = exec("git branch --show-current", cwd);
|
|
1525
|
+
return branch || null;
|
|
1526
|
+
},
|
|
1527
|
+
getHeadCommit(cwd) {
|
|
1528
|
+
const hash = exec("git rev-parse --short HEAD", cwd);
|
|
1529
|
+
return hash || null;
|
|
1530
|
+
},
|
|
1531
|
+
createBranch(cwd, name) {
|
|
1532
|
+
try {
|
|
1533
|
+
execSync(`git checkout -b ${name}`, { cwd, stdio: "pipe" });
|
|
1534
|
+
return true;
|
|
1535
|
+
} catch {
|
|
1536
|
+
consola3.warn(`Failed to create branch: ${name}`);
|
|
1537
|
+
return false;
|
|
1538
|
+
}
|
|
1539
|
+
},
|
|
1540
|
+
stageAll(cwd) {
|
|
1541
|
+
execSync("git add -A", { cwd, stdio: "pipe" });
|
|
1542
|
+
},
|
|
1543
|
+
commit(cwd, message) {
|
|
1544
|
+
try {
|
|
1545
|
+
execSync(`git commit -m "${message.replace(/"/g, '\\"')}"`, {
|
|
1546
|
+
cwd,
|
|
1547
|
+
stdio: "pipe"
|
|
1548
|
+
});
|
|
1549
|
+
return exec("git rev-parse --short HEAD", cwd);
|
|
1550
|
+
} catch {
|
|
1551
|
+
consola3.warn("Failed to create commit");
|
|
1552
|
+
return null;
|
|
1553
|
+
}
|
|
1554
|
+
},
|
|
1555
|
+
rollbackToCommit(cwd, commitHash) {
|
|
1556
|
+
try {
|
|
1557
|
+
execSync(`git reset --hard ${commitHash}`, { cwd, stdio: "pipe" });
|
|
1558
|
+
return true;
|
|
1559
|
+
} catch {
|
|
1560
|
+
consola3.error(`Failed to rollback to ${commitHash}`);
|
|
1561
|
+
return false;
|
|
1562
|
+
}
|
|
1563
|
+
},
|
|
1564
|
+
getLastCommitByAgent(cwd) {
|
|
1565
|
+
const log = exec(
|
|
1566
|
+
'git log --oneline --all --grep="cmsassets-agent" -n 1 --format="%H"',
|
|
1567
|
+
cwd
|
|
1568
|
+
);
|
|
1569
|
+
return log || null;
|
|
1570
|
+
},
|
|
1571
|
+
getCommitBefore(cwd, commitHash) {
|
|
1572
|
+
const parent = exec(`git rev-parse ${commitHash}~1`, cwd);
|
|
1573
|
+
return parent || null;
|
|
1574
|
+
},
|
|
1575
|
+
push(cwd, remote = "origin") {
|
|
1576
|
+
try {
|
|
1577
|
+
const branch = exec("git branch --show-current", cwd);
|
|
1578
|
+
execSync(`git push -u ${remote} ${branch}`, { cwd, stdio: "pipe" });
|
|
1579
|
+
return true;
|
|
1580
|
+
} catch {
|
|
1581
|
+
consola3.warn("Failed to push to remote");
|
|
1582
|
+
return false;
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
};
|
|
1586
|
+
|
|
1587
|
+
// src/verifier/index.ts
|
|
1588
|
+
import { execSync as execSync2 } from "child_process";
|
|
1589
|
+
import consola4 from "consola";
|
|
1590
|
+
|
|
1591
|
+
// src/verifier/profiles.ts
|
|
1592
|
+
function getQuickSteps(framework) {
|
|
1593
|
+
const steps = [];
|
|
1594
|
+
switch (framework) {
|
|
1595
|
+
case "nuxt":
|
|
1596
|
+
case "nuxt2":
|
|
1597
|
+
steps.push({
|
|
1598
|
+
name: "nuxt-prepare",
|
|
1599
|
+
command: "npx nuxt prepare",
|
|
1600
|
+
required: false
|
|
1601
|
+
});
|
|
1602
|
+
break;
|
|
1603
|
+
case "next":
|
|
1604
|
+
steps.push({
|
|
1605
|
+
name: "tsc-noEmit",
|
|
1606
|
+
command: "npx tsc --noEmit",
|
|
1607
|
+
required: false
|
|
1608
|
+
});
|
|
1609
|
+
break;
|
|
1610
|
+
case "astro":
|
|
1611
|
+
steps.push({
|
|
1612
|
+
name: "astro-check",
|
|
1613
|
+
command: "npx astro check",
|
|
1614
|
+
required: false
|
|
1615
|
+
});
|
|
1616
|
+
break;
|
|
1617
|
+
case "sveltekit":
|
|
1618
|
+
steps.push({
|
|
1619
|
+
name: "svelte-check",
|
|
1620
|
+
command: "npx svelte-check",
|
|
1621
|
+
required: false
|
|
1622
|
+
});
|
|
1623
|
+
break;
|
|
1624
|
+
default:
|
|
1625
|
+
steps.push({
|
|
1626
|
+
name: "tsc-noEmit",
|
|
1627
|
+
command: "npx tsc --noEmit",
|
|
1628
|
+
required: false
|
|
1629
|
+
});
|
|
1630
|
+
}
|
|
1631
|
+
return steps;
|
|
1632
|
+
}
|
|
1633
|
+
function getFullSteps(framework) {
|
|
1634
|
+
const steps = getQuickSteps(framework);
|
|
1635
|
+
steps.push({
|
|
1636
|
+
name: "lint",
|
|
1637
|
+
command: "npm run lint",
|
|
1638
|
+
required: false
|
|
1639
|
+
});
|
|
1640
|
+
switch (framework) {
|
|
1641
|
+
case "nuxt":
|
|
1642
|
+
case "nuxt2":
|
|
1643
|
+
steps.push({ name: "build", command: "npm run build", required: true });
|
|
1644
|
+
break;
|
|
1645
|
+
case "next":
|
|
1646
|
+
steps.push({ name: "build", command: "npm run build", required: true });
|
|
1647
|
+
break;
|
|
1648
|
+
case "astro":
|
|
1649
|
+
steps.push({ name: "build", command: "npm run build", required: true });
|
|
1650
|
+
break;
|
|
1651
|
+
case "sveltekit":
|
|
1652
|
+
steps.push({ name: "build", command: "npm run build", required: true });
|
|
1653
|
+
break;
|
|
1654
|
+
default:
|
|
1655
|
+
steps.push({ name: "build", command: "npm run build", required: false });
|
|
1656
|
+
}
|
|
1657
|
+
steps.push({
|
|
1658
|
+
name: "test",
|
|
1659
|
+
command: "npm test",
|
|
1660
|
+
required: false
|
|
1661
|
+
});
|
|
1662
|
+
return steps;
|
|
1663
|
+
}
|
|
1664
|
+
function getVerifySteps(profile, framework) {
|
|
1665
|
+
return profile === "full" ? getFullSteps(framework) : getQuickSteps(framework);
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
// src/verifier/index.ts
|
|
1669
|
+
function verify(root, opts = {}) {
|
|
1670
|
+
const startTime = Date.now();
|
|
1671
|
+
const profile = opts.profile ?? "quick";
|
|
1672
|
+
const framework = opts.framework ?? "unknown";
|
|
1673
|
+
const patchedFiles = opts.patchedFiles ?? [];
|
|
1674
|
+
const warnings = [];
|
|
1675
|
+
const steps = getVerifySteps(profile, framework);
|
|
1676
|
+
let lintPassed = null;
|
|
1677
|
+
let buildPassed = null;
|
|
1678
|
+
let testsPassed = null;
|
|
1679
|
+
for (const step of steps) {
|
|
1680
|
+
consola4.info(`Running: ${step.name} (${step.command})`);
|
|
1681
|
+
try {
|
|
1682
|
+
execSync2(step.command, {
|
|
1683
|
+
cwd: root,
|
|
1684
|
+
stdio: "pipe",
|
|
1685
|
+
timeout: 12e4
|
|
1686
|
+
});
|
|
1687
|
+
if (step.name === "lint") lintPassed = true;
|
|
1688
|
+
if (step.name === "build") buildPassed = true;
|
|
1689
|
+
if (step.name === "test") testsPassed = true;
|
|
1690
|
+
consola4.success(`${step.name} passed`);
|
|
1691
|
+
} catch (err) {
|
|
1692
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
1693
|
+
const truncated = message.substring(0, 500);
|
|
1694
|
+
if (step.name === "lint") lintPassed = false;
|
|
1695
|
+
if (step.name === "build") buildPassed = false;
|
|
1696
|
+
if (step.name === "test") testsPassed = false;
|
|
1697
|
+
if (step.required) {
|
|
1698
|
+
consola4.error(`${step.name} FAILED: ${truncated}`);
|
|
1699
|
+
warnings.push(`${step.name} failed (required): ${truncated}`);
|
|
1700
|
+
} else {
|
|
1701
|
+
consola4.warn(`${step.name} failed (optional): ${truncated}`);
|
|
1702
|
+
warnings.push(`${step.name} failed (optional): ${truncated}`);
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
return {
|
|
1707
|
+
schemaVersion: "1.0",
|
|
1708
|
+
profile,
|
|
1709
|
+
lintPassed,
|
|
1710
|
+
buildPassed,
|
|
1711
|
+
testsPassed,
|
|
1712
|
+
patchedFiles,
|
|
1713
|
+
warnings,
|
|
1714
|
+
durationMs: Date.now() - startTime
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
export {
|
|
1719
|
+
scan,
|
|
1720
|
+
createPlan,
|
|
1721
|
+
applyPlan,
|
|
1722
|
+
FrameworkName,
|
|
1723
|
+
CmsType,
|
|
1724
|
+
PackageManager,
|
|
1725
|
+
Confidence,
|
|
1726
|
+
InjectionType,
|
|
1727
|
+
VerifyProfile,
|
|
1728
|
+
FrameworkInfo,
|
|
1729
|
+
CmsInfo,
|
|
1730
|
+
InjectionCandidate,
|
|
1731
|
+
ScanResult,
|
|
1732
|
+
FilePatch,
|
|
1733
|
+
PatchPlan,
|
|
1734
|
+
PatchedFileReport,
|
|
1735
|
+
ApplyReport,
|
|
1736
|
+
VerifyReport,
|
|
1737
|
+
AiFileResult,
|
|
1738
|
+
AiReviewReport,
|
|
1739
|
+
createReport,
|
|
1740
|
+
saveReport,
|
|
1741
|
+
savePlanFile,
|
|
1742
|
+
loadPlanFile,
|
|
1743
|
+
gitOps,
|
|
1744
|
+
verify
|
|
1745
|
+
};
|