@@ -96,23 +96,39 @@ export default eventHandler(async (event) => {
9696 let parsed = destr ( content )
9797
9898 // Ensure we always return an object with a slug property
99- if ( typeof parsed === 'string ' || parsed === null ) {
100- // Try regex fallback if destr fails
99+ if ( typeof parsed !== 'object ' || parsed === null || Array . isArray ( parsed ) ) {
100+ // Try regex fallback if destr fails to produce an object
101101 const slugMatch = content . match ( / " s l u g " \s * : \s * " ( [ ^ " ] + ) " / )
102102 if ( slugMatch && slugMatch [ 1 ] ) {
103103 parsed = { slug : slugMatch [ 1 ] }
104104 }
105105 else {
106106 // Last resort fallback: try to find anything that looks like a slug in the string
107- const fallbackMatch = content . match ( / [ a - z 0 - 9 - ] + / i)
108- if ( fallbackMatch && fallbackMatch [ 0 ] && content . length < 50 ) {
109- parsed = { slug : fallbackMatch [ 0 ] . toLowerCase ( ) }
107+ // Look for an explicit "slug: <value>" first
108+ const explicitMatch = content . match ( / s l u g [: \s] + ( [ a - z 0 - 9 - ] + ) / i)
109+ if ( explicitMatch && explicitMatch [ 1 ] ) {
110+ parsed = { slug : explicitMatch [ 1 ] . toLowerCase ( ) }
110111 }
111112 else {
112- throw createError ( {
113- statusCode : 500 ,
114- statusMessage : 'Invalid AI response format' ,
115- } )
113+ // Try to find the most "slug-like" word in the content
114+ // Slugs are usually hyphenated or longer alphanumeric strings
115+ const words = content . match ( / [ a - z 0 - 9 - ] + / gi) || [ ]
116+ // Filter out common short words
117+ const candidates = words . filter ( w => w . length > 2 && ! [ 'the' , 'this' , 'that' , 'your' , 'with' , 'here' , 'your' , 'slug' ] . includes ( w . toLowerCase ( ) ) )
118+
119+ // Prioritize hyphenated words as they are likely intended as slugs
120+ const bestCandidate = candidates . find ( w => w . includes ( '-' ) ) || candidates [ 0 ] || words [ 0 ]
121+
122+ if ( bestCandidate ) {
123+ parsed = { slug : bestCandidate . toLowerCase ( ) }
124+ }
125+ else {
126+ console . error ( 'AI response parsing failed. Raw content:' , content )
127+ throw createError ( {
128+ statusCode : 500 ,
129+ statusMessage : 'Invalid AI response format' ,
130+ } )
131+ }
116132 }
117133 }
118134 }
0 commit comments