"use strict";exports.id=9310,exports.ids=[9310],exports.modules={9310:(a,b,c)=>{c.d(b,{G:()=>ac,d:()=>ab});var d=c(9021),e=c.n(d),f=c(9288),g=c.n(f),h=c(9484),i=c(6357),j=c(1254),k=c(2363),l=c(7044),m=c(3945),n=c(8281),o=c(7167);class p extends Error{constructor(){super("Task stopped"),this.name="TaskStoppedError"}}function q(a){return a instanceof DOMException&&"AbortError"===a.name}function r(a){return(0,o.nZ)(a.resolutionPreset)}function s(a,b){return[`Category: ${a.category}`,`Age group: ${a.ageGroup}`,`Generation mode: ${a.generationMode}`,`Product name: ${a.productName}`,`Product basic info: ${a.productInfo}`,`Image mode: ${a.imageMode||"create"}`,`Strict consistency: ${a.strictConsistency?"enabled":"disabled"}`,`Reference image weight: ${a.referenceImageWeight??70}/100`,`Image resolution: ${(0,o.iZ)(r(a))}`,a.productSpecs?`Product specs: ${a.productSpecs}`:"",a.productUrl?`Product source URL: ${a.productUrl}`:"",a.linkExtractStatus?`Product URL extraction status: ${a.linkExtractStatus}`:"",a.linkExtractSummary?`Product URL extracted summary:
${a.linkExtractSummary}`:"",a.additionalRequirements?`Additional requirements: ${a.additionalRequirements}`:"",b.length?`Uploaded images: ${b.join(", ")}`:"Uploaded images: none",a.shoeSoleImageFileIds?.length?`Sole reference image count: ${a.shoeSoleImageFileIds.length}`:"","鞋子"===a.category?"Shoes must be generated as clean side-view product images.":""].filter(Boolean).join("\n")}function t(a,b=4){let c=a.slice(0,b),d=[];for(let a of c)try{if(e().statSync(a.absPath).size>8388608)continue;let b=e().readFileSync(a.absPath);d.push({bytes:b,mimeType:a.mimeType||"image/jpeg",fileName:a.fileName})}catch{}return d}async function u(a){let b=t([a],1)[0];try{let c=g()(a.absPath,{failOn:"none"}).rotate(),d=await c.metadata(),e=d.width||0,f=d.height||0;if(e<64||f<64)return{analysisImages:b?[b]:[],generationBaseImage:b};let h=Math.max(1,Math.min(f-1,Math.round(.58*f))),i=Math.max(0,h-Math.round(.04*f)),j=Math.max(1,f-i),k=await c.clone().extract({left:0,top:0,width:e,height:h}).trim().png({compressionLevel:9}).toBuffer(),l=await c.clone().extract({left:0,top:i,width:e,height:j}).trim().png({compressionLevel:9}).toBuffer(),m={bytes:k,mimeType:"image/png",fileName:`${a.fileName}-outsole-bottom.png`},n={bytes:l,mimeType:"image/png",fileName:`${a.fileName}-outsole-side.png`};return{analysisImages:[m,n],generationBaseImage:n}}catch{return{analysisImages:b?[b]:[],generationBaseImage:b}}}function v(a,b){if(b<=1)return 0;try{let c=JSON.parse(a),d=Number(c?.selected_index??c?.selectedIndex??c?.index);if(Number.isFinite(d))return Math.max(0,Math.min(b-1,Math.round(d)-1))}catch{}let c=a.match(/(\d+)/);return c?Math.max(0,Math.min(b-1,Number(c[1])-1)):0}function w(a){let b=a.trim();try{let a=JSON.parse(b);if(Array.isArray(a)&&a.every(a=>a&&"object"==typeof a&&!Array.isArray(a)))return a}catch{}let c=b.match(/\[[\s\S]*\]/);if(!c)return null;try{let a=JSON.parse(c[0]);if(Array.isArray(a)&&a.every(a=>a&&"object"==typeof a&&!Array.isArray(a)))return a}catch{}return null}function x(a,b){return"string"==typeof a&&a.trim()?a.trim():b}function y(a,b,c){var d;return a.length?a[(d=a.length)<=1?0:c>0&&c<d?Math.min(d-1,Math.floor(b*d/c)):b%d]?.sourceIndex??a[0].sourceIndex:-1}function z(a,b){return Array.from({length:b},(c,d)=>y(a,d,b))}function A(a){return a>=85?"extreme_lock":a>=72?"high_lock":a>=60?"stable_innovation":a>=45?"moderate_innovation":"free_exploration"}function B(a){return"same_colorways"===a.generationMode||a.strictConsistency}async function C(a,b,c,d,e){let f=c.map(a=>a.trim()).filter(Boolean);return f.length?1===f.length?f[0]:a.generateText({system:"You are a fashion reference synthesizer. Merge multiple grounded summaries into one concise JSON-only synthesis. Keep only compatible traits, repeated themes, and production-usable conclusions. Do not invent facts.",user:`Synthesize the following ${b} summaries into one concise JSON with keys: shared_shape, shared_colors, shared_materials, shared_structure, design_direction, cautions. Language: ${d}.

`+f.map((a,b)=>`Summary ${b+1}:
${a}`).join("\n\n"),signal:e}):""}async function D(a,b,c,d,e){let f=Array.from({length:d},(b,c)=>({index:c,title:"same_colorways"===a.generationMode?`Colorway ${c+1}`:`Design ${c+1}`,designDirection:"same_colorways"===a.generationMode?"Keep the same product family and structural direction while changing the color balance.":"Create a fresh design direction synthesized from all uploaded references instead of copying any single reference.",keyColors:a.additionalRequirements||a.productInfo||"Balanced market-ready color story.",materialFocus:a.productSpecs||"Keep materials production-realistic and category-appropriate.",upperStructure:"鞋子"===a.category?"Clean side-view upper with production-friendly panel split and wearable proportion.":"Preserve category structure and commercially usable silhouette.",silhouetteNotes:"鞋子"===a.category?"Only side-view shoe presentation, square composition, product fills most of the frame.":"Single product hero view, square composition, no multi-product collage.",soleMatchCues:"鞋子"===a.category?"Match the outsole family to the concept and keep outsole shape, tread, thickness, and structure unchanged.":""}));try{let g=await b.generateText({system:"You are a fashion concept planner. Build commercially usable design concepts by synthesizing all uploaded references together. Never map one concept to just the first, second, or nth reference image. Extract shared themes, style logic, color language, and market direction first, then derive concepts from that synthesis.",user:`Generate exactly ${d} design concepts in strict JSON array format only. Language: ${a.language}. Category: ${a.category}. Age group: ${a.ageGroup}. Generation mode: ${a.generationMode}. ${K(a)} ${O(!!(a.trademarkImageFileIds?.length||a.additionalImageFileIds?.length))} ${"same_colorways"===a.generationMode?"All concepts must stay in the same product family and mainly vary color/material expression.":"Concepts may vary upper design direction, but they must stay in the same product family and market positioning."} ${"鞋子"===a.category?"For shoes, all concepts must remain side-view product concepts and leave room for outsole matching from uploaded or catalog sole candidates.":"For non-shoes, keep concepts focused on a single product hero image."} Return each item with keys: title, design_direction, key_colors, material_focus, upper_structure, silhouette_notes, sole_match_cues.

SYNTHESIZED PRODUCT REFERENCE SUMMARY:
${c||a.productInfo||a.productName}`,signal:e}),h=w(g);if(!h?.length)return f;return Array.from({length:d},(a,b)=>{let c=h[b]||{};return{index:b,title:x(c.title,f[b].title),designDirection:x(c.design_direction,f[b].designDirection),keyColors:x(c.key_colors,f[b].keyColors),materialFocus:x(c.material_focus,f[b].materialFocus),upperStructure:x(c.upper_structure,f[b].upperStructure),silhouetteNotes:x(c.silhouette_notes,f[b].silhouetteNotes),soleMatchCues:x(c.sole_match_cues,f[b].soleMatchCues)}})}catch(a){if(q(a)||e?.aborted)throw new p;return f}}async function E(a,b,c,d,e){let f=Array.from({length:d},(b,c)=>({index:c,title:"same_colorways"===a.generationMode?`Colorway ${c+1}`:`Design ${c+1}`,designDirection:"same_colorways"===a.generationMode?"Keep the exact same product family and only explore controlled color/material changes.":"Stay tightly aligned to the uploaded reference family and only make controlled design refinements.",keyColors:a.additionalRequirements||a.productInfo||"Stay close to the uploaded reference color logic.",materialFocus:a.productSpecs||"Keep materials and finish aligned with the uploaded product family.",upperStructure:"鞋子"===a.category?"Preserve the same side-view shoe family, panel logic, and wearable proportion.":"Preserve the same product family, proportion, and structural logic.",silhouetteNotes:"鞋子"===a.category?"Only side-view shoe presentation, square composition, no family redesign.":"Single product hero view, square composition, no family redesign.",soleMatchCues:"鞋子"===a.category?"Keep outsole family locked. Only color coordination or subtle upper refinements may change.":""}));if("same_colorways"===a.generationMode)return f;try{let g=await b.generateText({system:"You are a locked product-family planner. Create tightly controlled variation plans that stay very close to the uploaded references. Do not redesign the family. Keep silhouette, panel logic, logo zone, and overall proportion anchored to the uploaded references.",user:`Generate exactly ${d} variation plans in strict JSON array format only. Language: ${a.language}. Category: ${a.category}. Age group: ${a.ageGroup}. Generation mode: ${a.generationMode}. ${K(a)} Allow only controlled refinements within the same product family. Do not create a fresh design direction. ${"鞋子"===a.category?"For shoes, keep the same upper family and leave outsole matching locked to uploaded or selected sole references.":"For non-shoes, keep the same family silhouette, structure, and logo zone."} Return each item with keys: title, design_direction, key_colors, material_focus, upper_structure, silhouette_notes, sole_match_cues.

LOCKED PRODUCT FAMILY SUMMARY:
${c||a.productInfo||a.productName}`,signal:e}),h=w(g);if(!h?.length)return f;return Array.from({length:d},(a,b)=>{let c=h[b]||{};return{index:b,title:x(c.title,f[b].title),designDirection:x(c.design_direction,f[b].designDirection),keyColors:x(c.key_colors,f[b].keyColors),materialFocus:x(c.material_focus,f[b].materialFocus),upperStructure:x(c.upper_structure,f[b].upperStructure),silhouetteNotes:x(c.silhouette_notes,f[b].silhouetteNotes),soleMatchCues:x(c.sole_match_cues,f[b].soleMatchCues)}})}catch(a){if(q(a)||e?.aborted)throw new p;return f}}async function F(a,b,c,d="uploaded product photos",e){if(!c.length)return"";let f=[];for(let g=0;g<c.length;g+=1){let h=c[g];try{let i=await b.generateText({system:"You are a product visual analyst. Extract concrete visual facts only, no guesses. Describe product category, shape, color, material, distinctive marks/logo, packaging, and structural cues.",user:`Analyze ${d}${c.length>1?` batch ${g+1}`:""} and return a concise JSON with keys: product_type, colors, material, shape, distinguishing_features, packaging, cautions. Language: ${a.language}.`,images:h,signal:e});i.trim()&&f.push(i)}catch(a){if(q(a)||e?.aborted)throw new p}}return C(b,d,f,a.language,e)}async function G(a,b,c,d){if("鞋子"!==a.category||!c?.length)return"";try{return await b.generateText({system:"You are a footwear sole analyst. Extract concrete outsole facts only, no guesses. When two images are provided, treat image 1 as the outsole bottom view and image 2 as the outsole side profile of the same exact sole. Describe sole outline, tread pattern, sidewall profile, heel/toe drop, thickness, structural proportions, and note which uploaded sole is the strongest match when multiple sole candidates are provided.",user:`Analyze uploaded shoe sole photos and return a concise JSON with keys: outsole_bottom_view, side_profile_view, sole_outline, tread_pattern, sidewall_profile, thickness, heel_toe_ratio, structure, selected_sole_index, cautions. Language: ${a.language}.`,images:c,signal:d})}catch(a){if(q(a)||d?.aborted)throw new p;return""}}async function H(a,b,c,d,e,f){let g=e.filter(a=>a.summary.trim());if("鞋子"!==a.category||!g.length)return -1;if(1===g.length)return g[0].sourceIndex;try{let e=await b.generateText({system:"You are a footwear sole selector. Choose exactly one sole candidate that best fits the current shoe concept while staying production-realistic. Return JSON only with keys selected_index and reason.",user:`Pick the best sole candidate for this shoe concept. Respect outsole manufacturability and product fit. Language: ${a.language}.

Synthesized reference direction:
${c||a.productInfo||a.productName}

Current concept #${d.index+1} - ${d.title}
Design direction: ${d.designDirection}
Key colors: ${d.keyColors}
Material focus: ${d.materialFocus}
Upper structure: ${d.upperStructure}
Silhouette notes: ${d.silhouetteNotes}
Sole match cues: ${d.soleMatchCues}

`+g.map((a,b)=>`Candidate ${b+1} (source ${a.sourceIndex+1}):
${a.summary}`).join("\n\n"),signal:f}),h=v(e,g.length);return g[h]?.sourceIndex??g[0].sourceIndex}catch(a){if(q(a)||f?.aborted)throw new p;return g[0].sourceIndex}}async function I(a,b,c,d,e,f){let g=e.filter(a=>a.summary.trim());if("鞋子"!==a.category||!g.length)return d.map(()=>-1);if(1===g.length)return d.map(()=>g[0].sourceIndex);try{let e=await b.generateText({system:"You are a footwear sole planner. Assign the best uploaded sole candidate to each variation while keeping product-family consistency and manufacturability. Return strict JSON array only with objects containing concept_index and selected_index.",user:`Assign one uploaded sole candidate to each shoe variation. Language: ${a.language}.

If several sole candidates are viable, distribute usage across the uploaded candidates instead of defaulting every variation to candidate 1.

Locked product-family summary:
${c||a.productInfo||a.productName}

Variations:
${d.map(a=>`Concept ${a.index+1}: ${a.title}
Direction: ${a.designDirection}
Key colors: ${a.keyColors}
Material focus: ${a.materialFocus}
Upper structure: ${a.upperStructure}
Silhouette notes: ${a.silhouetteNotes}
Sole match cues: ${a.soleMatchCues}`).join("\n\n")}

Sole candidates:
${g.map((a,b)=>`Candidate ${b+1} (source ${a.sourceIndex+1}):
${a.summary}`).join("\n\n")}`,signal:f}),i=w(e);if(!i?.length)return z(g,d.length);var h=d.map((a,b)=>{let c=i.find(b=>Number(b.concept_index??b.conceptIndex??b.index)===a.index+1)||i[b]||{},e=Number(c.selected_index??c.selectedIndex??c.index);return Number.isFinite(e)?g[Math.max(0,Math.min(g.length-1,Math.round(e)-1))]?.sourceIndex??g[0].sourceIndex:y(g,b,d.length)});if(g.length<=1||h.length<=1)return h;let j=new Set(g.map(a=>a.sourceIndex));return new Set(h.filter(a=>j.has(a))).size>1?h:z(g,h.length)}catch(a){if(q(a)||f?.aborted)throw new p;return z(g,d.length)}}async function J(a,b,c,d,e,f){let g=e.filter(a=>a.summary.trim());if(!g.length)return -1;if(1===g.length)return g[0].sourceIndex;try{let e=await b.generateText({system:"You are a product reference selector. Choose exactly one uploaded reference image that best represents the current concept while staying faithful to the full multi-reference synthesis. Return JSON only with keys selected_index and reason.",user:`Pick the best representative uploaded reference for this concept. Language: ${a.language}.

Synthesized reference direction:
${c||a.productInfo||a.productName}

Current concept #${d.index+1} - ${d.title}
Design direction: ${d.designDirection}
Key colors: ${d.keyColors}
Material focus: ${d.materialFocus}
Upper structure: ${d.upperStructure}
Silhouette notes: ${d.silhouetteNotes}

`+g.map((a,b)=>`Candidate ${b+1} (source ${a.sourceIndex+1}):
${a.summary}`).join("\n\n"),signal:f}),h=v(e,g.length);return g[h]?.sourceIndex??g[0].sourceIndex}catch(a){if(q(a)||f?.aborted)throw new p;return g[0].sourceIndex}}function K(a){let b="鞋子"===a.category?"shoe":"服装"===a.category?"apparel":"箱包"===a.category?"bag":"product";switch(a.ageGroup){case"男童":return`TOP PRIORITY AGE GROUP LOCK: generate boys' kid ${b} only. Keep child-sized proportions, youthful styling, lighter visual mass, and no adult male or adult female maturity cues.`;case"女童":return`TOP PRIORITY AGE GROUP LOCK: generate girls' kid ${b} only. Keep child-sized proportions, youthful styling, lighter visual mass, and no adult female or adult male maturity cues.`;case"成年男":return`TOP PRIORITY AGE GROUP LOCK: generate adult men's ${b} only. Keep adult masculine proportions and mature styling. Do not produce childlike or juvenile cues.`;case"成年女":return`TOP PRIORITY AGE GROUP LOCK: generate adult women's ${b} only. Keep adult feminine proportions and mature styling. Do not produce childlike or juvenile cues.`;default:return""}}function L(a){return a.derivedOutputsOnly?"鞋子"===a.category?"DERIVED OUTPUT SOURCE LOCK: the selected source image is the exact product that must be preserved. Do not redesign the shoe, do not generate a new concept, and do not swap to a different upper or outsole family. For shoes, keep the same upper silhouette, outsole geometry, panel breakup, logo placement, proportions, and product identity as the selected source image. Only change camera angle, crop, panel layout, and presentation needed for the nine-grid or prompt description.":"DERIVED OUTPUT SOURCE LOCK: the selected source image is the exact product that must be preserved. Do not redesign the product, do not create a new concept, and do not reinterpret the product family. Keep the same silhouette, structure, color-block logic, material zones, and logo placement as the selected source image. Only change camera angle, crop, panel layout, and presentation needed for the nine-grid or prompt description.":""}function M(a){return!B(a)||a.derivedOutputsOnly?"":"鞋子"===a.category?"LOCKED FAMILY MODE: stay very close to the uploaded reference family. Do not redesign the shoe family. Preserve upper silhouette, panel breakup, proportions, logo zone, and overall market identity. Allow only controlled color/material updates and subtle refinements that still read as the same family.":"LOCKED FAMILY MODE: stay very close to the uploaded reference family. Do not redesign the product family. Preserve silhouette, structure, proportions, logo zone, and overall identity. Allow only controlled color/material updates and subtle refinements that still read as the same family."}function N(a,b){return b?["TOP PRIORITY CLIENT TRADEMARK LOCK: use only the uploaded client trademark/logo exactly as provided. Do not invent, replace, redraw, restyle, simplify, warp, stretch, curve, crop into a new shape, or substitute any letters or symbols. If the exact uploaded mark cannot fit cleanly at production-appropriate size, leave a clean reserved logo area or omit the logo for that view. Do not create placeholder branding, fake letters, generic symbols, substitute logos, or any approximate brand graphic.","鞋子"===a.category?"Prefer a clean logo area on the lateral side panel, heel tab, tongue label, or strap zone depending on the product.":"服装"===a.category?"Prefer a clean logo area on chest, sleeve, hem, or back-neck zones depending on the garment.":"Prefer a clean logo area on the front panel, flap, strap tag, or side patch depending on the bag structure."].join(" "):""}function O(a){let b="When removing or replacing a reference logo, do not erase it with holes, scars, blobs, copied texture patches, stickers, rough cover-ups, or damaged-looking artifacts; the original logo area must become a clean intentional product surface with seamless material, natural panel stitching, an emboss-ready blank zone, woven-label area, or matching trim.";return a?["GLOBAL BRAND SAFETY: if branding appears, use only the uploaded client trademark asset exactly as provided. Never introduce any third-party brand name, logo, monogram, slogan, or recognizable external trademark.",b].join(" "):["GLOBAL BRAND SAFETY: never generate any real-world third-party brand, competitor logo, recognizable monogram, or external trademark text. If a brand area is needed, leave it blank or use only neutral abstract non-readable geometry with no real letters or known symbols.",b].join(" ")}function P(a,b){return"鞋子"!==a.category?"":["SHOE STYLE PRIMARY: the uploaded product reference is the primary visual source for upper silhouette, panel breakup, materials, proportions, and overall style.",b?"The matched sole reference is a locked outsole component only; use it for outsole structure without letting it dominate the shoe style.":"When a shoe source image is provided, preserve the source shoe family and side-view product identity.","Outsole color may coordinate with the upper, but outsole geometry, tread, texture, sidewall, and structural details must not change when a matched sole is provided."].filter(Boolean).join(" ")}function Q(a,b,c){if(!b)return;if("edit"===a.imageMode||"same_colorways"===a.generationMode||a.strictConsistency)return b;let d=A(a.referenceImageWeight??70);if("extreme_lock"===d||"high_lock"===d)return b}async function R(a,b,c,d){if(!c?.length)return"";try{return await b.generateText({system:"You are a brand asset analyst. Extract only concrete facts from the uploaded trademark/logo images. The uploaded asset is the exact client trademark that must be preserved. Describe exact text content, exact symbol structure, dominant colors, line style, proportions, placement cues, and any cautions against distortion. Do not invent brand meaning or substitute letters or symbols.",user:`Analyze uploaded trademark assets and return a concise JSON with keys: exact_text, logo_form, symbol_structure, colors, line_style, proportions, placement_cues, distortion_cautions. Language: ${a.language}.`,images:c,signal:d})}catch(a){if(q(a)||d?.aborted)throw new p;return""}}function S(a,b){if(!b)return"create";if(a.strictConsistency||"edit"===a.imageMode||"same_colorways"===a.generationMode)return"edit";let c=A(a.referenceImageWeight??70);return"extreme_lock"===c||"high_lock"===c?"edit":"create"}function T(a){let b=A(a.referenceImageWeight??70);return a.strictConsistency||"extreme_lock"===b?"鞋子"===a.category?"Reference priority: EXTREME LOCK. Keep the uploaded shoe reference family nearly identical in upper silhouette, panel logic, proportions, logo placement, and overall style. Sole references remain separate outsole-only constraints.":"Reference priority: EXTREME LOCK. Keep the uploaded product nearly identical in shape, logo, material, color, and overall family.":"high_lock"===b?"鞋子"===a.category?"Reference priority: VERY HIGH. Stay clearly within the uploaded shoe family and preserve its upper silhouette, material zones, panel logic, and product identity, while allowing a clearly new design direction.":"Reference priority: VERY HIGH. Stay clearly within the uploaded product family and preserve its silhouette, structure, material logic, and logo zone, while allowing a clearly new design direction.":"stable_innovation"===b?"鞋子"===a.category?"Reference priority: HIGH NEW-STYLE. Create a genuinely new shoe direction synthesized from all uploaded references. Keep age group, category, outsole locks, and broad family cues, but do not reduce the result to a light local edit of one reference.":"Reference priority: HIGH NEW-STYLE. Create a genuinely new product direction synthesized from all uploaded references. Keep age group, category, and broad family cues, but do not reduce the result to a light local edit of one reference.":"moderate_innovation"===b?"鞋子"===a.category?"Reference priority: CLEAR NEW-STYLE. Build a noticeably new shoe from the multi-reference synthesis. Keep age group, category, and outsole constraints, but do not mimic one uploaded shoe or just tweak local details.":"Reference priority: CLEAR NEW-STYLE. Build a noticeably new product from the multi-reference synthesis. Keep age group and category aligned, but do not mimic one uploaded reference or just tweak local details.":"鞋子"===a.category?"Reference priority: FREE EXPLORATION. Keep age group, category, and outsole locks. References provide only broad inspiration, and the result must still avoid third-party brands or copied market products.":"Reference priority: FREE EXPLORATION. Keep age group and category locked. References provide only broad inspiration, and the result must still avoid third-party brands or copied market products."}function U(){return"Required output component: a compact top-right Pantone legend is mandatory. Use 3-5 clean vertical color swatches with Pantone code text. If space is tight, slightly reduce product scale to reserve a clean top-right margin. Do not omit the legend. The legend must stay outside the product silhouette and must not cover the product."}function V(a,b,c="running"){let d=new Date().toISOString();m.db.updateTask(a,a=>({...a,status:c,result:b,updatedAt:d,completedAt:"stopped"===c?d:a.completedAt,error:"stopped"===c?void 0:a.error}))}function W(a,b,c){let d=m.db.findTaskById(a);if(!d)throw Error("Task not found");if(c?.aborted||d.stopRequested)throw V(a,b,"stopped"),new p;V(a,b,"running")}async function X(a,b,c,d,e,f){let g=(0,i.FB)("prompt.video.v1");return b.generateText({system:`You are prompt.video.v1.
${g}
${c}`,user:`Generate video prompt script text only in ${a.language}. Do not generate actual video.
${"model"===e?"Create a 10-second model-wearing video prompt. Start with a wider full-body or half-body styling shot, then move the camera closer to the product details. The model must wear or carry the product naturally.\n":"Create a 10-second product-only video prompt. Start with a wider establishing shot that shows the overall product clearly, then move the camera closer to highlight product details, materials, structure, and color accents. Do not use a model.\n"}${L(a)}
${d}`,signal:f})}async function Y(a,b,c,d,e,f,g,h,k,m,n,q){let s=(0,i.FB)("image.hero.v1"),t=k.length?k:[{concept:{index:0,title:"Design 1",designDirection:b.productInfo||b.productName,keyColors:b.additionalRequirements||"",materialFocus:b.productSpecs||"",upperStructure:"鞋子"===b.category?"Side-view shoe.":"Single product hero view.",silhouetteNotes:"鞋子"===b.category?"Side view only.":"Front or side view only.",soleMatchCues:""},baseImage:h}],u=[],v=[];async function w(i){if(q?.aborted)throw new p;aa(a,`generating_detail_image_${i+1}`);let k=t[i],v=k.matchedSole?`MATCHED SOLE CANDIDATE: ${k.matchedSole.sourceIndex+1}. Matched sole facts: ${k.matchedSole.summary} SOLE REGION LOCK: apply this matched sole only to the outsole region. Do not let the sole reference override the uploaded product reference's upper style, silhouette, panel language, or overall design family. Keep outsole shape, tread pattern, groove layout, lugs, pods, cut lines, edge profile, sidewall rhythm, thickness, heel/toe ratio, arch curve, molded breaks, surface texture, and structural material logic unchanged. Do not smooth, simplify, sharpen, redraw, add, remove, relocate, merge, split, or restyle any sole detail. Only sole color may be adjusted to harmonize with the upper. The upper and overall style must continue to follow the uploaded product reference family.`:"",w=!k.matchedProductReference||m<=1?"":`STYLE REFERENCE ANCHOR: use uploaded product reference ${k.matchedProductReference.sourceIndex+1} as the representative visual base for this output. Also follow the shared design synthesis from all ${m} uploaded product references. Do not default every output to reference 1, and do not let any sole reference override the selected product reference's upper style.`,x=await d.generateText({system:`You are image.hero.v1.
${s}
${e}
${(0,j.rZ)("detail")}`,user:`Create one image-generation prompt in ${b.language} for a single product image.
${K(b)}
${U()}
${P(b,!!k.matchedSole?.image)}
${T(b)}
${w?`${w}
`:""}${v?`${v}
`:""}${g?`${g}
`:""}${M(b)}
${"same_colorways"===b.generationMode?"This image must stay in the same product family and mainly vary color/material balance.\n":B(b)?"This image must stay tightly aligned to the uploaded reference family and only make controlled refinements.\n":"This image must express a fresh design direction while preserving the same product family and market positioning.\n"}Each prompt must preserve the same product identity synthesized from all uploaded references, not just one reference image.
${"鞋子"===b.category?"Only generate one clean side-view shoe image.\n":"Only generate one clean front view or side view product image.\n"}Do not ask for close-up detail shots, multi-product layouts, technical callout boards, or e-commerce style detail breakdowns.
Use a square 1:1 composition and let the product occupy most of the frame with minimal empty space.
Category: ${b.category}; Age group: ${b.ageGroup}; Generation mode: ${b.generationMode}.
Current concept #${k.concept.index+1}: ${k.concept.title}
Design direction: ${k.concept.designDirection}
Key colors: ${k.concept.keyColors}
Material focus: ${k.concept.materialFocus}
Upper structure: ${k.concept.upperStructure}
Silhouette notes: ${k.concept.silhouetteNotes}
${k.concept.soleMatchCues?`Sole match cues: ${k.concept.soleMatchCues}
`:""}${b.strictConsistency?"鞋子"===b.category?"STRICT CONSISTENCY ON: preserve product silhouette, material, pattern/logo position, and outsole geometry in this panel; avoid redesigning the product family.\n":"STRICT CONSISTENCY ON: preserve product silhouette, material, pattern/logo position, and core proportion in this panel; avoid redesigning the product family.\n":""}Return prompt text only.

${f}`,signal:q}),y=(0,o.mB)(r(b)),z="鞋子"===b.category&&k.matchedSole?.image?"edit":S(b,!!(k.baseImage??h)),A=await (0,o.Oo)(d,{prompt:x,count:1,size:y,mode:z,baseImage:k.baseImage??h,referenceImages:k.matchedSole?.image?[k.matchedSole.image]:void 0,signal:q}),C=await (0,l.AR)(A[0].bytes,A[0].mimeType,`detail-${i+1}.png`,c);u[i]={fileId:C.id,url:`/api/files/${C.id}`,prompt:x},n.detailImages=u.filter(Boolean),W(a,n,q)}for(let a=0;a<t.length;a+=2){if(q?.aborted)throw new p;let b=Array.from({length:Math.min(2,t.length-a)},(b,c)=>a+c);(await Promise.allSettled(b.map(a=>w(a)))).forEach((a,c)=>{if("rejected"===a.status){let d=b[c],e=t[d]?.concept.title||`detail image ${d+1}`;v.push({index:d+1,prompt:e,error:a.reason instanceof Error?a.reason.message:"detail image generation failed"})}})}let x=u.filter(a=>!!a);if(!x.length&&v.length)throw Error(v[0].error);return{prompts:x.map(a=>a.prompt),images:x,detailImageErrors:v.length?v:void 0}}async function Z(a,b,c,d,e,f,g,h){let j=(0,i.FB)("image.hero.v1"),k=await c.generateText({system:`You are image.hero.v1.
${j}
${d}`,user:`Create one image-generation prompt in ${a.language} for ${a.platform}.
Generate a single 3x3 nine-grid composite product consistency board.
${"鞋子"===a.category?"Each of 9 panels should present the SAME shoe product with a mix of key views and detail callouts: lateral side, medial side, top, heel, outsole, toe, material detail, logo/detail placement, and color/material close-up.\n":"Each of 9 panels should present the SAME product with a mix of key views and detail callouts: front, side, back, top or opening, hardware/closure detail, material texture detail, logo detail, structure detail, and one clean hero angle.\n"}Arrange all 9 panels cleanly within one square 1:1 board.
${"鞋子"===a.category?"Panel suggestions: lateral side, medial side, top, heel, outsole, toe, tongue or lace detail, logo detail, material/color detail.\n":"Panel suggestions: front, side, back, top/opening, 45-degree hero, logo detail, hardware detail, material texture detail, construction detail.\n"}No unrelated objects. Keep product identity, color blocks, material, proportions, and logo placement consistent across all panels.
Category: ${a.category}; Age group: ${a.ageGroup}; Generation mode: ${a.generationMode}.
${"鞋子"===a.category?"For shoes, keep all major product panels faithful to the same outsole family and upper design.\n":"Keep all panels faithful to the same selected product.\n"}${L(a)}
${M(a)}
${f?`${f}
`:""}Use a square 1:1 composition and let the grid fill most of the frame with minimal empty space.
${U()}
${T(a)}
${a.strictConsistency||a.derivedOutputsOnly?"STRICT CONSISTENCY ON: do not redesign the product; only vary camera angle, crop, panel layout, and detail callout framing.\n":""}Output must be one single composed image (not 9 separate files).
${e}
Return prompt text only.`,signal:h}),m=S(a,!!g),n=(0,o.mB)(r(a)),p=await (0,o.Oo)(c,{prompt:k,count:1,size:n,mode:m,baseImage:g,signal:h}),q=await (0,l.AR)(p[0].bytes,p[0].mimeType,"nine-grid.png",b);return{fileId:q.id,url:`/api/files/${q.id}`,prompt:k}}async function $(a,b,c,d,e,f,g,h){let j=(0,i.FB)("image.hero.v1"),k=await c.generateText({system:`You are image.hero.v1.
${j}
${d}`,user:`Create one image-generation prompt in ${a.language} for ${a.platform}.
SOURCE REPLICA BOARD MODE: build a nine-grid board from the exact selected source image only.
Do not create a new design. Do not reinterpret the product family. Do not restyle the upper or outsole.
Generate a single 3x3 nine-grid composite board showing the SAME exact product in nine coordinated panels.
${"鞋子"===a.category?"For shoes, use panels such as lateral side, medial side, top, heel, outsole, toe, tongue or lace detail, logo detail, and material/color detail. Every panel must remain faithful to the same exact shoe from the selected source image.\n":"Use panels such as front, side, back, top/opening, 45-degree hero, logo detail, hardware detail, material texture detail, and construction detail. Every panel must remain faithful to the same exact selected product.\n"}Only vary camera angle, crop, framing, and panel composition.
${P(a,"鞋子"===a.category&&!!f)}
${N(a,g)}
${L(a)}
${T(a)}
Use a square 1:1 composition and let the grid fill most of the frame with minimal empty space.
Output must be one single composed image (not 9 separate files).
${e}
Return prompt text only.`,signal:h}),m=(0,o.mB)(r(a)),n=f?"edit":S(a,!!f),p=await (0,o.Oo)(c,{prompt:k,count:1,size:m,mode:n,baseImage:f,signal:h}),q=await (0,l.AR)(p[0].bytes,p[0].mimeType,"nine-grid.png",b);return{fileId:q.id,url:`/api/files/${q.id}`,prompt:k}}function _(a,b){return a.includes(b)}function aa(a,b){m.db.updateTask(a,a=>({...a,phase:b,updatedAt:new Date().toISOString()}))}async function ab(a,b,c){let d=m.db.findTaskById(a);if(!d)throw Error("Task not found");if(c?.aborted||d.stopRequested)return void m.db.updateTask(a,a=>({...a,status:"stopped",phase:"stopped",updatedAt:new Date().toISOString(),completedAt:new Date().toISOString()}));m.db.updateTask(a,a=>({...a,status:"running",phase:"building_context",updatedAt:new Date().toISOString()}));let e=(0,n.V)((0,k.b)(b),a),f={};try{var g;let b=d.request,h=d.requestedBy,i=m.db.listFilesByIds(b.productImageFileIds),k=b.derivedOutputsOnly?[]:m.db.listFilesByIds(b.shoeSoleImageFileIds||[]),l=m.db.listFilesByIds(b.trademarkImageFileIds||b.additionalImageFileIds||[]),n=(b.derivedOutputsOnly?i:m.db.listFilesByIds([...b.productImageFileIds,...b.shoeSoleImageFileIds||[],...b.trademarkImageFileIds||[],...b.additionalImageFileIds||[]])).map(a=>a.fileName),o=(0,j.aI)(b.country,b.platform,b.language,b.category,b.ageGroup),p=function(a,b=4,c=8){let d=t(a,c),e=[];for(let a=0;a<d.length;a+=b){let c=d.slice(a,a+b);c.length&&e.push(c)}return e}(i,4,8),q=t(i,8),r=t(l,4),v=q[0];aa(a,"analyzing_uploaded_images");let w=await F(b,e,p,"uploaded product references",c),x=B(b),z=b.derivedOutputsOnly?[]:q.map((a,b)=>({sourceIndex:b,summary:`Uploaded product reference ${b+1}`,image:a}));if(!b.derivedOutputsOnly&&!x)for(let a=0;a<q.length;a+=1){let d=q[a],f=await F(b,e,[[d]],`uploaded product reference ${a+1}`,c);f.trim()&&(z[a]={sourceIndex:a,summary:f,image:d})}aa(a,"analyzing_sole_images");let A=[];if(!b.derivedOutputsOnly)for(let a=0;a<k.length;a+=1){let d=k[a],f=await u(d),g=await G(b,e,f.analysisImages,c);g.trim()&&A.push({sourceIndex:a,summary:g,image:f.generationBaseImage})}let C=[];if(!b.derivedOutputsOnly){let a=Math.max(1,Math.min(12,b.detailImageCount||6)),d=x?await E(b,e,w,a,c):await D(b,e,w,a,c),f=x?await I(b,e,w,d,A,c):[];for(let a of d){let g=x?f[a.index]??-1:await H(b,e,w,a,A,c),h=g>=0?A.find(a=>a.sourceIndex===g):void 0,i=x?y(z,a.index,d.length):await J(b,e,w,a,z,c),j=i>=0?z.find(a=>a.sourceIndex===i):void 0,k=j?.image||v;C.push({concept:a,matchedSole:h,matchedProductReference:j,baseImage:Q(b,k,void 0)})}}let K=A.map(a=>`Candidate ${a.sourceIndex+1}: ${a.summary}`).join("\n\n");aa(a,"analyzing_brand_assets");let L=!!r.length,M=await R(b,e,r,c),P=[O(L),L?`${g=b.category,"鞋子"===g?"Brand placement for shoes: prioritize lateral side panel or heel tab, then tongue label or lace/strap zone. Align the mark with quarter-panel seams, foxing line, heel counter, or tongue axis; avoid covering flex lines, vent holes, visible stitch logic, or outsole rhythm.":"服装"===g?"Brand placement for apparel: prioritize chest, sleeve/upper arm, hem/side seam, then back-neck label areas. Integrate the mark with shoulder lines, seam direction, and neckline balance; avoid oversized placement that distorts drape or silhouette.":"Brand placement for bags: prioritize front panel/flap, then side patch/corner tab, then strap/handle tag. Keep the mark integrated with body proportion, panel junctions, edge-paint rhythm, and hardware layout; avoid oversized placement that breaks structure."} ${N(b,!0)}`:""].filter(Boolean).join(" "),S="鞋子"===b.category&&A.length?"SOLE MATCHING MODE: first synthesize design directions from all product references, then match each output image to the most suitable uploaded or catalog sole candidate. Each output image may use a different sole candidate. The outsole shape, tread, thickness, ratio, and structural logic must remain faithful to the matched sole used for that image.":"",T=C[0]?.baseImage??Q(b,v,void 0);aa(a,"building_design_context");let U=b.derivedOutputsOnly?[s(b,n),"DERIVED OUTPUT MODE: use only the currently selected single source image as the exact product master.","Do not reinterpret prior design concepts, prior rounds, uploaded sole sets, or broader brand-asset planning into a new design.",w?`Exact selected source image facts:
${w}`:"","鞋子"===b.category?"For shoes, preserve the exact upper silhouette, outsole shape, tread pattern, sidewall rhythm, logo placement, and proportion from the selected source image.":"Preserve the exact silhouette, structure, material zoning, color blocking, and logo placement from the selected source image."].filter(Boolean).join("\n\n"):[s(b,n),w?`Visual grounding from uploaded images:
${w}`:"",K?`Sole grounding from uploaded and selected sole images:
${K}`:"",S?`Sole matching guidance:
${S}`:"",M?`Exact client trademark grounding:
${M}`:""].filter(Boolean).join("\n\n"),V=b.derivedOutputsOnly?U:[s(b,n),w?`Visual grounding from uploaded images:
${w}`:"",S?`Sole matching guidance:
${S}`:"",M?`Exact client trademark grounding:
${M}`:""].filter(Boolean).join("\n\n");if(!b.derivedOutputsOnly){aa(a,"generating_detail_prompts");let d=await Y(a,b,h,e,o,V,P,T,C,z.length,f,c);f.detailImages=d.images,d.detailImageErrors?.length&&(f.detailImageErrors=d.detailImageErrors),W(a,f)}_(b.selectedOutputs,"PRODUCT_VIDEO_PROMPT")&&(aa(a,"generating_product_video_prompt"),f.productVideoPrompt=await X(b,e,o,U,"product",c),f.videoPrompt=f.productVideoPrompt,W(a,f,c)),_(b.selectedOutputs,"MODEL_VIDEO_PROMPT")&&(aa(a,"generating_model_video_prompt"),f.modelVideoPrompt=await X(b,e,o,U,"model",c),W(a,f,c)),_(b.selectedOutputs,"NINE_GRID")&&(aa(a,"generating_nine_grid"),f.nineGridImage=b.derivedOutputsOnly?await $(b,h,e,o,U,T,L,c):await Z(b,h,e,o,U,P,T,c),W(a,f,c)),m.db.updateTask(a,a=>({...a,status:"completed",phase:"completed",result:f,updatedAt:new Date().toISOString(),completedAt:new Date().toISOString()}))}catch(d){if(d instanceof p||q(d)||c?.aborted||m.db.findTaskById(a)?.stopRequested){m.db.findTaskById(a)&&(V(a,f,"stopped"),m.db.updateTask(a,a=>({...a,status:"stopped",phase:"stopped",result:f,updatedAt:new Date().toISOString(),completedAt:new Date().toISOString()})));return}let b=d instanceof Error?d.message:"Unknown generation error";m.db.updateTask(a,a=>({...a,status:"failed",phase:"failed",error:b,updatedAt:new Date().toISOString()}))}}function ac(a,b){let c=!1!==b.useSharedImageCredentials,d=b.textBaseUrl||("gemini"===b.textProvider?h.U.gemini.defaultBaseUrl:"deepseek"===b.textProvider?h.U.deepseek.defaultBaseUrl:"mimo"===b.textProvider?h.U.mimo.defaultBaseUrl:"agnes"===b.textProvider?h.U.agnes.defaultBaseUrl:h.U.openai.defaultBaseUrl),e=b.textApiKey,f="gemini"===b.imageProvider||"agnes"===b.imageProvider?b.imageProvider:"openai",g=c?d:b.imageBaseUrl||("gemini"===f?h.U.gemini.defaultBaseUrl:"agnes"===f?h.U.agnes.defaultBaseUrl:h.U.openai.defaultBaseUrl),i=c?e:b.imageApiKey||e;return{textProvider:b.textProvider,imageProvider:f,textBaseUrl:d,textApiKey:e,textModel:b.textModel||("gemini"===b.textProvider?h.U.gemini.defaultTextModel:"deepseek"===b.textProvider?h.U.deepseek.defaultTextModel:"mimo"===b.textProvider?h.U.mimo.defaultTextModel:"agnes"===b.textProvider?h.U.agnes.defaultTextModel:h.U.openai.defaultTextModel),imageBaseUrl:g,imageApiKey:i,imageModel:b.imageModel||("gemini"===f?h.U.gemini.defaultImageModel:"agnes"===f?h.U.agnes.defaultImageModel:h.U.openai.defaultImageModel),useSharedImageCredentials:c}}}};