(function(){"use strict";try{if(typeof document<"u"){var e=document.createElement("style");e.appendChild(document.createTextNode('@import"https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap";:root{--stone-50: #fafaf9;--stone-100: #f5f5f4;--stone-200: #e7e5e4;--stone-300: #d6d3d1;--stone-400: #a8a29e;--stone-500: #78716c;--stone-600: #57534e;--stone-700: #44403c;--stone-800: #292524;--stone-900: #1c1917;--slate-50: #f8fafc;--slate-100: #f1f5f9;--slate-200: #e2e8f0;--slate-300: #cbd5e1;--slate-400: #94a3b8;--slate-500: #64748b;--slate-600: #475569;--slate-700: #334155;--slate-800: #1e293b;--slate-900: #0f172a;--accent-blue: #3b82f6;--accent-blue-hover: #2563eb;--accent-green: #10b981;--accent-amber: #f59e0b;--accent-red: #ef4444;--primary: var(--stone-800);--primary-hover: var(--stone-900);--secondary: var(--stone-100);--secondary-hover: var(--stone-200);--muted: var(--stone-500);--muted-light: var(--stone-400);--border: var(--stone-200);--border-light: var(--stone-100);--background: #ffffff;--surface: var(--stone-50);--surface-elevated: #ffffff;--text-xs: .75rem;--text-sm: .875rem;--text-base: 1rem;--text-lg: 1.125rem;--text-xl: 1.25rem;--text-2xl: 1.5rem;--text-3xl: 1.875rem;--space-1: .25rem;--space-2: .5rem;--space-3: .75rem;--space-4: 1rem;--space-5: 1.25rem;--space-6: 1.5rem;--space-8: 2rem;--space-10: 2.5rem;--space-12: 3rem;--space-16: 4rem;--radius-sm: .25rem;--radius: .5rem;--radius-md: .75rem;--radius-lg: 1rem;--radius-xl: 1.5rem;--shadow-sm: 0 1px 2px 0 rgb(0 0 0 / .05);--shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--shadow-md: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--shadow-lg: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--shadow-xl: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--transition: all .15s cubic-bezier(.4, 0, .2, 1);--transition-fast: all .1s cubic-bezier(.4, 0, .2, 1)}.blockart-container{font-family:-apple-system,BlinkMacSystemFont,Segoe UI,Inter,system-ui,sans-serif;font-feature-settings:"cv11","ss01";font-variation-settings:"opsz" 32;max-width:720px;margin:0 auto;padding:var(--space-6);background:var(--background);border:1px solid var(--border);border-radius:var(--radius-lg);color:var(--stone-800);font-size:var(--text-base);line-height:1.6;min-height:500px;box-shadow:var(--shadow-sm);position:relative}.blockart-content{display:flex;flex-direction:column;gap:var(--space-6)}.blockart-title{margin:0;font-size:var(--text-2xl);font-weight:700;color:var(--stone-900);text-align:center;letter-spacing:-.025em;line-height:1.2}.step-header{text-align:center;margin-bottom:var(--space-8)}.step-header h2{margin:0 0 var(--space-2) 0;font-size:var(--text-xl);font-weight:600;color:var(--stone-900);letter-spacing:-.025em;line-height:1.3}.step-header p{margin:0;font-size:var(--text-base);color:var(--muted);font-weight:400}.form-group{margin-bottom:var(--space-5)}.form-label{display:block;margin-bottom:var(--space-2);font-size:var(--text-sm);font-weight:500;color:var(--stone-700);letter-spacing:.01em}.form-input,.form-textarea{width:100%;padding:var(--space-3) var(--space-4);border:1px solid var(--border);border-radius:var(--radius);font-size:var(--text-base);color:var(--stone-900);background:var(--background);box-sizing:border-box;transition:var(--transition);font-family:inherit;outline:none}.form-input:focus,.form-textarea:focus{border-color:var(--stone-400);box-shadow:0 0 0 3px #78716c1a}.form-textarea{resize:vertical;min-height:100px;font-family:inherit;line-height:1.5}.character-count{margin-top:var(--space-2);text-align:right;font-size:var(--text-xs);color:var(--muted-light);font-weight:500}.btn{display:inline-flex;align-items:center;justify-content:center;gap:var(--space-2);padding:var(--space-3) var(--space-5);border:1px solid var(--border);border-radius:var(--radius);font-size:var(--text-sm);font-weight:500;cursor:pointer;transition:var(--transition);background:var(--background);color:var(--stone-700);text-decoration:none;box-sizing:border-box;font-family:inherit;letter-spacing:.01em;outline:none;position:relative;overflow:hidden}.btn:hover:not(:disabled){background:var(--stone-50);border-color:var(--stone-300);transform:translateY(-1px);box-shadow:var(--shadow-sm)}.btn:active:not(:disabled){transform:translateY(0);box-shadow:none}.btn:disabled{opacity:.5;cursor:not-allowed;pointer-events:none}.btn-primary{background:var(--primary);color:#fff;border-color:var(--primary)}.btn-primary:hover:not(:disabled){background:var(--primary-hover);border-color:var(--primary-hover)}.btn-secondary{background:var(--secondary);color:var(--stone-700);border-color:var(--border)}.btn-secondary:hover:not(:disabled){background:var(--secondary-hover);border-color:var(--stone-300)}.btn-large{padding:var(--space-4) var(--space-6);font-size:var(--text-base);font-weight:600}.btn-small{padding:var(--space-2) var(--space-3);font-size:var(--text-xs)}.choice-options{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:var(--space-4);margin:var(--space-8) 0}.choice-option{padding:var(--space-6);border:1px solid var(--border);border-radius:var(--radius-md);background:var(--background);cursor:pointer;transition:var(--transition);text-align:center;position:relative;overflow:hidden}.choice-option:before{content:"";position:absolute;top:0;left:0;right:0;height:3px;background:transparent;transition:var(--transition)}.choice-option:hover{border-color:var(--stone-300);transform:translateY(-2px);box-shadow:var(--shadow-md)}.choice-option:hover:before{background:var(--stone-400)}.choice-option h3{margin:0 0 var(--space-2) 0;font-size:var(--text-lg);font-weight:600;color:var(--stone-900);letter-spacing:-.01em}.choice-option p{margin:0;font-size:var(--text-sm);color:var(--muted);line-height:1.5}.upload-area{border:2px dashed var(--border);border-radius:var(--radius-lg);padding:var(--space-12);text-align:center;cursor:pointer;transition:var(--transition);background:var(--surface);margin:var(--space-6) 0}.upload-area:hover{border-color:var(--stone-300);background:var(--stone-50)}.upload-area.dragging{border-color:var(--accent-blue);background:#3b82f60d}.upload-content{display:flex;flex-direction:column;align-items:center;gap:var(--space-3)}.upload-icon{color:var(--muted-light)}.upload-content h3{margin:0;font-size:var(--text-lg);font-weight:600;color:var(--stone-900)}.upload-content p{margin:0;font-size:var(--text-base);color:var(--muted)}.upload-requirements{margin-top:var(--space-2)}.upload-requirements small{font-size:var(--text-xs);color:var(--muted-light);font-weight:500}.upload-processing{display:flex;flex-direction:column;align-items:center;gap:var(--space-3)}.image-preview-container{display:flex;flex-direction:column;gap:var(--space-6)}.image-preview-main{position:relative}.image-preview-fullscreen{position:relative;border-radius:var(--radius-lg);overflow:hidden;background:var(--stone-900);box-shadow:var(--shadow-lg)}.fullscreen-image-container{position:relative;width:100%;min-height:400px;display:flex;align-items:center;justify-content:center;background:linear-gradient(45deg,#f0f0f0 25%,transparent 25%),linear-gradient(-45deg,#f0f0f0 25%,transparent 25%),linear-gradient(45deg,transparent 75%,#f0f0f0 75%),linear-gradient(-45deg,transparent 75%,#f0f0f0 75%);background-size:20px 20px;background-position:0 0,0 10px,10px -10px,-10px 0px}.fullscreen-image{max-width:100%;max-height:500px;width:auto;height:auto;object-fit:contain;border-radius:var(--radius)}.overlay-top,.overlay-bottom{position:absolute;left:0;right:0;padding:var(--space-4);background:linear-gradient(to bottom,rgba(0,0,0,.8),transparent);opacity:0;transition:var(--transition);pointer-events:none}.overlay-top{top:0;background:linear-gradient(to bottom,rgba(0,0,0,.8),transparent)}.overlay-bottom{bottom:0;background:linear-gradient(to top,rgba(0,0,0,.8),transparent);pointer-events:auto}.image-preview-fullscreen:hover .overlay-top,.image-preview-fullscreen:hover .overlay-bottom{opacity:1}.overlay-top{display:flex;justify-content:space-between;align-items:center}.app-badge,.status-badge{padding:var(--space-1) var(--space-3);border-radius:var(--radius);font-size:var(--text-xs);font-weight:600;letter-spacing:.05em;text-transform:uppercase}.app-badge{background:#fff3;color:#fff;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.status-badge{background:#10b981e6;color:#fff}.comparison-controls{display:flex;gap:var(--space-2);margin-bottom:var(--space-4)}.comparison-btn{padding:var(--space-2) var(--space-3);border:1px solid rgba(255,255,255,.3);border-radius:var(--radius);background:#ffffff1a;color:#fffc;font-size:var(--text-xs);font-weight:500;cursor:pointer;transition:var(--transition);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.comparison-btn:hover{background:#fff3;color:#fff}.comparison-btn.active{background:#ffffffe6;color:var(--stone-900);border-color:transparent}.primary-actions{display:flex;gap:var(--space-3);align-items:center}.action-btn{display:inline-flex;align-items:center;gap:var(--space-2);padding:var(--space-3) var(--space-4);border:1px solid rgba(255,255,255,.3);border-radius:var(--radius);font-size:var(--text-sm);font-weight:500;cursor:pointer;transition:var(--transition);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);text-decoration:none}.action-btn.primary{background:#3b82f6e6;color:#fff;border-color:transparent}.action-btn.primary:hover{background:#2563ebe6;transform:translateY(-1px)}.action-btn.secondary{background:#ffffff1a;color:#ffffffe6}.action-btn.secondary:hover{background:#fff3;color:#fff}.step-actions{display:flex;justify-content:space-between;align-items:center;margin-top:var(--space-8);padding-top:var(--space-6);border-top:1px solid var(--border-light)}.step-actions .btn:only-child{margin-left:auto}.image-processor{display:flex;flex-direction:column;gap:var(--space-6)}.processor-header{text-align:center}.processor-header h2{margin:0 0 var(--space-2) 0;font-size:1.5rem;font-weight:600;color:var(--color-text-primary)}.processor-header p{margin:0;color:var(--color-text-secondary);font-size:.9rem}.processor-content{position:relative;display:flex;flex-direction:column;align-items:center;gap:var(--space-4)}.image-container{position:relative;max-width:100%;width:100%;max-width:600px;background:var(--color-bg-secondary);border-radius:var(--border-radius-lg);overflow:hidden;border:1px solid var(--color-border)}.processing-image{width:100%;height:auto;display:block}.image-loading{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--space-3);padding:var(--space-8);min-height:200px;color:var(--color-text-secondary)}.image-placeholder{display:flex;align-items:center;justify-content:center;padding:var(--space-8);min-height:200px;color:var(--color-text-secondary);background:var(--color-bg-tertiary)}.image-help{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,#000c);color:#fff;padding:var(--space-4) var(--space-3) var(--space-3);font-size:.8rem;text-align:center}.processing-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#ffffffe6;display:flex;align-items:center;justify-content:center;-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);z-index:10}.processing-indicator{display:flex;flex-direction:column;align-items:center;gap:var(--space-3);text-align:center}.processing-text{font-size:.9rem;color:var(--color-text-secondary);font-weight:500}.streaming-info{margin-top:var(--space-3);text-align:center}.streaming-info small{display:block;font-size:var(--text-xs);color:var(--muted-light);margin-bottom:var(--space-2)}.progress-bar{width:120px;height:4px;background:var(--stone-200);border-radius:2px;overflow:hidden;margin:0 auto}.progress-fill{height:100%;background:var(--stone-600);border-radius:2px;transition:width .3s ease}.streaming-overlay{position:absolute;bottom:0;left:0;right:0;background:linear-gradient(transparent,#000c);border-radius:0 0 var(--radius) var(--radius);pointer-events:none}.streaming-indicator{padding:var(--space-3);text-align:center}.streaming-indicator .streaming-info{margin:0}.streaming-indicator .streaming-info small{color:#fff;font-weight:500;text-shadow:0 1px 2px rgba(0,0,0,.5)}.processor-actions{display:flex;justify-content:center;gap:var(--space-3)}.success-actions,.processing-actions{display:flex;gap:var(--space-3)}.preview-container{position:relative;width:100%;max-width:300px;background:var(--color-bg-secondary);border-radius:var(--border-radius-md);overflow:hidden;border:1px solid var(--color-border)}.compact-image-preview{margin:var(--space-4) 0;display:flex;justify-content:center;width:100%}.compact-preview-image{max-width:100%;width:100%;height:auto;max-height:300px;object-fit:contain;border-radius:var(--border-radius-md);box-shadow:var(--shadow-sm);display:block;background:var(--color-bg-secondary)}.preview-loading{display:flex;align-items:center;justify-content:center;gap:var(--space-2);padding:var(--space-4);color:var(--color-text-secondary);font-size:.85rem}.preview-fallback{position:relative}.preview-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#000000b3;display:flex;align-items:center;justify-content:center;color:#fff;font-size:.8rem;font-weight:500}.preview-help{display:block;margin-top:var(--space-2);font-size:.75rem;color:var(--color-text-secondary);text-align:center;font-style:italic}.image-processor.processing{min-height:400px;display:flex;align-items:center;justify-content:center}.processing-container{text-align:center;max-width:400px;padding:var(--space-6)}.processing-content{display:flex;flex-direction:column;align-items:center;gap:var(--space-4)}.loading-spinner{display:flex;align-items:center;justify-content:center}.processing-status{margin:0;color:var(--color-text-secondary);font-size:.9rem}.prompt-display{margin-top:var(--space-3);position:relative;max-width:100%}.prompt-text{font-size:var(--text-sm);color:var(--stone-600);line-height:1.4;padding:var(--space-3);background:var(--stone-50);border-radius:var(--radius);border-left:3px solid var(--accent-blue);position:relative;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;mask-image:linear-gradient(to bottom,black 0%,black 70%,transparent 100%);-webkit-mask-image:linear-gradient(to bottom,black 0%,black 70%,transparent 100%)}.prompt-text:after{content:"";position:absolute;bottom:0;left:0;right:0;height:20px;background:linear-gradient(to bottom,transparent 0%,var(--stone-50) 100%);pointer-events:none}@media (max-width: 768px){.image-container{max-width:100%}.processor-header h2{font-size:1.25rem}.preview-container{max-width:100%}.processor-actions,.success-actions,.processing-actions{flex-direction:column;align-items:stretch}.compact-preview-image{max-height:250px}}@media (max-width: 480px){.compact-preview-image{max-height:200px}}.example-prompts{margin-top:var(--space-6)}.example-prompts h4{margin:0 0 var(--space-4) 0;font-size:var(--text-sm);font-weight:600;color:var(--stone-700);text-align:center}.examples-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:var(--space-3)}.example-prompt{padding:var(--space-3);border:1px solid var(--border-light);border-radius:var(--radius);background:var(--surface);font-size:var(--text-sm);color:var(--stone-700);cursor:pointer;transition:var(--transition);text-align:left;line-height:1.4}.example-prompt:hover{border-color:var(--stone-300);background:var(--stone-50);transform:translateY(-1px);box-shadow:var(--shadow-sm)}.edit-mode-selector{display:flex;flex-direction:column;gap:var(--space-4)}.edit-mode-selector .step-header{text-align:center;margin-bottom:var(--space-2)}.edit-mode-selector .step-header h2{margin-bottom:var(--space-1);font-size:1.4rem}.edit-mode-selector .step-header p{margin:0;font-size:.85rem}.edit-mode-selector .image-preview{margin:var(--space-3) 0 var(--space-4) 0;text-align:center}.edit-mode-selector .compact-preview-image{max-width:250px;max-height:150px;width:auto;height:auto;object-fit:contain;border-radius:var(--border-radius-md);box-shadow:var(--shadow-sm);display:block;margin:0 auto}.edit-mode-selector .preview-help{margin-top:var(--space-1);font-size:.7rem;color:var(--color-text-secondary);font-style:italic}.edit-mode-selection,.edit-mode-options{display:flex;flex-direction:column;gap:var(--space-3)}.edit-mode-option{padding:var(--space-4);border:1px solid var(--color-border);border-radius:var(--border-radius-lg);cursor:pointer;transition:var(--transition);background:var(--color-bg-primary);position:relative;overflow:hidden}.edit-mode-option:before{content:"";position:absolute;top:0;left:0;right:0;bottom:0;background:linear-gradient(135deg,transparent,rgba(59,130,246,.05));opacity:0;transition:var(--transition)}.edit-mode-option:hover{border-color:var(--color-primary);transform:translateY(-1px);box-shadow:var(--shadow-md)}.edit-mode-option:hover:before{opacity:1}.edit-mode-option h3{margin:var(--space-2) 0 var(--space-1) 0;font-size:1.1rem;font-weight:600;color:var(--color-text-primary)}.edit-mode-option p{margin:0 0 var(--space-2) 0;color:var(--color-text-secondary);font-size:.85rem}.mode-features{margin-top:var(--space-2);padding-top:var(--space-2);border-top:1px solid var(--color-border-light)}.mode-features small{color:var(--color-text-tertiary);font-size:.75rem;line-height:1.4}.edit-mode-selector .step-actions{margin-top:var(--space-4);padding-top:var(--space-3);border-top:1px solid var(--color-border-light)}@media (max-width: 768px){.edit-mode-selector{gap:var(--space-3)}.edit-mode-selector .compact-preview-image{max-width:200px;max-height:120px}.edit-mode-option{padding:var(--space-3)}.edit-mode-option h3{font-size:1rem}}.version-history-panel{background:var(--surface);border:1px solid var(--border-light);border-radius:var(--radius-md);padding:var(--space-4);margin-top:var(--space-6)}.version-history-header{display:flex;align-items:center;gap:var(--space-2);margin-bottom:var(--space-4);padding-bottom:var(--space-3);border-bottom:1px solid var(--border-light)}.version-history-header h3{margin:0;font-size:var(--text-base);font-weight:600;color:var(--stone-800)}.version-list{list-style:none;padding:0;margin:0;display:flex;flex-direction:column;gap:var(--space-3)}.version-item{display:flex;align-items:center;gap:var(--space-3);padding:var(--space-3);border:1px solid var(--border-light);border-radius:var(--radius);background:var(--background);transition:var(--transition)}.version-item:hover{border-color:var(--stone-300);box-shadow:var(--shadow-sm)}.version-thumbnail{width:48px;height:48px;object-fit:cover;border-radius:var(--radius-sm);flex-shrink:0}.version-info{flex:1;min-width:0}.version-prompt{display:block;font-size:var(--text-sm);color:var(--stone-800);font-weight:500;line-height:1.4;margin-bottom:var(--space-1)}.version-timestamp{font-size:var(--text-xs);color:var(--muted-light)}.action-btn-icon{padding:var(--space-2);border:1px solid var(--border-light);border-radius:var(--radius-sm);background:var(--background);color:var(--muted);cursor:pointer;transition:var(--transition);display:flex;align-items:center;justify-content:center}.action-btn-icon:hover{border-color:var(--stone-300);background:var(--stone-50);color:var(--stone-700)}.mask-editor-content{display:flex;flex-direction:column;gap:var(--space-6)}.canvas-wrapper{position:relative;display:flex;justify-content:center;background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);padding:var(--space-4)}.mask-canvas,.base-canvas,.overlay-canvas{border-radius:var(--radius);box-shadow:var(--shadow)}.mask-controls{display:flex;flex-direction:column;gap:var(--space-4);padding:var(--space-4);background:var(--surface);border:1px solid var(--border-light);border-radius:var(--radius)}.control-group{display:flex;flex-direction:column;gap:var(--space-2)}.control-group label{font-size:var(--text-sm);font-weight:500;color:var(--stone-700)}.brush-slider{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:6px;background:var(--border);border-radius:3px;outline:none}.brush-slider::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:20px;height:20px;background:var(--accent-blue);border-radius:50%;cursor:pointer}.tool-buttons{display:flex;gap:var(--space-2)}.tool-btn{flex:1;padding:var(--space-3);border:1px solid var(--border);border-radius:var(--radius);background:var(--background);color:var(--stone-700);font-size:var(--text-sm);font-weight:500;cursor:pointer;transition:var(--transition)}.tool-btn:hover{border-color:var(--stone-300);background:var(--stone-50)}.tool-btn.active{border-color:var(--accent-blue);background:#3b82f61a;color:var(--accent-blue)}.mask-help{padding:var(--space-4);background:var(--stone-50);border:1px solid var(--border-light);border-radius:var(--radius);font-size:var(--text-sm);color:var(--stone-700);line-height:1.5}.mask-help p{margin:0 0 var(--space-2) 0}.mask-help ul{margin:0;padding-left:var(--space-4)}.mask-help li{margin-bottom:var(--space-1)}.mask-editor-new,.mask-editor-workspace{display:flex;flex-direction:column;gap:var(--space-6)}.canvas-container{position:relative;display:flex;justify-content:center;align-items:center;min-height:400px;padding:var(--space-6);background:var(--stone-50);border:2px dashed var(--border);border-radius:var(--radius-lg);overflow:hidden}.canvas-loading{display:flex;flex-direction:column;align-items:center;gap:var(--space-3);color:var(--muted)}.mask-canvas-base,.mask-canvas-overlay{border-radius:var(--radius);box-shadow:var(--shadow-lg);border:2px solid var(--stone-200);opacity:0;transition:opacity .3s ease}.mask-canvas-base.loaded,.mask-canvas-overlay.loaded{opacity:1}.mask-toolbar{display:flex;flex-wrap:wrap;gap:var(--space-6);padding:var(--space-5);background:var(--surface);border:1px solid var(--border-light);border-radius:var(--radius-lg);align-items:center}.toolbar-section{display:flex;flex-direction:column;gap:var(--space-2);min-width:120px}.toolbar-title{font-size:var(--text-xs);font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:.1em}.tool-buttons-new{display:flex;gap:var(--space-2)}.tool-btn-new{display:flex;align-items:center;gap:var(--space-2);padding:var(--space-3) var(--space-4);border:1px solid var(--border);border-radius:var(--radius);background:var(--background);color:var(--stone-700);font-size:var(--text-sm);font-weight:500;cursor:pointer;transition:var(--transition);min-width:80px;justify-content:center}.tool-btn-new:hover{border-color:var(--stone-300);background:var(--stone-50);transform:translateY(-1px)}.tool-btn-new.active{border-color:var(--accent-blue);background:#3b82f61a;color:var(--accent-blue);box-shadow:0 0 0 3px #3b82f61a}.brush-slider-new{-webkit-appearance:none;-moz-appearance:none;appearance:none;height:8px;background:var(--stone-200);border-radius:4px;outline:none;transition:var(--transition);min-width:120px}.brush-slider-new::-webkit-slider-thumb{-webkit-appearance:none;-moz-appearance:none;appearance:none;width:24px;height:24px;background:var(--accent-blue);border-radius:50%;cursor:pointer;transition:var(--transition);box-shadow:0 2px 8px #0000001a}.brush-slider-new::-webkit-slider-thumb:hover{transform:scale(1.1);box-shadow:0 4px 12px #00000026}.mask-instructions{display:flex;flex-direction:column;gap:var(--space-3);padding:var(--space-5);background:linear-gradient(135deg,var(--stone-50) 0%,var(--background) 100%);border:1px solid var(--border-light);border-radius:var(--radius-lg)}.instruction-item{display:flex;align-items:center;gap:var(--space-3);font-size:var(--text-sm);color:var(--stone-700)}.instruction-icon{display:flex;align-items:center;justify-content:center;width:24px;height:24px;border-radius:50%;font-weight:700;font-size:14px}.instruction-icon.paint{background:#ef44441a;color:#ef4444}.instruction-icon.erase{background:#9ca3af1a;color:#6b7280}.instruction-icon.tip{background:#3b82f61a;color:#3b82f6;font-size:12px}.notification-toast{position:fixed;top:var(--space-6);right:var(--space-6);z-index:1000;max-width:400px;border-radius:var(--radius-lg);padding:var(--space-4);box-shadow:0 10px 25px #0000001a,0 4px 10px #0000001a;-webkit-backdrop-filter:blur(10px);backdrop-filter:blur(10px);animation:slideIn .3s ease-out;border:1px solid var(--border-light)}.notification-success{background:#22c55ef2;color:#fff;border-color:#22c55e}.notification-error{background:#ef4444f2;color:#fff;border-color:#ef4444}.notification-info{background:#3b82f6f2;color:#fff;border-color:#3b82f6}.notification-content{display:flex;align-items:center;gap:var(--space-3)}.notification-icon{flex-shrink:0;display:flex;align-items:center;justify-content:center}.notification-message{flex:1;font-size:var(--text-sm);font-weight:500;line-height:1.4}.notification-close{flex-shrink:0;background:none;border:none;color:inherit;cursor:pointer;padding:var(--space-1);border-radius:var(--radius);transition:var(--transition);opacity:.8}.notification-close:hover{opacity:1;background:#ffffff1a}@keyframes slideIn{0%{transform:translate(100%);opacity:0}to{transform:translate(0);opacity:1}}@media (max-width: 768px){.notification-toast{top:var(--space-4);right:var(--space-4);left:var(--space-4);max-width:none}}.error-message{padding:var(--space-4);background:#ef44441a;border:1px solid rgb(239 68 68 / .2);border-radius:var(--radius);color:#b91c1c;font-size:var(--text-sm);margin:var(--space-4) 0;text-align:center}.spinner{width:20px;height:20px;border:2px solid var(--border);border-top:2px solid var(--accent-blue);border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}@media (max-width: 768px){.blockart-container{padding:var(--space-4);margin:var(--space-2)}.choice-options,.edit-mode-options,.examples-grid{grid-template-columns:1fr}.fullscreen-image{max-height:300px}.generated-image,.comparison-image{max-width:200px;max-height:200px}.generation-placeholder,.edit-placeholder{width:200px;height:200px}.edit-comparison{flex-direction:column;gap:var(--space-4)}.edit-arrow{transform:rotate(90deg)}.primary-actions{flex-direction:column;width:100%}.action-btn{width:100%}}.btn:focus-visible,.choice-option:focus-visible,.edit-mode-option:focus-visible,.example-prompt:focus-visible{outline:2px solid var(--accent-blue);outline-offset:2px}@media print{.blockart-container{box-shadow:none;border:1px solid #000}.overlay-top,.overlay-bottom{display:none}}.form-label-with-actions{display:flex;justify-content:space-between;align-items:center;margin-bottom:var(--space-2)}.ai-enhance-container{position:relative}.ai-enhance-btn{display:inline-flex;align-items:center;gap:var(--space-2);padding:var(--space-2) var(--space-3);background:var(--accent-blue);color:#fff;border:none;border-radius:var(--radius);font-size:var(--text-sm);font-weight:500;cursor:pointer;transition:var(--transition)}.ai-enhance-btn:hover{background:var(--accent-blue-hover)}.ai-enhance-btn:disabled{opacity:.6;cursor:not-allowed}.ai-enhance-dropdown{position:absolute;top:calc(100% + 4px);right:0;width:260px;background:#fff;border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-lg);z-index:1000}.dropdown-header{padding:var(--space-3);border-bottom:1px solid var(--border-light);background:var(--stone-50)}.dropdown-header h4{margin:0 0 var(--space-1) 0;font-size:var(--text-sm);font-weight:600;color:var(--stone-900)}.dropdown-header p{margin:0;font-size:var(--text-xs);color:var(--muted)}.dropdown-actions{padding:var(--space-2)}.dropdown-action{display:block;width:100%;padding:var(--space-2);background:transparent;border:none;border-radius:var(--radius-sm);color:var(--stone-700);font-size:var(--text-sm);font-weight:400;cursor:pointer;transition:var(--transition);text-align:left;margin-bottom:var(--space-1)}.dropdown-action:hover{background:var(--stone-100);color:var(--stone-900)}.dropdown-action:last-child{margin-bottom:0}.textarea-container{position:relative}.textarea-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:#ffffffe6;display:flex;align-items:center;justify-content:center;border-radius:var(--radius);z-index:10}.enhancement-loader{display:flex;flex-direction:column;align-items:center;gap:var(--space-2);text-align:center}.enhancement-loader .spinner{width:20px;height:20px}.enhancement-loader span{font-size:var(--text-sm);color:var(--stone-700)}.textarea-footer{display:flex;justify-content:space-between;align-items:center;margin-top:var(--space-2)}.enhancement-error{font-size:var(--text-xs);color:var(--accent-red);background:#ef44441a;padding:var(--space-1) var(--space-2);border-radius:var(--radius-sm)}@media (max-width: 768px){.ai-enhance-dropdown{width:220px}.form-label-with-actions{flex-direction:column;align-items:flex-start;gap:var(--space-2)}.ai-enhance-container{align-self:flex-end}}html{overflow:auto;height:100%}:root{--sb_green: #00b3b0;--sb_green_75: #40c6c4;--sb_green_50: #7fd9d7;--sb_green_25: #d9f4f3;--sb_dark_blue: #1b243f;--sb_dark_blue_75: #545b6f;--sb_dark_blue_50: #8d919f;--sb_dark_blue_25: #c6c8cf;--green: #2db47d;--green_75: #62c79e;--green_50: #96d9be;--green_25: #caecde;--green_disabled: #004e4c;--yellow: #fbce41;--yellow_75: #fcdb71;--yellow_50: #fde6a0;--yellow_25: #fef3cf;--blue: #395ece;--blue_75: #6b87db;--blue_50: #9caee6;--blue_25: #cdd7f3;--orange: #ffac00;--orange_75: #ffc140;--orange_50: #ffd57f;--orange_25: #ffeabf;--red: #ff6159;--red_75: #ff8983;--red_50: #ffb0ac;--red_25: #ffd7d5;--light: #dfe3e8;--light_75: #e7eaee;--light_50: #eff1f3;--light_25: #f7f8f9;--light_gray: #b1b5be;--black: #101525;--white: #fff;font-family:Roboto,sans-serif;font-style:normal;line-height:1.5;font-weight:400;font-size:1rem;font-synthesis:none;text-rendering:optimizeLegibility;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;-webkit-text-size-adjust:100%}#app{width:100%}body{margin:0;display:flex;box-sizing:border-box}')),document.head.appendChild(e)}}catch(r){console.error("vite-plugin-css-injected-by-js",r)}})(); "use strict";var Xp=Object.defineProperty;var Kp=(e,t,n)=>t in e?Xp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var ys=(e,t,n)=>Kp(e,typeof t!="symbol"?t+"":t,n);var nd={exports:{}},Di={},rd={exports:{}},q={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var as=Symbol.for("react.element"),qp=Symbol.for("react.portal"),Gp=Symbol.for("react.fragment"),Jp=Symbol.for("react.strict_mode"),Yp=Symbol.for("react.profiler"),Zp=Symbol.for("react.provider"),em=Symbol.for("react.context"),tm=Symbol.for("react.forward_ref"),nm=Symbol.for("react.suspense"),rm=Symbol.for("react.memo"),sm=Symbol.for("react.lazy"),wu=Symbol.iterator;function im(e){return e===null||typeof e!="object"?null:(e=wu&&e[wu]||e["@@iterator"],typeof e=="function"?e:null)}var sd={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},id=Object.assign,od={};function ir(e,t,n){this.props=e,this.context=t,this.refs=od,this.updater=n||sd}ir.prototype.isReactComponent={};ir.prototype.setState=function(e,t){if(typeof e!="object"&&typeof e!="function"&&e!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,e,t,"setState")};ir.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,"forceUpdate")};function ad(){}ad.prototype=ir.prototype;function Ga(e,t,n){this.props=e,this.context=t,this.refs=od,this.updater=n||sd}var Ja=Ga.prototype=new ad;Ja.constructor=Ga;id(Ja,ir.prototype);Ja.isPureReactComponent=!0;var xu=Array.isArray,ld=Object.prototype.hasOwnProperty,Ya={current:null},ud={key:!0,ref:!0,__self:!0,__source:!0};function cd(e,t,n){var r,s={},i=null,o=null;if(t!=null)for(r in t.ref!==void 0&&(o=t.ref),t.key!==void 0&&(i=""+t.key),t)ld.call(t,r)&&!ud.hasOwnProperty(r)&&(s[r]=t[r]);var a=arguments.length-2;if(a===1)s.children=n;else if(1>>1,V=A[K];if(0>>1;Ks(et,F))yts(jn,et)?(A[K]=jn,A[yt]=F,K=yt):(A[K]=et,A[He]=F,K=He);else if(yts(jn,F))A[K]=jn,A[yt]=F,K=yt;else break e}}return D}function s(A,D){var F=A.sortIndex-D.sortIndex;return F!==0?F:A.id-D.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;e.unstable_now=function(){return i.now()}}else{var o=Date,a=o.now();e.unstable_now=function(){return o.now()-a}}var l=[],c=[],g=1,h=null,m=3,y=!1,x=!1,w=!1,k=typeof setTimeout=="function"?setTimeout:null,f=typeof clearTimeout=="function"?clearTimeout:null,d=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function p(A){for(var D=n(c);D!==null;){if(D.callback===null)r(c);else if(D.startTime<=A)r(c),D.sortIndex=D.expirationTime,t(l,D);else break;D=n(c)}}function v(A){if(w=!1,p(A),!x)if(n(l)!==null)x=!0,Y(E);else{var D=n(c);D!==null&&ee(v,D.startTime-A)}}function E(A,D){x=!1,w&&(w=!1,f(I),I=-1),y=!0;var F=m;try{for(p(D),h=n(l);h!==null&&(!(h.expirationTime>D)||A&&!P());){var K=h.callback;if(typeof K=="function"){h.callback=null,m=h.priorityLevel;var V=K(h.expirationTime<=D);D=e.unstable_now(),typeof V=="function"?h.callback=V:h===n(l)&&r(l),p(D)}else r(l);h=n(l)}if(h!==null)var We=!0;else{var He=n(c);He!==null&&ee(v,He.startTime-D),We=!1}return We}finally{h=null,m=F,y=!1}}var _=!1,C=null,I=-1,O=5,j=-1;function P(){return!(e.unstable_now()-jA||125K?(A.sortIndex=F,t(c,A),n(l)===null&&A===n(c)&&(w?(f(I),I=-1):w=!0,ee(v,F-K))):(A.sortIndex=V,t(l,A),x||y||(x=!0,Y(E))),A},e.unstable_shouldYield=P,e.unstable_wrapCallback=function(A){var D=m;return function(){var F=m;m=D;try{return A.apply(this,arguments)}finally{m=F}}}})(md);pd.exports=md;var gm=pd.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var ym=$,Je=gm;function N(e){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+e,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Vo=Object.prototype.hasOwnProperty,vm=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,ku={},Su={};function wm(e){return Vo.call(Su,e)?!0:Vo.call(ku,e)?!1:vm.test(e)?Su[e]=!0:(ku[e]=!0,!1)}function xm(e,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(e=e.toLowerCase().slice(0,5),e!=="data-"&&e!=="aria-");default:return!1}}function _m(e,t,n,r){if(t===null||typeof t>"u"||xm(e,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function $e(e,t,n,r,s,i,o){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=s,this.mustUseProperty=n,this.propertyName=e,this.type=t,this.sanitizeURL=i,this.removeEmptyString=o}var Ce={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(e){Ce[e]=new $e(e,0,!1,e,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(e){var t=e[0];Ce[t]=new $e(t,1,!1,e[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(e){Ce[e]=new $e(e,2,!1,e.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(e){Ce[e]=new $e(e,2,!1,e,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(e){Ce[e]=new $e(e,3,!1,e.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(e){Ce[e]=new $e(e,3,!0,e,null,!1,!1)});["capture","download"].forEach(function(e){Ce[e]=new $e(e,4,!1,e,null,!1,!1)});["cols","rows","size","span"].forEach(function(e){Ce[e]=new $e(e,6,!1,e,null,!1,!1)});["rowSpan","start"].forEach(function(e){Ce[e]=new $e(e,5,!1,e.toLowerCase(),null,!1,!1)});var el=/[\-:]([a-z])/g;function tl(e){return e[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(e){var t=e.replace(el,tl);Ce[t]=new $e(t,1,!1,e,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(e){var t=e.replace(el,tl);Ce[t]=new $e(t,1,!1,e,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(e){var t=e.replace(el,tl);Ce[t]=new $e(t,1,!1,e,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(e){Ce[e]=new $e(e,1,!1,e.toLowerCase(),null,!1,!1)});Ce.xlinkHref=new $e("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(e){Ce[e]=new $e(e,1,!1,e.toLowerCase(),null,!0,!0)});function nl(e,t,n,r){var s=Ce.hasOwnProperty(t)?Ce[t]:null;(s!==null?s.type!==0:r||!(2a||s[o]!==i[a]){var l=` `+s[o].replace(" at new "," at ");return e.displayName&&l.includes("")&&(l=l.replace("",e.displayName)),l}while(1<=o&&0<=a);break}}}finally{fo=!1,Error.prepareStackTrace=n}return(e=e?e.displayName||e.name:"")?wr(e):""}function km(e){switch(e.tag){case 5:return wr(e.type);case 16:return wr("Lazy");case 13:return wr("Suspense");case 19:return wr("SuspenseList");case 0:case 2:case 15:return e=ho(e.type,!1),e;case 11:return e=ho(e.type.render,!1),e;case 1:return e=ho(e.type,!0),e;default:return""}}function qo(e){if(e==null)return null;if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case Tn:return"Fragment";case On:return"Portal";case Qo:return"Profiler";case rl:return"StrictMode";case Xo:return"Suspense";case Ko:return"SuspenseList"}if(typeof e=="object")switch(e.$$typeof){case vd:return(e.displayName||"Context")+".Consumer";case yd:return(e._context.displayName||"Context")+".Provider";case sl:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case il:return t=e.displayName||null,t!==null?t:qo(e.type)||"Memo";case Ut:t=e._payload,e=e._init;try{return qo(e(t))}catch{}}return null}function Sm(e){var t=e.type;switch(e.tag){case 24:return"Cache";case 9:return(t.displayName||"Context")+".Consumer";case 10:return(t._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return e=t.render,e=e.displayName||e.name||"",t.displayName||(e!==""?"ForwardRef("+e+")":"ForwardRef");case 7:return"Fragment";case 5:return t;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return qo(t);case 8:return t===rl?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t}return null}function tn(e){switch(typeof e){case"boolean":case"number":case"string":case"undefined":return e;case"object":return e;default:return""}}function xd(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function Cm(e){var t=xd(e)?"checked":"value",n=Object.getOwnPropertyDescriptor(e.constructor.prototype,t),r=""+e[t];if(!e.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var s=n.get,i=n.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return s.call(this)},set:function(o){r=""+o,i.call(this,o)}}),Object.defineProperty(e,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(o){r=""+o},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function xs(e){e._valueTracker||(e._valueTracker=Cm(e))}function _d(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return e&&(r=xd(e)?e.checked?"true":"false":e.value),e=r,e!==n?(t.setValue(e),!0):!1}function li(e){if(e=e||(typeof document<"u"?document:void 0),typeof e>"u")return null;try{return e.activeElement||e.body}catch{return e.body}}function Go(e,t){var n=t.checked;return le({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??e._wrapperState.initialChecked})}function Eu(e,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=tn(t.value!=null?t.value:n),e._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function kd(e,t){t=t.checked,t!=null&&nl(e,"checked",t,!1)}function Jo(e,t){kd(e,t);var n=tn(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&e.value===""||e.value!=n)&&(e.value=""+n):e.value!==""+n&&(e.value=""+n);else if(r==="submit"||r==="reset"){e.removeAttribute("value");return}t.hasOwnProperty("value")?Yo(e,t.type,n):t.hasOwnProperty("defaultValue")&&Yo(e,t.type,tn(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(e.defaultChecked=!!t.defaultChecked)}function Iu(e,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+e._wrapperState.initialValue,n||t===e.value||(e.value=t),e.defaultValue=t}n=e.name,n!==""&&(e.name=""),e.defaultChecked=!!e._wrapperState.initialChecked,n!==""&&(e.name=n)}function Yo(e,t,n){(t!=="number"||li(e.ownerDocument)!==e)&&(n==null?e.defaultValue=""+e._wrapperState.initialValue:e.defaultValue!==""+n&&(e.defaultValue=""+n))}var xr=Array.isArray;function Qn(e,t,n,r){if(e=e.options,t){t={};for(var s=0;s"+t.valueOf().toString()+"",t=_s.firstChild;e.firstChild;)e.removeChild(e.firstChild);for(;t.firstChild;)e.appendChild(t.firstChild)}});function Hr(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var Rr={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},Em=["Webkit","ms","Moz","O"];Object.keys(Rr).forEach(function(e){Em.forEach(function(t){t=t+e.charAt(0).toUpperCase()+e.substring(1),Rr[t]=Rr[e]})});function Id(e,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||Rr.hasOwnProperty(e)&&Rr[e]?(""+t).trim():t+"px"}function jd(e,t){e=e.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,s=Id(n,t[n],r);n==="float"&&(n="cssFloat"),r?e.setProperty(n,s):e[n]=s}}var Im=le({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function ta(e,t){if(t){if(Im[e]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(N(137,e));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(N(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(N(61))}if(t.style!=null&&typeof t.style!="object")throw Error(N(62))}}function na(e,t){if(e.indexOf("-")===-1)return typeof t.is=="string";switch(e){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var ra=null;function ol(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var sa=null,Xn=null,Kn=null;function Pu(e){if(e=cs(e)){if(typeof sa!="function")throw Error(N(280));var t=e.stateNode;t&&(t=Hi(t),sa(e.stateNode,e.type,t))}}function Nd(e){Xn?Kn?Kn.push(e):Kn=[e]:Xn=e}function Pd(){if(Xn){var e=Xn,t=Kn;if(Kn=Xn=null,Pu(e),t)for(e=0;e>>=0,e===0?32:31-(bm(e)/Fm|0)|0}var ks=64,Ss=4194304;function _r(e){switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return e&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return e}}function fi(e,t){var n=e.pendingLanes;if(n===0)return 0;var r=0,s=e.suspendedLanes,i=e.pingedLanes,o=n&268435455;if(o!==0){var a=o&~s;a!==0?r=_r(a):(i&=o,i!==0&&(r=_r(i)))}else o=n&~s,o!==0?r=_r(o):i!==0&&(r=_r(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&s)&&(s=r&-r,i=t&-t,s>=i||s===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=e.entangledLanes,t!==0)for(e=e.entanglements,t&=r;0n;n++)t.push(e);return t}function ls(e,t,n){e.pendingLanes|=t,t!==536870912&&(e.suspendedLanes=0,e.pingedLanes=0),e=e.eventTimes,t=31-pt(t),e[t]=n}function Bm(e,t){var n=e.pendingLanes&~t;e.pendingLanes=t,e.suspendedLanes=0,e.pingedLanes=0,e.expiredLanes&=t,e.mutableReadLanes&=t,e.entangledLanes&=t,t=e.entanglements;var r=e.eventTimes;for(e=e.expirationTimes;0=Or),Fu=" ",Du=!1;function qd(e,t){switch(e){case"keyup":return gg.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Gd(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var Ln=!1;function vg(e,t){switch(e){case"compositionend":return Gd(t);case"keypress":return t.which!==32?null:(Du=!0,Fu);case"textInput":return e=t.data,e===Fu&&Du?null:e;default:return null}}function wg(e,t){if(Ln)return e==="compositionend"||!pl&&qd(e,t)?(e=Xd(),Vs=dl=Vt=null,Ln=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-e};e=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Wu(n)}}function ef(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?ef(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function tf(){for(var e=window,t=li();t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)e=t.contentWindow;else break;t=li(e.document)}return t}function ml(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}function Ng(e){var t=tf(),n=e.focusedElem,r=e.selectionRange;if(t!==n&&n&&n.ownerDocument&&ef(n.ownerDocument.documentElement,n)){if(r!==null&&ml(n)){if(t=r.start,e=r.end,e===void 0&&(e=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(e,n.value.length);else if(e=(t=n.ownerDocument||document)&&t.defaultView||window,e.getSelection){e=e.getSelection();var s=n.textContent.length,i=Math.min(r.start,s);r=r.end===void 0?i:Math.min(r.end,s),!e.extend&&i>r&&(s=r,r=i,i=s),s=Hu(n,i);var o=Hu(n,r);s&&o&&(e.rangeCount!==1||e.anchorNode!==s.node||e.anchorOffset!==s.offset||e.focusNode!==o.node||e.focusOffset!==o.offset)&&(t=t.createRange(),t.setStart(s.node,s.offset),e.removeAllRanges(),i>r?(e.addRange(t),e.extend(o.node,o.offset)):(t.setEnd(o.node,o.offset),e.addRange(t)))}}for(t=[],e=n;e=e.parentNode;)e.nodeType===1&&t.push({element:e,left:e.scrollLeft,top:e.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,$n=null,ca=null,Lr=null,da=!1;function Vu(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;da||$n==null||$n!==li(r)||(r=$n,"selectionStart"in r&&ml(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Lr&&Gr(Lr,r)||(Lr=r,r=mi(ca,"onSelect"),0Dn||(e.current=ya[Dn],ya[Dn]=null,Dn--)}function ne(e,t){Dn++,ya[Dn]=e.current,e.current=t}var nn={},Re=sn(nn),ze=sn(!1),vn=nn;function Zn(e,t){var n=e.type.contextTypes;if(!n)return nn;var r=e.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var s={},i;for(i in n)s[i]=t[i];return r&&(e=e.stateNode,e.__reactInternalMemoizedUnmaskedChildContext=t,e.__reactInternalMemoizedMaskedChildContext=s),s}function Ue(e){return e=e.childContextTypes,e!=null}function yi(){se(ze),se(Re)}function Yu(e,t,n){if(Re.current!==nn)throw Error(N(168));ne(Re,t),ne(ze,n)}function df(e,t,n){var r=e.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var s in r)if(!(s in t))throw Error(N(108,Sm(e)||"Unknown",s));return le({},n,r)}function vi(e){return e=(e=e.stateNode)&&e.__reactInternalMemoizedMergedChildContext||nn,vn=Re.current,ne(Re,e),ne(ze,ze.current),!0}function Zu(e,t,n){var r=e.stateNode;if(!r)throw Error(N(169));n?(e=df(e,t,vn),r.__reactInternalMemoizedMergedChildContext=e,se(ze),se(Re),ne(Re,e)):se(ze),ne(ze,n)}var Pt=null,Vi=!1,jo=!1;function ff(e){Pt===null?Pt=[e]:Pt.push(e)}function zg(e){Vi=!0,ff(e)}function on(){if(!jo&&Pt!==null){jo=!0;var e=0,t=Z;try{var n=Pt;for(Z=1;e>=o,s-=o,At=1<<32-pt(t)+s|n<I?(O=C,C=null):O=C.sibling;var j=m(f,C,p[I],v);if(j===null){C===null&&(C=O);break}e&&C&&j.alternate===null&&t(f,C),d=i(j,d,I),_===null?E=j:_.sibling=j,_=j,C=O}if(I===p.length)return n(f,C),ie&&an(f,I),E;if(C===null){for(;II?(O=C,C=null):O=C.sibling;var P=m(f,C,j.value,v);if(P===null){C===null&&(C=O);break}e&&C&&P.alternate===null&&t(f,C),d=i(P,d,I),_===null?E=P:_.sibling=P,_=P,C=O}if(j.done)return n(f,C),ie&&an(f,I),E;if(C===null){for(;!j.done;I++,j=p.next())j=h(f,j.value,v),j!==null&&(d=i(j,d,I),_===null?E=j:_.sibling=j,_=j);return ie&&an(f,I),E}for(C=r(f,C);!j.done;I++,j=p.next())j=y(C,f,I,j.value,v),j!==null&&(e&&j.alternate!==null&&C.delete(j.key===null?I:j.key),d=i(j,d,I),_===null?E=j:_.sibling=j,_=j);return e&&C.forEach(function(b){return t(f,b)}),ie&&an(f,I),E}function k(f,d,p,v){if(typeof p=="object"&&p!==null&&p.type===Tn&&p.key===null&&(p=p.props.children),typeof p=="object"&&p!==null){switch(p.$$typeof){case ws:e:{for(var E=p.key,_=d;_!==null;){if(_.key===E){if(E=p.type,E===Tn){if(_.tag===7){n(f,_.sibling),d=s(_,p.props.children),d.return=f,f=d;break e}}else if(_.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Ut&&nc(E)===_.type){n(f,_.sibling),d=s(_,p.props),d.ref=pr(f,_,p),d.return=f,f=d;break e}n(f,_);break}else t(f,_);_=_.sibling}p.type===Tn?(d=yn(p.props.children,f.mode,v,p.key),d.return=f,f=d):(v=Zs(p.type,p.key,p.props,null,f.mode,v),v.ref=pr(f,d,p),v.return=f,f=v)}return o(f);case On:e:{for(_=p.key;d!==null;){if(d.key===_)if(d.tag===4&&d.stateNode.containerInfo===p.containerInfo&&d.stateNode.implementation===p.implementation){n(f,d.sibling),d=s(d,p.children||[]),d.return=f,f=d;break e}else{n(f,d);break}else t(f,d);d=d.sibling}d=Lo(p,f.mode,v),d.return=f,f=d}return o(f);case Ut:return _=p._init,k(f,d,_(p._payload),v)}if(xr(p))return x(f,d,p,v);if(ur(p))return w(f,d,p,v);As(f,p)}return typeof p=="string"&&p!==""||typeof p=="number"?(p=""+p,d!==null&&d.tag===6?(n(f,d.sibling),d=s(d,p),d.return=f,f=d):(n(f,d),d=To(p,f.mode,v),d.return=f,f=d),o(f)):n(f,d)}return k}var tr=gf(!0),yf=gf(!1),_i=sn(null),ki=null,Bn=null,wl=null;function xl(){wl=Bn=ki=null}function _l(e){var t=_i.current;se(_i),e._currentValue=t}function xa(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)!==t?(e.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),e===n)break;e=e.return}}function Gn(e,t){ki=e,wl=Bn=null,e=e.dependencies,e!==null&&e.firstContext!==null&&(e.lanes&t&&(De=!0),e.firstContext=null)}function at(e){var t=e._currentValue;if(wl!==e)if(e={context:e,memoizedValue:t,next:null},Bn===null){if(ki===null)throw Error(N(308));Bn=e,ki.dependencies={lanes:0,firstContext:e}}else Bn=Bn.next=e;return t}var fn=null;function kl(e){fn===null?fn=[e]:fn.push(e)}function vf(e,t,n,r){var s=t.interleaved;return s===null?(n.next=n,kl(t)):(n.next=s.next,s.next=n),t.interleaved=n,Lt(e,r)}function Lt(e,t){e.lanes|=t;var n=e.alternate;for(n!==null&&(n.lanes|=t),n=e,e=e.return;e!==null;)e.childLanes|=t,n=e.alternate,n!==null&&(n.childLanes|=t),n=e,e=e.return;return n.tag===3?n.stateNode:null}var Bt=!1;function Sl(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function wf(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,effects:e.effects})}function Mt(e,t){return{eventTime:e,lane:t,tag:0,payload:null,callback:null,next:null}}function Jt(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,G&2){var s=r.pending;return s===null?t.next=t:(t.next=s.next,s.next=t),r.pending=t,Lt(e,n)}return s=r.interleaved,s===null?(t.next=t,kl(r)):(t.next=s.next,s.next=t),r.interleaved=t,Lt(e,n)}function Xs(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ll(e,n)}}function rc(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var s=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var o={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?s=i=o:i=i.next=o,n=n.next}while(n!==null);i===null?s=i=t:i=i.next=t}else s=i=t;n={baseState:r.baseState,firstBaseUpdate:s,lastBaseUpdate:i,shared:r.shared,effects:r.effects},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}function Si(e,t,n,r){var s=e.updateQueue;Bt=!1;var i=s.firstBaseUpdate,o=s.lastBaseUpdate,a=s.shared.pending;if(a!==null){s.shared.pending=null;var l=a,c=l.next;l.next=null,o===null?i=c:o.next=c,o=l;var g=e.alternate;g!==null&&(g=g.updateQueue,a=g.lastBaseUpdate,a!==o&&(a===null?g.firstBaseUpdate=c:a.next=c,g.lastBaseUpdate=l))}if(i!==null){var h=s.baseState;o=0,g=c=l=null,a=i;do{var m=a.lane,y=a.eventTime;if((r&m)===m){g!==null&&(g=g.next={eventTime:y,lane:0,tag:a.tag,payload:a.payload,callback:a.callback,next:null});e:{var x=e,w=a;switch(m=t,y=n,w.tag){case 1:if(x=w.payload,typeof x=="function"){h=x.call(y,h,m);break e}h=x;break e;case 3:x.flags=x.flags&-65537|128;case 0:if(x=w.payload,m=typeof x=="function"?x.call(y,h,m):x,m==null)break e;h=le({},h,m);break e;case 2:Bt=!0}}a.callback!==null&&a.lane!==0&&(e.flags|=64,m=s.effects,m===null?s.effects=[a]:m.push(a))}else y={eventTime:y,lane:m,tag:a.tag,payload:a.payload,callback:a.callback,next:null},g===null?(c=g=y,l=h):g=g.next=y,o|=m;if(a=a.next,a===null){if(a=s.shared.pending,a===null)break;m=a,a=m.next,m.next=null,s.lastBaseUpdate=m,s.shared.pending=null}}while(!0);if(g===null&&(l=h),s.baseState=l,s.firstBaseUpdate=c,s.lastBaseUpdate=g,t=s.shared.interleaved,t!==null){s=t;do o|=s.lane,s=s.next;while(s!==t)}else i===null&&(s.shared.lanes=0);_n|=o,e.lanes=o,e.memoizedState=h}}function sc(e,t,n){if(e=t.effects,t.effects=null,e!==null)for(t=0;tn?n:4,e(!0);var r=Po.transition;Po.transition={};try{e(!1),t()}finally{Z=n,Po.transition=r}}function $f(){return lt().memoizedState}function Hg(e,t,n){var r=Zt(e);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},bf(e))Ff(t,n);else if(n=vf(e,t,n,r),n!==null){var s=Te();mt(n,e,r,s),Df(n,t,r)}}function Vg(e,t,n){var r=Zt(e),s={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(bf(e))Ff(t,s);else{var i=e.alternate;if(e.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var o=t.lastRenderedState,a=i(o,n);if(s.hasEagerState=!0,s.eagerState=a,gt(a,o)){var l=t.interleaved;l===null?(s.next=s,kl(t)):(s.next=l.next,l.next=s),t.interleaved=s;return}}catch{}finally{}n=vf(e,t,s,r),n!==null&&(s=Te(),mt(n,e,r,s),Df(n,t,r))}}function bf(e){var t=e.alternate;return e===ae||t!==null&&t===ae}function Ff(e,t){$r=Ei=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function Df(e,t,n){if(n&4194240){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,ll(e,n)}}var Ii={readContext:at,useCallback:je,useContext:je,useEffect:je,useImperativeHandle:je,useInsertionEffect:je,useLayoutEffect:je,useMemo:je,useReducer:je,useRef:je,useState:je,useDebugValue:je,useDeferredValue:je,useTransition:je,useMutableSource:je,useSyncExternalStore:je,useId:je,unstable_isNewReconciler:!1},Qg={readContext:at,useCallback:function(e,t){return xt().memoizedState=[e,t===void 0?null:t],e},useContext:at,useEffect:oc,useImperativeHandle:function(e,t,n){return n=n!=null?n.concat([e]):null,qs(4194308,4,Rf.bind(null,t,e),n)},useLayoutEffect:function(e,t){return qs(4194308,4,e,t)},useInsertionEffect:function(e,t){return qs(4,2,e,t)},useMemo:function(e,t){var n=xt();return t=t===void 0?null:t,e=e(),n.memoizedState=[e,t],e},useReducer:function(e,t,n){var r=xt();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,e={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:t},r.queue=e,e=e.dispatch=Hg.bind(null,ae,e),[r.memoizedState,e]},useRef:function(e){var t=xt();return e={current:e},t.memoizedState=e},useState:ic,useDebugValue:Rl,useDeferredValue:function(e){return xt().memoizedState=e},useTransition:function(){var e=ic(!1),t=e[0];return e=Wg.bind(null,e[1]),xt().memoizedState=e,[t,e]},useMutableSource:function(){},useSyncExternalStore:function(e,t,n){var r=ae,s=xt();if(ie){if(n===void 0)throw Error(N(407));n=n()}else{if(n=t(),xe===null)throw Error(N(349));xn&30||Sf(r,t,n)}s.memoizedState=n;var i={value:n,getSnapshot:t};return s.queue=i,oc(Ef.bind(null,r,i,e),[e]),r.flags|=2048,ss(9,Cf.bind(null,r,i,n,t),void 0,null),n},useId:function(){var e=xt(),t=xe.identifierPrefix;if(ie){var n=Rt,r=At;n=(r&~(1<<32-pt(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=ns++,0<\/script>",e=e.removeChild(e.firstChild)):typeof r.is=="string"?e=o.createElement(n,{is:r.is}):(e=o.createElement(n),n==="select"&&(o=e,r.multiple?o.multiple=!0:r.size&&(o.size=r.size))):e=o.createElementNS(e,n),e[kt]=t,e[Zr]=r,qf(e,t,!1,!1),t.stateNode=e;e:{switch(o=na(n,r),n){case"dialog":re("cancel",e),re("close",e),s=r;break;case"iframe":case"object":case"embed":re("load",e),s=r;break;case"video":case"audio":for(s=0;ssr&&(t.flags|=128,r=!0,mr(i,!1),t.lanes=4194304)}else{if(!r)if(e=Ci(o),e!==null){if(t.flags|=128,r=!0,n=e.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),mr(i,!0),i.tail===null&&i.tailMode==="hidden"&&!o.alternate&&!ie)return Ne(t),null}else 2*ce()-i.renderingStartTime>sr&&n!==1073741824&&(t.flags|=128,r=!0,mr(i,!1),t.lanes=4194304);i.isBackwards?(o.sibling=t.child,t.child=o):(n=i.last,n!==null?n.sibling=o:t.child=o,i.last=o)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=ce(),t.sibling=null,n=oe.current,ne(oe,r?n&1|2:n&1),t):(Ne(t),null);case 22:case 23:return bl(),r=t.memoizedState!==null,e!==null&&e.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Ke&1073741824&&(Ne(t),t.subtreeFlags&6&&(t.flags|=8192)):Ne(t),null;case 24:return null;case 25:return null}throw Error(N(156,t.tag))}function ey(e,t){switch(yl(t),t.tag){case 1:return Ue(t.type)&&yi(),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return nr(),se(ze),se(Re),Il(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 5:return El(t),null;case 13:if(se(oe),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(N(340));er()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return se(oe),null;case 4:return nr(),null;case 10:return _l(t.type._context),null;case 22:case 23:return bl(),null;case 24:return null;default:return null}}var Ms=!1,Ae=!1,ty=typeof WeakSet=="function"?WeakSet:Set,L=null;function Wn(e,t){var n=e.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){ue(e,t,r)}else n.current=null}function Pa(e,t,n){try{n()}catch(r){ue(e,t,r)}}var yc=!1;function ny(e,t){if(fa=hi,e=tf(),ml(e)){if("selectionStart"in e)var n={start:e.selectionStart,end:e.selectionEnd};else e:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var s=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var o=0,a=-1,l=-1,c=0,g=0,h=e,m=null;t:for(;;){for(var y;h!==n||s!==0&&h.nodeType!==3||(a=o+s),h!==i||r!==0&&h.nodeType!==3||(l=o+r),h.nodeType===3&&(o+=h.nodeValue.length),(y=h.firstChild)!==null;)m=h,h=y;for(;;){if(h===e)break t;if(m===n&&++c===s&&(a=o),m===i&&++g===r&&(l=o),(y=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=y}n=a===-1||l===-1?null:{start:a,end:l}}else n=null}n=n||{start:0,end:0}}else n=null;for(ha={focusedElem:e,selectionRange:n},hi=!1,L=t;L!==null;)if(t=L,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,L=e;else for(;L!==null;){t=L;try{var x=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(x!==null){var w=x.memoizedProps,k=x.memoizedState,f=t.stateNode,d=f.getSnapshotBeforeUpdate(t.elementType===t.type?w:ct(t.type,w),k);f.__reactInternalSnapshotBeforeUpdate=d}break;case 3:var p=t.stateNode.containerInfo;p.nodeType===1?p.textContent="":p.nodeType===9&&p.documentElement&&p.removeChild(p.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(N(163))}}catch(v){ue(t,t.return,v)}if(e=t.sibling,e!==null){e.return=t.return,L=e;break}L=t.return}return x=yc,yc=!1,x}function br(e,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var s=r=r.next;do{if((s.tag&e)===e){var i=s.destroy;s.destroy=void 0,i!==void 0&&Pa(t,n,i)}s=s.next}while(s!==r)}}function Ki(e,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&e)===e){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function Aa(e){var t=e.ref;if(t!==null){var n=e.stateNode;switch(e.tag){case 5:e=n;break;default:e=n}typeof t=="function"?t(e):t.current=e}}function Yf(e){var t=e.alternate;t!==null&&(e.alternate=null,Yf(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&(delete t[kt],delete t[Zr],delete t[ga],delete t[Fg],delete t[Dg])),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}function Zf(e){return e.tag===5||e.tag===3||e.tag===4}function vc(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||Zf(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function Ra(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(e,t):n.insertBefore(e,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(e,n)):(t=n,t.appendChild(e)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=gi));else if(r!==4&&(e=e.child,e!==null))for(Ra(e,t,n),e=e.sibling;e!==null;)Ra(e,t,n),e=e.sibling}function Ma(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(e=e.child,e!==null))for(Ma(e,t,n),e=e.sibling;e!==null;)Ma(e,t,n),e=e.sibling}var _e=null,ft=!1;function Ft(e,t,n){for(n=n.child;n!==null;)eh(e,t,n),n=n.sibling}function eh(e,t,n){if(Ct&&typeof Ct.onCommitFiberUnmount=="function")try{Ct.onCommitFiberUnmount(zi,n)}catch{}switch(n.tag){case 5:Ae||Wn(n,t);case 6:var r=_e,s=ft;_e=null,Ft(e,t,n),_e=r,ft=s,_e!==null&&(ft?(e=_e,n=n.stateNode,e.nodeType===8?e.parentNode.removeChild(n):e.removeChild(n)):_e.removeChild(n.stateNode));break;case 18:_e!==null&&(ft?(e=_e,n=n.stateNode,e.nodeType===8?Io(e.parentNode,n):e.nodeType===1&&Io(e,n),Kr(e)):Io(_e,n.stateNode));break;case 4:r=_e,s=ft,_e=n.stateNode.containerInfo,ft=!0,Ft(e,t,n),_e=r,ft=s;break;case 0:case 11:case 14:case 15:if(!Ae&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){s=r=r.next;do{var i=s,o=i.destroy;i=i.tag,o!==void 0&&(i&2||i&4)&&Pa(n,t,o),s=s.next}while(s!==r)}Ft(e,t,n);break;case 1:if(!Ae&&(Wn(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(a){ue(n,t,a)}Ft(e,t,n);break;case 21:Ft(e,t,n);break;case 22:n.mode&1?(Ae=(r=Ae)||n.memoizedState!==null,Ft(e,t,n),Ae=r):Ft(e,t,n);break;default:Ft(e,t,n)}}function wc(e){var t=e.updateQueue;if(t!==null){e.updateQueue=null;var n=e.stateNode;n===null&&(n=e.stateNode=new ty),t.forEach(function(r){var s=dy.bind(null,e,r);n.has(r)||(n.add(r),r.then(s,s))})}}function ut(e,t){var n=t.deletions;if(n!==null)for(var r=0;rs&&(s=o),r&=~i}if(r=s,r=ce()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*sy(r/1960))-r,10e?16:e,Qt===null)var r=!1;else{if(e=Qt,Qt=null,Pi=0,G&6)throw Error(N(331));var s=G;for(G|=4,L=e.current;L!==null;){var i=L,o=i.child;if(L.flags&16){var a=i.deletions;if(a!==null){for(var l=0;lce()-Ll?gn(e,0):Tl|=n),Be(e,t)}function lh(e,t){t===0&&(e.mode&1?(t=Ss,Ss<<=1,!(Ss&130023424)&&(Ss=4194304)):t=1);var n=Te();e=Lt(e,t),e!==null&&(ls(e,t,n),Be(e,n))}function cy(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),lh(e,n)}function dy(e,t){var n=0;switch(e.tag){case 13:var r=e.stateNode,s=e.memoizedState;s!==null&&(n=s.retryLane);break;case 19:r=e.stateNode;break;default:throw Error(N(314))}r!==null&&r.delete(t),lh(e,n)}var uh;uh=function(e,t,n){if(e!==null)if(e.memoizedProps!==t.pendingProps||ze.current)De=!0;else{if(!(e.lanes&n)&&!(t.flags&128))return De=!1,Yg(e,t,n);De=!!(e.flags&131072)}else De=!1,ie&&t.flags&1048576&&hf(t,xi,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Gs(e,t),e=t.pendingProps;var s=Zn(t,Re.current);Gn(t,n),s=Nl(null,t,r,e,s,n);var i=Pl();return t.flags|=1,typeof s=="object"&&s!==null&&typeof s.render=="function"&&s.$$typeof===void 0?(t.tag=1,t.memoizedState=null,t.updateQueue=null,Ue(r)?(i=!0,vi(t)):i=!1,t.memoizedState=s.state!==null&&s.state!==void 0?s.state:null,Sl(t),s.updater=Xi,t.stateNode=s,s._reactInternals=t,ka(t,r,e,n),t=Ea(null,t,r,!0,i,n)):(t.tag=0,ie&&i&&gl(t),Oe(null,t,s,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Gs(e,t),e=t.pendingProps,s=r._init,r=s(r._payload),t.type=r,s=t.tag=hy(r),e=ct(r,e),s){case 0:t=Ca(null,t,r,e,n);break e;case 1:t=pc(null,t,r,e,n);break e;case 11:t=fc(null,t,r,e,n);break e;case 14:t=hc(null,t,r,ct(r.type,e),n);break e}throw Error(N(306,r,""))}return t;case 0:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ct(r,s),Ca(e,t,r,s,n);case 1:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ct(r,s),pc(e,t,r,s,n);case 3:e:{if(Qf(t),e===null)throw Error(N(387));r=t.pendingProps,i=t.memoizedState,s=i.element,wf(e,t),Si(t,r,null,n);var o=t.memoizedState;if(r=o.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:o.cache,pendingSuspenseBoundaries:o.pendingSuspenseBoundaries,transitions:o.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){s=rr(Error(N(423)),t),t=mc(e,t,r,n,s);break e}else if(r!==s){s=rr(Error(N(424)),t),t=mc(e,t,r,n,s);break e}else for(qe=Gt(t.stateNode.containerInfo.firstChild),Ge=t,ie=!0,ht=null,n=yf(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(er(),r===s){t=$t(e,t,n);break e}Oe(e,t,r,n)}t=t.child}return t;case 5:return xf(t),e===null&&wa(t),r=t.type,s=t.pendingProps,i=e!==null?e.memoizedProps:null,o=s.children,pa(r,s)?o=null:i!==null&&pa(r,i)&&(t.flags|=32),Vf(e,t),Oe(e,t,o,n),t.child;case 6:return e===null&&wa(t),null;case 13:return Xf(e,t,n);case 4:return Cl(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=tr(t,null,r,n):Oe(e,t,r,n),t.child;case 11:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ct(r,s),fc(e,t,r,s,n);case 7:return Oe(e,t,t.pendingProps,n),t.child;case 8:return Oe(e,t,t.pendingProps.children,n),t.child;case 12:return Oe(e,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,s=t.pendingProps,i=t.memoizedProps,o=s.value,ne(_i,r._currentValue),r._currentValue=o,i!==null)if(gt(i.value,o)){if(i.children===s.children&&!ze.current){t=$t(e,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var a=i.dependencies;if(a!==null){o=i.child;for(var l=a.firstContext;l!==null;){if(l.context===r){if(i.tag===1){l=Mt(-1,n&-n),l.tag=2;var c=i.updateQueue;if(c!==null){c=c.shared;var g=c.pending;g===null?l.next=l:(l.next=g.next,g.next=l),c.pending=l}}i.lanes|=n,l=i.alternate,l!==null&&(l.lanes|=n),xa(i.return,n,t),a.lanes|=n;break}l=l.next}}else if(i.tag===10)o=i.type===t.type?null:i.child;else if(i.tag===18){if(o=i.return,o===null)throw Error(N(341));o.lanes|=n,a=o.alternate,a!==null&&(a.lanes|=n),xa(o,n,t),o=i.sibling}else o=i.child;if(o!==null)o.return=i;else for(o=i;o!==null;){if(o===t){o=null;break}if(i=o.sibling,i!==null){i.return=o.return,o=i;break}o=o.return}i=o}Oe(e,t,s.children,n),t=t.child}return t;case 9:return s=t.type,r=t.pendingProps.children,Gn(t,n),s=at(s),r=r(s),t.flags|=1,Oe(e,t,r,n),t.child;case 14:return r=t.type,s=ct(r,t.pendingProps),s=ct(r.type,s),hc(e,t,r,s,n);case 15:return Wf(e,t,t.type,t.pendingProps,n);case 17:return r=t.type,s=t.pendingProps,s=t.elementType===r?s:ct(r,s),Gs(e,t),t.tag=1,Ue(r)?(e=!0,vi(t)):e=!1,Gn(t,n),zf(t,r,s),ka(t,r,s,n),Ea(null,t,r,!0,e,n);case 19:return Kf(e,t,n);case 22:return Hf(e,t,n)}throw Error(N(156,t.tag))};function ch(e,t){return $d(e,t)}function fy(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function st(e,t,n,r){return new fy(e,t,n,r)}function Dl(e){return e=e.prototype,!(!e||!e.isReactComponent)}function hy(e){if(typeof e=="function")return Dl(e)?1:0;if(e!=null){if(e=e.$$typeof,e===sl)return 11;if(e===il)return 14}return 2}function en(e,t){var n=e.alternate;return n===null?(n=st(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&14680064,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n}function Zs(e,t,n,r,s,i){var o=2;if(r=e,typeof e=="function")Dl(e)&&(o=1);else if(typeof e=="string")o=5;else e:switch(e){case Tn:return yn(n.children,s,i,t);case rl:o=8,s|=8;break;case Qo:return e=st(12,n,t,s|2),e.elementType=Qo,e.lanes=i,e;case Xo:return e=st(13,n,t,s),e.elementType=Xo,e.lanes=i,e;case Ko:return e=st(19,n,t,s),e.elementType=Ko,e.lanes=i,e;case wd:return Gi(n,s,i,t);default:if(typeof e=="object"&&e!==null)switch(e.$$typeof){case yd:o=10;break e;case vd:o=9;break e;case sl:o=11;break e;case il:o=14;break e;case Ut:o=16,r=null;break e}throw Error(N(130,e==null?e:typeof e,""))}return t=st(o,n,t,s),t.elementType=e,t.type=r,t.lanes=i,t}function yn(e,t,n,r){return e=st(7,e,r,t),e.lanes=n,e}function Gi(e,t,n,r){return e=st(22,e,r,t),e.elementType=wd,e.lanes=n,e.stateNode={isHidden:!1},e}function To(e,t,n){return e=st(6,e,null,t),e.lanes=n,e}function Lo(e,t,n){return t=st(4,e.children!==null?e.children:[],e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}function py(e,t,n,r,s){this.tag=t,this.containerInfo=e,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=mo(0),this.expirationTimes=mo(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=mo(0),this.identifierPrefix=r,this.onRecoverableError=s,this.mutableSourceEagerHydrationData=null}function zl(e,t,n,r,s,i,o,a,l){return e=new py(e,t,n,a,l),t===1?(t=1,i===!0&&(t|=8)):t=0,i=st(3,null,null,t),e.current=i,i.stateNode=e,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},Sl(i),e}function my(e,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(ph)}catch(e){console.error(e)}}ph(),hd.exports=Ye;var xy=hd.exports,mh,jc=xy;mh=jc.createRoot,jc.hydrateRoot;const J=(e,t)=>typeof e=="object"&&e!==null&&t in e,_y=e=>{try{return structuredClone(e),!0}catch{return!1}},ky=()=>Math.random().toString(16).slice(2,10),Sy=()=>new Array(4).fill(0).map(ky).join("-"),Cy=e=>J(e,"name")&&typeof e.name=="string"&&J(e,"value")&&typeof e.value=="string",gh=e=>J(e,"field_type")&&typeof e.field_type=="string"&&J(e,"options")&&Array.isArray(e.options)&&e.options.every(Cy)&&(!J(e,"translatable")||J(e,"translatable")&&typeof e.translatable=="boolean"),In=e=>J(e,"action")&&typeof e.action=="string"&&J(e,"uid")&&typeof e.uid=="string",Hl=e=>J(e,"content")&&typeof e.content=="object"&&e.content!==null&&!Array.isArray(e.content),Ey=e=>In(e)&&e.action==="loaded"&&J(e,"language")&&typeof e.language=="string"&&J(e,"schema")&&gh(e.schema)&&J(e,"userId")&&(typeof e.userId=="number"||typeof e.userId>"u")&&J(e,"story")&&Hl(e.story)&&J(e,"isAIEnabled")&&typeof e.isAIEnabled=="boolean"&&J(e,"isModalOpen")&&typeof e.isModalOpen=="boolean",Iy=e=>In(e)&&e.action==="state-changed"&&J(e,"language")&&typeof e.language=="string"&&J(e,"schema")&&gh(e.schema)&&J(e,"userId")&&(typeof e.userId=="number"||typeof e.userId>"u")&&J(e,"story")&&Hl(e.story)&&J(e,"isAIEnabled")&&typeof e.isAIEnabled=="boolean"&&J(e,"isModalOpen")&&typeof e.isModalOpen=="boolean",jy=e=>e.reduce((t,n)=>(t[n.name]=n.value,t),{}),Ny=e=>J(e,"filename")&&typeof e.filename=="string"&&J(e,"asset")&&typeof e.asset=="object",Py=e=>{const{asset:t}=e;return t},Ay=e=>In(e)&&e.action==="asset-selected"&&Ry(e)&&Ny(e),Ry=e=>!J(e,"field")||typeof e.field>"u"?!0:typeof e.field=="string",My=e=>In(e)&&e.action==="get-context"&&J(e,"story")&&Hl(e.story),Oy=e=>J(e,"isSpaceAdmin")&&typeof e.isSpaceAdmin=="boolean"&&J(e,"permissions")&&e.permissions!==null&&(typeof e.permissions=="object"||typeof e.permissions>"u")&&!Array.isArray(e.permissions),Ty=e=>In(e)&&e.action==="get-user-context"&&J(e,"user")&&Oy(e.user),Ly=e=>In(e)&&e.action==="prompt-ai"&&J(e,"aiResponse")&&typeof e.aiResponse=="object"&&e.aiResponse!==null&&J(e.aiResponse,"ok")&&typeof e.aiResponse.ok=="boolean"&&(e.aiResponse.ok?J(e.aiResponse,"answer")&&typeof e.aiResponse.answer=="string":J(e.aiResponse,"error")&&typeof e.aiResponse.error=="string"),$y=e=>{const{aiResponse:t}=e;return t},by=e=>({action:"plugin-changed",event:"update",...e}),Nc=e=>({action:"plugin-changed",event:"toggleModal",...e}),Fy=e=>({action:"plugin-changed",event:"loaded",fullHeight:!0,subscribeState:!0,...e}),Dy=(e,t)=>({action:"plugin-changed",event:"heightChange",uid:e,height:t}),zy=e=>({action:"plugin-changed",event:"getContext",debounce:!1,...e}),Uy=e=>({action:"plugin-changed",event:"getUserContext",...e}),By=e=>({action:"plugin-changed",event:"showAssetModal",...e}),Wy=(e,t)=>({action:"prompt-ai",event:"promptAI",...t,promptAIPayload:{...e}}),Hy=e=>{const t=new URLSearchParams(e),n=t.get("uid")??void 0,r=t.get("protocol")??void 0,s=t.get("host")??void 0,i=t.get("preview")??void 0;return r!=="http:"&&r!=="https:"||typeof n>"u"||typeof s>"u"?void 0:{uid:n,secure:r==="https:",host:s,preview:typeof i<"u"}},yr=(e,t)=>{const n=t(e.model);return"error"in n&&typeof n.error=="string"&&(console.warn("[Warning] The provided content is not valid, but it's still sent to the Visual Editor."),console.warn(` > ${n.error}`)),{interfaceLang:e.interfaceLanguage,spaceId:e.spaceId??void 0,userId:e.userId??void 0,story:e.story??void 0,storyId:e.storyId??void 0,storyLang:e.language===""?"default":e.language,blockUid:e.blockId??void 0,token:e.token??void 0,options:jy(e.schema.options),translatable:e.schema.translatable??!1,isAIEnabled:e.isAIEnabled??!1,uid:e.uid??void 0,content:n.content,isModalOpen:e.isModalOpen,releases:e.releases,releaseId:e.releaseId}},Vy=()=>{let e={asset:{},context:{},userContext:{},stateChanged:{},loaded:{},promptAI:{}};return{pushCallback:(r,s)=>{const i=Sy();return e={...e,[r]:{...e[r],[i]:s}},i},popCallback:(r,s)=>{if(typeof s>"u")return;const i=e[r][s],o=Object.entries(e[r]).reduce((a,[l,c])=>(l===s||(a[l]=c),a),{});return e={...e,[r]:o},i}}},Qy=({uid:e,postToContainer:t,onUpdateState:n,validateContent:r,enablePortalModal:s})=>{const{pushCallback:i,popCallback:o}=Vy();return{actions:{setContent:f=>new Promise(d=>{const p=i("stateChanged",v=>d(yr(v,r)));t(by({uid:e,callbackId:p,model:f}))}),setModalOpen:(f,d)=>new Promise(p=>{const v=i("stateChanged",E=>p(yr(E,r)));t(Nc({uid:e,callbackId:v,status:f,modalSize:d}))}),selectAsset:()=>new Promise(f=>{const d=i("asset",p=>f(Py(p)));t(By({uid:e,callbackId:d}))}),requestContext:()=>new Promise(f=>{const d=i("context",p=>f(p.story));t(zy({uid:e,callbackId:d}))}),promptAI:f=>new Promise(d=>{const p=i("promptAI",v=>d($y(v)));t(Wy(f,{uid:e,callbackId:p}))}),requestUserContext:()=>new Promise(f=>{const d=i("userContext",p=>f(p.user));t(Uy({uid:e,callbackId:d}))})},messageCallbacks:{onStateChange:f=>{var d;(d=o("stateChanged",f.callbackId))==null||d(f),n(yr(f,r))},onLoaded:f=>{var d;(d=o("loaded",f.callbackId))==null||d(f),n(yr(f,r))},onContextRequest:f=>{var d;(d=o("context",f.callbackId))==null||d(f)},onUserContextRequest:f=>{var d;(d=o("userContext",f.callbackId))==null||d(f)},onAssetSelect:f=>{var d;(d=o("asset",f.callbackId))==null||d(f)},onPromptAI:f=>{var d;(d=o("promptAI",f.callbackId))==null||d(f)},onUnknownMessage:f=>{console.debug(`Plugin received a message from container of an unknown action type "${f.action}". You may need to upgrade the version of the @storyblok/field-plugin library. Full message: ${JSON.stringify(f)}`)}},onHeightChange:f=>{t(Dy(e,f))},onKeydownEsc:()=>{t(Nc({uid:e,status:!1}))},initialize:()=>new Promise(f=>{const d=i("loaded",p=>f(yr(p,r)));t(Fy({uid:e,callbackId:d,enablePortalModal:s}))})}},Xy=e=>{const t=()=>{e(document.body.clientHeight)},n=new ResizeObserver(t);return n.observe(document.body),()=>n.disconnect()},Ky=e=>{const t=n=>{n.key==="Escape"&&e()};return document.addEventListener("keydown",t),()=>document.removeEventListener("keydown",t)},qy=()=>{const e=document==null?void 0:document.querySelector('link[href^="https://plugins.storyblok.com"]');return e==null||e.setAttribute("disabled",""),()=>{e==null||e.removeAttribute("disabled")}},Gy=(e,t,n)=>{In(e)&&e.uid===t&&(Ey(e)?n.onLoaded(e):Iy(e)?n.onStateChange(e):My(e)?n.onContextRequest(e):Ty(e)?n.onUserContextRequest(e):Ay(e)?n.onAssetSelect(e):Ly(e)?n.onPromptAI(e):n.onUnknownMessage(e))},Jy=(e,t,n)=>{const r=s=>{s.origin===t&&Gy(s.data,e,n)};return window.addEventListener("message",r,!1),()=>{window.removeEventListener("message",r,!1)}},Yy="https://plugin-sandbox.storyblok.com/field-plugin/",Zy=()=>{const e=new URLSearchParams({url:window.location.href}).toString();return`${Yy}?${e}`},ev=({onUpdateState:e,validateContent:t,targetOrigin:n,enablePortalModal:r})=>{if(!(window.parent!==window))return e({type:"error",error:new Error(`The window is not embedded within another window. Did you mean to open the field plugin in the sandbox? ${Zy()}`)}),()=>{};const i=Hy(window.location.search);if(!i)return e({type:"error",error:new Error("The URL parameters does not match the expected format.")}),()=>{};const{uid:o,host:a}=i,l=typeof n=="string"?n:a==="plugin-sandbox.storyblok.com"?"https://plugin-sandbox.storyblok.com":"https://app.storyblok.com",c=p=>{try{window.parent.postMessage(p,l)}catch(v){throw _y(p)?v:new Error("The argument could not be cloned. The argument must be cloneable with structuredClone(), so that it can be sent to other windows with window.postMessage(). Does your object contain functions, getters, setters, proxies, or any other value that is not cloneable? Did you try to pass a reactive object? For a full description on the structuredClone algorithm, see: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm",{cause:v})}},g=qy(),{actions:h,messageCallbacks:m,onHeightChange:y,onKeydownEsc:x,initialize:w}=Qy({uid:o,postToContainer:c,onUpdateState:p=>{e({type:"loaded",data:p,actions:h})},validateContent:t||(p=>({content:p})),enablePortalModal:r}),k=Xy(y),f=Ky(x),d=Jy(i.uid,l,m);return w(),()=>{d(),k(),f(),g()}},tv=(e={})=>{const[t,n]=$.useState({type:"loading"});return $.useEffect(()=>ev({...e,onUpdateState:r=>{r.type==="error"?n({type:"error",error:r.error}):r.type==="loaded"&&n({type:"loaded",data:r.data,actions:r.actions})}}),[]),t},nv=e=>{const t=e.split(","),n=t[0].match(/:(.*?);/),r=n?n[1]:"image/png",s=atob(t[1]);let i=s.length;const o=new Uint8Array(i);for(;i--;)o[i]=s.charCodeAt(i);return new Blob([o],{type:r})},rv=(e,t=1024,n=1024,r=.8)=>new Promise((s,i)=>{const o=document.createElement("canvas"),a=o.getContext("2d"),l=new Image;l.onload=()=>{let{width:c,height:g}=l;c>g?c>t&&(g=g*t/c,c=t):g>n&&(c=c*n/g,g=n),o.width=c,o.height=g,a==null||a.drawImage(l,0,0,c,g);const h=o.toDataURL("image/jpeg",r);s(h)},l.onerror=()=>i(new Error("Failed to load image")),l.src=URL.createObjectURL(e)}),sv=e=>["image/jpeg","image/jpg","image/png","image/webp"].includes(e.type)&&e.size<=10485760,Pc=e=>new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.onload=()=>t(r),r.onerror=s=>{console.error("Failed to load image:",e,s),n(new Error(`Failed to load image: ${e}`))},r.src=e}),ba=e=>new Promise((t,n)=>{const r=new Image;r.onload=()=>t(r),r.onerror=s=>{console.error("Failed to load image:",e,s),n(new Error(`Failed to load image: ${e}`))},r.src=e}),yh=e=>{if(!e.startsWith("MASK:"))return null;try{const t=e.substring(5).split(":"),[n,r]=t,[s,i]=n.split("x").map(Number),o=r.split(",").map(Number),a=s*i,l=new Uint8Array(a);let c=0,g=0;for(const h of o){for(let m=0;m{try{if(t.startsWith("MASK:"))return iv(e,t,n,r);const[s,i]=await Promise.all([Pc(e),Pc(t)]),o=s.width/s.height;let a=Math.min(n,s.width),l=a/o;l>r&&(l=r,a=r*o);const c=document.createElement("canvas");c.width=a,c.height=l;const g=c.getContext("2d");if(!g)throw new Error("Could not get canvas context");g.drawImage(s,0,0,a,l);const h=document.createElement("canvas");h.width=i.width,h.height=i.height;const m=h.getContext("2d");if(!m)throw new Error("Could not get temporary canvas context");m.drawImage(i,0,0);const y=m.getImageData(0,0,i.width,i.height);g.globalCompositeOperation="source-over",g.fillStyle="rgba(255, 0, 0, 0.4)";const x=a/i.width,w=l/i.height,k=g.getImageData(0,0,a,l),f=new Uint8ClampedArray(k.data);for(let p=0;p200&&j>200&&P>200&&b>0&&(f[I]=Math.min(255,f[I]+100),f[I+1]=Math.max(0,f[I+1]-50),f[I+2]=Math.max(0,f[I+2]-50))}}const d=new ImageData(f,a,l);return g.putImageData(d,0,0),c.toDataURL("image/png")}catch(s){return console.error("Standard mask overlay failed, trying iframe-safe approach:",s),ov(e,t,n,r)}},iv=async(e,t,n=800,r=600)=>{try{const s=await ba(e),i=yh(t);if(!i)throw new Error("Failed to decode mask data");const o=s.width/s.height;let a=Math.min(n,s.width),l=a/o;l>r&&(l=r,a=r*o);const c=document.createElement("canvas");c.width=a,c.height=l;const g=c.getContext("2d");if(!g)throw new Error("Could not get canvas context");g.drawImage(s,0,0,a,l);const h=g.getImageData(0,0,a,l),m=new Uint8ClampedArray(h.data),y=a/i.width,x=l/i.height;for(let k=0;k{try{const[s,i]=await Promise.all([ba(e),ba(t)]),o=s.width/s.height;let a=Math.min(n,s.width),l=a/o;l>r&&(l=r,a=r*o);const c=document.createElement("canvas");c.width=a,c.height=l;const g=c.getContext("2d");if(!g)throw new Error("Could not get canvas context");try{g.drawImage(s,0,0,a,l);const h=document.createElement("canvas");h.width=i.width,h.height=i.height;const m=h.getContext("2d");if(!m)throw new Error("Could not get temporary canvas context");m.drawImage(i,0,0);const y=m.getImageData(0,0,i.width,i.height),x=g.getImageData(0,0,a,l),w=new Uint8ClampedArray(x.data),k=a/i.width,f=l/i.height;for(let p=0;p200&&j>200&&P>200&&b>0&&(w[I]=Math.min(255,w[I]+100),w[I+1]=Math.max(0,w[I+1]-50),w[I+2]=Math.max(0,w[I+2]-50))}}const d=new ImageData(w,a,l);return g.putImageData(d,0,0),c.toDataURL("image/png")}catch(h){return console.error("Canvas operations failed in iframe context:",h),null}}catch(s){return console.error("Iframe-safe mask overlay failed:",s),null}},av=e=>{const t=yh(e);if(!t)return null;const n=document.createElement("canvas");n.width=t.width,n.height=t.height;const r=n.getContext("2d");if(!r)return null;const s=r.createImageData(t.width,t.height),i=s.data;for(let o=0;o{const[n,r]=$.useState(!1),[s,i]=$.useState(!1),[o,a]=$.useState(null),l=$.useRef(null),c=async w=>{if(a(null),!sv(w)){a("Please select a valid image file (JPEG, PNG, WebP) under 10MB.");return}i(!0);try{const k=await rv(w);e(k)}catch{a("Failed to process the image. Please try again.")}finally{i(!1)}},g=w=>{var f;const k=(f=w.target.files)==null?void 0:f[0];k&&c(k)},h=w=>{w.preventDefault(),r(!0)},m=w=>{w.preventDefault(),r(!1)},y=w=>{w.preventDefault(),r(!1);const k=w.dataTransfer.files[0];k&&c(k)},x=()=>{var w;(w=l.current)==null||w.click()};return u.jsxs("div",{className:"image-upload",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Upload Image"}),u.jsx("p",{children:"Upload an image from your computer that you want to edit with AI."})]}),u.jsxs("div",{className:`upload-area ${n?"dragging":""} ${s?"processing":""}`,onDragOver:h,onDragLeave:m,onDrop:y,onClick:s?void 0:x,style:{cursor:s?"not-allowed":"pointer"},children:[u.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:g,style:{display:"none"},disabled:s}),s?u.jsxs("div",{className:"upload-processing",children:[u.jsx("div",{className:"spinner"}),u.jsx("p",{children:"Processing image..."}),u.jsx("small",{style:{color:"var(--muted)",marginTop:"var(--space-2)"},children:"Optimizing for AI processing"})]}):u.jsxs("div",{className:"upload-content",children:[u.jsx("div",{className:"upload-icon",children:u.jsxs("svg",{width:"48",height:"48",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[u.jsx("path",{d:"M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"}),u.jsx("polyline",{points:"17 8 12 3 7 8"}),u.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),u.jsx("h3",{children:"Drop image here or click to browse"}),u.jsx("p",{children:"Choose an image file from your computer"}),u.jsxs("div",{className:"upload-requirements",children:[u.jsx("small",{children:"Supported formats: JPEG, PNG, WebP"}),u.jsx("small",{children:"Maximum size: 10MB"})]})]})]}),o&&u.jsxs("div",{className:"error-message",children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginRight:"var(--space-2)",flexShrink:0},children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),u.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),o]}),u.jsx("div",{className:"step-actions",children:u.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:t,disabled:s,children:[u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:u.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back"]})})]})},uv=({onModeSelect:e,onBack:t,originalImage:n,maskData:r})=>{const s=$.useRef(null),[i,o]=$.useState(null);return $.useEffect(()=>{if(n&&r){const a=s.current;if(!a)return;const l=a.getContext("2d");if(!l)return;const c=new Image,g=new Image;let h=0;const m=()=>{h++,h===2&&(a.width=c.width,a.height=c.height,l.drawImage(c,0,0),l.globalAlpha=.5,l.drawImage(g,0,0),l.globalAlpha=1,o(a.toDataURL()))};c.onload=m,g.onload=m,c.src=n,g.src=r}else o(null)},[n,r]),u.jsxs("div",{className:"edit-mode-selector",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Choose Editing Mode"}),u.jsx("p",{children:"Select how you want to edit your image with AI assistance."})]}),n&&u.jsx("div",{className:"image-preview",style:{marginBottom:"var(--space-6)",textAlign:"center"},children:u.jsx("img",{src:i||n,alt:i?"Original with Mask":"Original",className:"compact-preview-image",style:{maxWidth:"300px",maxHeight:"200px",objectFit:"contain"}})}),u.jsx("canvas",{ref:s,style:{display:"none"}}),u.jsx("div",{className:"edit-mode-selection",children:u.jsxs("div",{className:"edit-mode-options",children:[u.jsxs("div",{className:"edit-mode-option",onClick:()=>e("full"),children:[u.jsx("div",{style:{fontSize:"24px",marginBottom:"var(--space-3)",color:"var(--muted)"},children:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[u.jsx("path",{d:"M21 16V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2h14a2 2 0 002-2z"}),u.jsx("path",{d:"M16 12h-4l-2-2-2 2h4v4"})]})}),u.jsx("h3",{children:"Full Edit"}),u.jsx("p",{children:"Apply changes to the entire image"}),u.jsx("div",{className:"mode-features",children:u.jsx("small",{children:"Best for overall style changes • Color adjustments • Global effects"})})]}),u.jsxs("div",{className:"edit-mode-option",onClick:()=>e("inpaint"),children:[u.jsx("div",{style:{fontSize:"24px",marginBottom:"var(--space-3)",color:"var(--muted)"},children:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[u.jsx("path",{d:"M9 7H6a2 2 0 00-2 2v9a2 2 0 002 2h9a2 2 0 002-2v-3"}),u.jsx("path",{d:"M9 15h3l8.5-8.5a2.12 2.12 0 00-3-3L9 12v3z"}),u.jsx("path",{d:"M16 5l3 3"})]})}),u.jsx("h3",{children:"Inpaint Mode"}),u.jsx("p",{children:"Edit only specific areas you select"}),u.jsx("div",{className:"mode-features",children:u.jsx("small",{children:"Best for object removal • Adding elements • Selective changes"})})]})]})}),u.jsx("div",{className:"step-actions",children:u.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:t,children:[u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:u.jsx("path",{d:"m15 18-6-6 6-6"})}),"Back"]})})]})},cv=({originalImage:e,onMaskCreated:t,onBack:n})=>{const r=$.useRef(null),s=$.useRef(null),i=$.useRef(null),[o,a]=$.useState(!1),[l,c]=$.useState(30),[g,h]=$.useState("paint"),[m,y]=$.useState(!1),[x,w]=$.useState({width:0,height:0}),[k,f]=$.useState({width:0,height:0}),[d,p]=$.useState(null);$.useEffect(()=>{const P=s.current,b=i.current,T=r.current;if(!P||!b||!T)return;const R=P.getContext("2d"),U=b.getContext("2d");if(!R||!U)return;const Y=new Image;Y.onload=()=>{w({width:Y.width,height:Y.height});const ee=T.getBoundingClientRect(),A=Math.min(800,ee.width-40),D=600,F=Y.width/Y.height;let K=A,V=A/F;V>D&&(V=D,K=D*F),P.width=K,P.height=V,P.style.width=`${K}px`,P.style.height=`${V}px`,b.width=K,b.height=V,b.style.width=`${K}px`,b.style.height=`${V}px`,f({width:K,height:V}),R.drawImage(Y,0,0,K,V),U.lineCap="round",U.lineJoin="round",y(!0)},Y.onerror=()=>{console.error("Failed to load image for mask editor")},Y.src=e},[e]);const v=P=>{const b=i.current;if(!b)return null;const T=b.getBoundingClientRect();let R,U;if("touches"in P&&P.touches.length>0)R=P.touches[0].clientX,U=P.touches[0].clientY;else if("clientX"in P)R=P.clientX,U=P.clientY;else return null;return{x:R-T.left,y:U-T.top}},E=(P,b)=>{const T=i.current,R=T==null?void 0:T.getContext("2d");R&&(R.save(),g==="paint"?(R.globalCompositeOperation="source-over",R.strokeStyle="rgb(255, 0, 0)",R.lineWidth=l):(R.globalCompositeOperation="destination-out",R.lineWidth=l),R.beginPath(),R.moveTo(P.x,P.y),R.lineTo(b.x,b.y),R.stroke(),R.restore())},_=P=>{P.preventDefault();const b=v(P);if(!b)return;a(!0),p(b);const T=i.current,R=T==null?void 0:T.getContext("2d");R&&(R.save(),g==="paint"?(R.globalCompositeOperation="source-over",R.fillStyle="rgb(255, 0, 0)"):R.globalCompositeOperation="destination-out",R.beginPath(),R.arc(b.x,b.y,l/2,0,Math.PI*2),R.fill(),R.restore())},C=P=>{if(P.preventDefault(),!o||!d)return;const b=v(P);b&&(E(d,b),p(b))},I=()=>{a(!1),p(null)},O=()=>{const P=i.current,b=P==null?void 0:P.getContext("2d");!b||!P||!m||b.clearRect(0,0,P.width,P.height)},j=()=>{const P=i.current;if(!P)return;const b=document.createElement("canvas");b.width=x.width,b.height=x.height;const T=b.getContext("2d");if(!T)return;T.drawImage(P,0,0,x.width,x.height);const R=T.getImageData(0,0,x.width,x.height),U=[];let Y=0,ee=0;for(let F=0;F200&&V<100&&We<100&&He>0?1:0;et===Y?ee++:(U.push(ee),Y=et,ee=1)}U.push(ee);const A={width:x.width,height:x.height,runs:U},D=`MASK:${A.width}x${A.height}:${A.runs.join(",")}`;t(D)};return u.jsxs("div",{className:"mask-editor-new",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Create Mask"}),u.jsx("p",{children:"Paint over the areas you want to edit. Red areas will be modified by AI."})]}),u.jsxs("div",{className:"mask-editor-workspace",children:[u.jsxs("div",{className:"canvas-container",ref:r,children:[!m&&u.jsxs("div",{className:"canvas-loading",children:[u.jsx("div",{className:"spinner"}),u.jsx("p",{children:"Loading image..."})]}),u.jsx("canvas",{ref:s,className:`mask-canvas-base ${m?"loaded":""}`,style:{position:"absolute",zIndex:1}}),u.jsx("canvas",{ref:i,className:`mask-canvas-overlay ${m?"loaded":""}`,onMouseDown:_,onMouseMove:C,onMouseUp:I,onMouseLeave:I,onTouchStart:_,onTouchMove:C,onTouchEnd:I,style:{cursor:g==="paint"?"crosshair":"copy",touchAction:"none",position:"absolute",zIndex:2}})]}),u.jsxs("div",{className:"mask-toolbar",children:[u.jsxs("div",{className:"toolbar-section",children:[u.jsx("div",{className:"toolbar-title",children:"Tools"}),u.jsxs("div",{className:"tool-buttons-new",children:[u.jsxs("button",{className:`tool-btn-new ${g==="paint"?"active":""}`,onClick:()=>h("paint"),children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08"}),u.jsx("path",{d:"m7.07 14.94-1.13 1.13a3 3 0 0 1-4.24 0l-1.06-1.06a3 3 0 0 1 0-4.24l1.13-1.13"})]}),"Paint"]}),u.jsxs("button",{className:`tool-btn-new ${g==="erase"?"active":""}`,onClick:()=>h("erase"),children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21"}),u.jsx("path",{d:"M22 21H7"}),u.jsx("path",{d:"m5 11 9 9"})]}),"Erase"]})]})]}),u.jsxs("div",{className:"toolbar-section",children:[u.jsxs("div",{className:"toolbar-title",children:["Brush Size: ",l,"px"]}),u.jsx("input",{type:"range",min:"5",max:"80",value:l,onChange:P=>c(parseInt(P.target.value)),className:"brush-slider-new"})]}),u.jsx("div",{className:"toolbar-section",children:u.jsxs("button",{className:"btn btn-secondary btn-small",onClick:O,disabled:!m,children:[u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 6h18"}),u.jsx("path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6"}),u.jsx("path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2"})]}),"Clear All"]})})]}),u.jsxs("div",{className:"mask-instructions",children:[u.jsxs("div",{className:"instruction-item",children:[u.jsx("div",{className:"instruction-icon paint",children:"●"}),u.jsx("span",{children:"Paint red areas over parts you want to edit"})]}),u.jsxs("div",{className:"instruction-item",children:[u.jsx("div",{className:"instruction-icon erase",children:"◌"}),u.jsx("span",{children:"Use eraser to remove painted areas (not the image)"})]}),u.jsxs("div",{className:"instruction-item",children:[u.jsx("div",{className:"instruction-icon tip",children:"💡"}),u.jsx("span",{children:"Only red areas will be modified by AI"})]})]})]}),u.jsxs("div",{className:"step-actions",children:[u.jsxs("button",{className:"btn btn-secondary",onClick:n,children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M19 12H5"}),u.jsx("path",{d:"M12 19l-7-7 7-7"})]}),"Back"]}),u.jsxs("button",{className:"btn btn-primary",onClick:j,disabled:!m,children:["Continue",u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M5 12h14"}),u.jsx("path",{d:"M12 5l7 7-7 7"})]})]})]})]})},dv=({onSubmit:e,onBack:t,originalImage:n,editMode:r="full",maskData:s,actions:i})=>{const[o,a]=$.useState(""),[l,c]=$.useState(null),[g,h]=$.useState(null),[m,y]=$.useState(!1),[x,w]=$.useState(!1),[k,f]=$.useState(!1),[d,p]=$.useState(null);$.useEffect(()=>{r==="inpaint"&&n&&s?(console.log("PromptInput: Creating mask overlay..."),console.log("Mask data type:",s.startsWith("MASK:")?"compact":"data URL"),console.log("Mask data length:",s.length),y(!0),vh(n,s).then(T=>{console.log("PromptInput: Mask overlay created successfully:",!!T),h(T)}).catch(T=>{console.error("PromptInput: Failed to create mask overlay:",T),h(null)}).finally(()=>{y(!1)})):(h(null),y(!1))},[n,s,r]),$.useEffect(()=>{const T=R=>{const U=R.target;x&&!U.closest(".ai-enhance-container")&&w(!1)};if(x)return document.addEventListener("mousedown",T),()=>document.removeEventListener("mousedown",T)},[x]);const v=T=>{T.preventDefault();const R=o.trim();if(!R){c("Please enter a description of what you want to create or change.");return}if(R.length<10){c("Please provide a more detailed description (at least 10 characters).");return}c(null),e(R)},E=()=>{switch(r){case"generate":return"Describe Your Image";case"inpaint":return"Describe Your Edit";default:return"Describe Your Changes"}},_=()=>{switch(r){case"generate":return"What image do you want to create?";case"inpaint":return"How should the highlighted areas be modified?";default:return"How do you want to transform your image?"}},C=()=>{switch(r){case"generate":return"A majestic mountain landscape at sunset...";case"inpaint":return"Replace with a beautiful garden...";default:return"Make the colors more vibrant..."}},I=r==="generate"?["A serene mountain lake at golden hour with perfect reflections","A cozy modern living room with warm lighting and plants","A futuristic cityscape with flying cars and neon lights","A magical forest clearing with glowing fireflies at dusk","A vintage bookstore with wooden shelves and reading nooks","An underwater coral reef scene with tropical fish"]:r==="inpaint"?["Replace with a beautiful sunset sky","Add a person sitting in this area","Fill with lush green grass and flowers","Change to a modern glass building","Remove the object completely","Add floating balloons in the sky"]:["Transform into a vintage sepia photograph","Make the lighting dramatic and moody","Add vibrant sunset colors to the sky","Convert to a minimalist black and white style","Enhance with soft romantic lighting","Apply a magical fantasy atmosphere"],O=T=>{a(T),c(null)},j=async T=>{if(!o.trim()||!i){p("Please enter some text first");return}f(!0),p(null);try{let R="";switch(T){case"prompt":R=`Convert this into a command starting with "generate an image of". Focus on concrete objects, colors, lighting, composition, style. Avoid stories, emotions, abstract concepts. Keep it under 50 words: "${o}"`;break;case"complete":R=`Complete this text as a command starting with "generate an image of": "${o}"`;break;case"shorten":R=`Make this shorter and more concise, starting with "generate an image of": "${o}"`;break;case"extend":R=`Add specific visual details while keeping it as a command starting with "generate an image of". Include materials, textures, lighting, camera angle, artistic style. Keep under 60 words: "${o}"`;break;case"rephrase":R=`Rephrase this as a clear command starting with "generate an image of". Use visual, concrete terms. Keep it concise: "${o}"`;break;case"summarize":R=`Summarize this as a command starting with "generate an image of": "${o}"`;break;case"simplify":R=`Simplify this into a clear command starting with "generate an image of": "${o}"`;break;case"translate":R=`Translate this to English (if needed) and format as a command starting with "generate an image of": "${o}"`;break;case"tldr":R=`Create a brief command starting with "generate an image of" that captures the key elements of: "${o}"`;break;case"adjust-tone":R=`Convert this into a professional command starting with "generate an image of". Focus on visual elements, composition, lighting style: "${o}"`;break;case"emojify":R=`Add relevant emojis while keeping it as a command starting with "generate an image of": "${o}"`;break;case"fix_spelling_and_grammar":R=`Fix spelling and grammar while formatting as a command starting with "generate an image of": "${o}"`;break;default:R=`Improve this text as a command starting with "generate an image of": "${o}"`}const U=await i.promptAI({action:"prompt",basedOnCurrentStory:!1,text:R});U&&U.ok&&U.answer?(a(U.answer),c(null)):p("AI enhancement failed to return a result")}catch(R){p((R==null?void 0:R.message)||"Enhancement failed")}finally{f(!1),w(!1)}},P=T=>({prompt:"Make More Descriptive",complete:"Complete Text",shorten:"Make Shorter",extend:"Add More Details",rephrase:"Rephrase",summarize:"Summarize",simplify:"Simplify",translate:"Translate",tldr:"TLDR","adjust-tone":"Adjust Tone",emojify:"Add Emojis",fix_spelling_and_grammar:"Fix Grammar"})[T],b=()=>r==="generate"?null:r==="inpaint"?u.jsx("div",{className:"preview-container",children:m?u.jsxs("div",{className:"preview-loading",children:[u.jsx("div",{className:"spinner",style:{width:"20px",height:"20px"}}),u.jsx("span",{children:"Preparing preview..."})]}):g?u.jsxs(u.Fragment,{children:[u.jsx("img",{src:g,alt:"Image with mask overlay",className:"compact-preview-image"}),u.jsx("small",{className:"preview-help",children:"Red areas will be edited by AI"})]}):n?u.jsxs(u.Fragment,{children:[u.jsxs("div",{className:"preview-fallback",children:[u.jsx("img",{src:n,alt:"Original",className:"compact-preview-image"}),u.jsx("div",{className:"preview-overlay",children:u.jsx("span",{children:"Mask preview unavailable"})})]}),u.jsx("small",{className:"preview-help",children:"Selected areas will be edited by AI"})]}):null}):n?u.jsx("div",{className:"preview-container",children:u.jsx("img",{src:n,alt:"Original",className:"compact-preview-image"})}):null;return u.jsxs("div",{className:"prompt-input",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:E()}),u.jsx("p",{children:_()})]}),r!=="generate"&&u.jsx("div",{className:"compact-image-preview",children:b()}),u.jsxs("form",{onSubmit:v,className:"prompt-form",children:[u.jsxs("div",{className:"form-group",children:[u.jsxs("div",{className:"form-label-with-actions",children:[u.jsxs("label",{htmlFor:"prompt",className:"form-label",children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",style:{marginRight:"var(--space-2)"},children:[u.jsx("path",{d:"M12 20h9"}),u.jsx("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),"Prompt"]}),i&&u.jsxs("div",{className:"ai-enhance-container",children:[u.jsx("button",{type:"button",className:"ai-enhance-btn",onClick:()=>w(!x),disabled:k,children:k?u.jsxs(u.Fragment,{children:[u.jsx("div",{className:"spinner"}),"Enhancing..."]}):u.jsxs(u.Fragment,{children:[u.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:u.jsx("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"})}),"AI Enhance"]})}),x&&u.jsxs("div",{className:"ai-enhance-dropdown",children:[u.jsxs("div",{className:"dropdown-header",children:[u.jsx("h4",{children:"AI Enhancement"}),u.jsx("p",{children:"Uses your page content as context to create more relevant prompts"})]}),u.jsx("div",{className:"dropdown-actions",children:["prompt","extend","rephrase","simplify","adjust-tone","complete","shorten","summarize","fix_spelling_and_grammar"].map(T=>u.jsx("button",{type:"button",className:"dropdown-action",onClick:()=>j(T),children:P(T)},T))})]})]})]}),u.jsxs("div",{className:"textarea-container",children:[u.jsx("textarea",{id:"prompt",value:o,onChange:T=>a(T.target.value),placeholder:C(),className:"form-textarea",rows:4}),k&&u.jsx("div",{className:"textarea-overlay",children:u.jsxs("div",{className:"enhancement-loader",children:[u.jsx("div",{className:"spinner"}),u.jsx("span",{children:"Enhancing prompt..."})]})})]}),u.jsxs("div",{className:"textarea-footer",children:[u.jsxs("div",{className:"character-count",children:[o.length," characters"]}),d&&u.jsx("div",{className:"enhancement-error",children:d})]})]}),l&&u.jsx("div",{className:"error-message",children:l}),u.jsxs("div",{className:"step-actions",children:[u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:t,children:"Back"}),u.jsx("button",{type:"submit",className:"btn btn-primary",disabled:!o.trim(),children:r==="generate"?"Generate Image":"Process Image"})]})]}),u.jsxs("div",{className:"example-prompts",children:[u.jsx("h4",{children:"Example prompts:"}),u.jsx("div",{className:"examples-grid",children:I.map((T,R)=>u.jsx("button",{type:"button",className:"example-prompt",onClick:()=>O(T),children:T},R))})]})]})},fv=({originalImage:e,isProcessing:t,editMode:n,processedImage:r,partialImage:s,partialIndex:i,streamingProgress:o,maskData:a,status:l,onRetry:c,onCancel:g})=>{const[h,m]=$.useState(null),[y,x]=$.useState(!1);$.useEffect(()=>{n==="inpaint"&&e&&a&&!r?(console.log("ImageProcessor: Creating mask overlay..."),console.log("Mask data type:",a.startsWith("MASK:")?"compact":"data URL"),console.log("Mask data length:",a.length),x(!0),vh(e,a).then(E=>{console.log("ImageProcessor: Mask overlay created successfully:",!!E),m(E)}).catch(E=>{console.error("ImageProcessor: Failed to create mask overlay:",E),m(null)}).finally(()=>{x(!1)})):(m(null),x(!1))},[e,a,n,r]);const w=()=>r||(s&&t?s:n==="inpaint"&&h?h:e||null),k=()=>r?"Processed image":s&&t?`Generating image... (${i||0}/2)`:n==="inpaint"&&h?"Original image with editing mask":e?"Original image":"Image",f=()=>l?l.startsWith('Processing: "')?"Processing your image...":l:n==="generate"?"Generating your image...":n==="inpaint"?"Processing selected areas...":"Processing your image...",d=()=>{if(l&&l.startsWith('Processing: "')){const E=l.match(/Processing: "(.+)"/);return E?E[1]:null}return null},p=()=>null,v=w();return!v&&!y?u.jsx("div",{className:"image-processor processing",children:u.jsx("div",{className:"processing-container",children:u.jsxs("div",{className:"processing-content",children:[u.jsx("div",{className:"loading-spinner",children:u.jsx("div",{className:"spinner"})}),u.jsx("h3",{children:n==="generate"?"Creating Image":"Processing Image"}),u.jsx("p",{className:"processing-status",children:f()}),u.jsx("div",{className:"processing-actions",children:u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:g,children:"Cancel"})})]})})}):u.jsxs("div",{className:"image-processor",children:[u.jsxs("div",{className:"processor-header",children:[u.jsx("h2",{children:r?"Image Complete!":n==="generate"?"Creating Image":"Processing Image"}),u.jsxs("div",{children:[u.jsx("p",{children:r?"Your image has been processed successfully.":f()}),d()&&u.jsx("div",{className:"prompt-display",children:u.jsx("div",{className:"prompt-text",children:d()})})]})]}),u.jsxs("div",{className:"processor-content",children:[u.jsx("div",{className:"image-container",children:y?u.jsxs("div",{className:"image-loading",children:[u.jsx("div",{className:"spinner",style:{width:"24px",height:"24px"}}),u.jsx("span",{children:"Preparing preview..."})]}):v?u.jsxs(u.Fragment,{children:[u.jsx("img",{src:v,alt:k(),className:"processing-image"}),p()]}):u.jsx("div",{className:"image-placeholder",children:u.jsx("span",{children:"No image available"})})}),t&&!r&&!s&&u.jsx("div",{className:"processing-overlay",children:u.jsxs("div",{className:"processing-indicator",children:[u.jsx("div",{className:"spinner"}),u.jsx("span",{className:"processing-text",children:f()})]})}),t&&!r&&s&&u.jsx("div",{className:"streaming-overlay",children:u.jsx("div",{className:"streaming-indicator",children:u.jsxs("div",{className:"streaming-info",children:[u.jsxs("small",{children:["Generating... ",i||0,"/2"]}),o&&u.jsx("div",{className:"progress-bar",children:u.jsx("div",{className:"progress-fill",style:{width:`${o}%`}})})]})})})]}),u.jsx("div",{className:"processor-actions",children:r?u.jsx("div",{className:"success-actions",children:u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:c,children:"Try Again"})}):u.jsx("div",{className:"processing-actions",children:u.jsx("button",{type:"button",className:"btn btn-secondary",onClick:g,children:"Cancel"})})})]})},hv=({versions:e,onRestore:t})=>{const n=a=>{const l=new Date(a),g=new Date().getTime()-l.getTime(),h=Math.floor(g/(1e3*60)),m=Math.floor(g/(1e3*60*60)),y=Math.floor(g/(1e3*60*60*24));return h<60?h<=1?"Just now":`${h} minutes ago`:m<24?m===1?"1 hour ago":`${m} hours ago`:y<7?y===1?"1 day ago":`${y} days ago`:l.toLocaleDateString()},r=a=>a.length>60?a.substring(0,60)+"...":a,s=a=>{switch(a){case"generate":return u.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:u.jsx("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"})});case"inpaint":return u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M9 7H6a2 2 0 00-2 2v9a2 2 0 002 2h9a2 2 0 002-2v-3"}),u.jsx("path",{d:"M9 15h3l8.5-8.5a2.12 2.12 0 00-3-3L9 12v3z"}),u.jsx("path",{d:"M16 5l3 3"})]});default:return u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M21 16V8a2 2 0 00-2-2H5a2 2 0 00-2 2v8a2 2 0 002 2h14a2 2 0 002-2z"}),u.jsx("path",{d:"M16 12h-4l-2-2-2 2h4v4"})]})}},i=a=>{switch(a){case"generate":return"Generated";case"inpaint":return"Inpaint";case"full":return"Full Edit";default:return"Edit"}},o=[...e].sort((a,l)=>l.timestamp-a.timestamp);return e.length===0?null:u.jsx("div",{className:"version-history-panel",children:u.jsx("ul",{className:"version-list",children:o.map((a,l)=>u.jsxs("li",{className:"version-item",children:[u.jsx("img",{src:a.imageUrl,alt:`Version ${l+1}`,className:"version-thumbnail"}),u.jsxs("div",{className:"version-info",children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)",marginBottom:"var(--space-1)"},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--space-1)",color:"var(--muted)"},children:[s(a.editMode),u.jsx("span",{style:{fontSize:"var(--text-xs)",fontWeight:"500"},children:i(a.editMode)})]}),u.jsx("div",{style:{fontSize:"var(--text-xs)",color:"var(--muted-light)"},children:n(a.timestamp)})]}),u.jsxs("div",{className:"version-prompt",children:['"',r(a.prompt),'"']}),a.altText&&u.jsx("div",{style:{fontSize:"var(--text-xs)",color:"var(--muted-light)",marginTop:"var(--space-1)",fontStyle:"italic"},children:a.altText.length>40?a.altText.substring(0,40)+"...":a.altText})]}),u.jsx("button",{className:"action-btn-icon",onClick:()=>t(a),title:"Restore this version",children:u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 12a9 9 0 10.9-4"}),u.jsx("path",{d:"M21 12a9 9 0 10-.9 4"}),u.jsx("path",{d:"M8 12l4-4 4 4"})]})})]},a.timestamp))})})},pv=({originalImage:e,editedImage:t,prompt:n,altText:r,editMode:s,maskData:i,onSaveToStoryblok:o,onStartOver:a,isSaving:l,isGeneratingAltText:c,versions:g,onRestoreVersion:h})=>{const[m,y]=$.useState("edited"),[x,w]=$.useState(!1),k=$.useRef(null);$.useEffect(()=>{if(m==="mask"&&s==="inpaint"&&e&&i&&k.current){const p=k.current,v=p.getContext("2d");if(!v)return;const E=new Image,_=new Image;let C=0;const I=()=>{if(C++,C===2){p.width=E.width,p.height=E.height,v.drawImage(E,0,0),v.globalCompositeOperation="source-over",v.fillStyle="rgba(255, 0, 0, 0.4)";const O=document.createElement("canvas");O.width=_.width,O.height=_.height;const j=O.getContext("2d");if(!j)return;j.drawImage(_,0,0);const b=j.getImageData(0,0,_.width,_.height).data;for(let T=0;T<_.height;T++)for(let R=0;R<_.width;R++){const U=(T*_.width+R)*4,Y=b[U],ee=b[U+1],A=b[U+2],D=b[U+3];Y>200&&ee>200&&A>200&&D>0&&v.fillRect(R,T,1,1)}}};E.onload=I,_.onload=I,E.src=e,_.src=i}},[e,i,s,m]);const f=()=>{if(s==="generate")return"Generated";switch(m){case"edited":return"Edited";case"original":return"Original";case"mask":return"Mask";default:return"Edited"}},d=()=>s==="full"?"Full Edit":s==="inpaint"?"Inpaint Edit":"Generated from text";return u.jsxs("div",{className:"image-preview-container",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Preview Result"}),u.jsx("p",{children:"Your AI-processed image is ready. Save it to Storyblok or create another version."})]}),u.jsx("div",{className:"image-preview-main",children:u.jsxs("div",{className:"image-preview-fullscreen",children:[u.jsxs("div",{className:"fullscreen-image-container",children:[(s==="generate"||m==="edited")&&t&&u.jsx("img",{src:t,alt:"Edited",className:"fullscreen-image"}),s!=="generate"&&m==="original"&&e&&u.jsx("img",{src:e,alt:"Original",className:"fullscreen-image"}),s==="inpaint"&&m==="mask"&&u.jsx("canvas",{ref:k,className:"fullscreen-image"})]}),u.jsxs("div",{className:"overlay-top",children:[u.jsx("div",{className:"app-badge",children:"BlockArt"}),u.jsx("div",{className:"status-badge",children:f()})]}),u.jsxs("div",{className:"overlay-bottom",children:[s!=="generate"&&u.jsxs("div",{className:"comparison-controls",children:[u.jsx("button",{className:`comparison-btn ${m==="edited"?"active":""}`,onClick:()=>y("edited"),children:"Edited"}),u.jsx("button",{className:`comparison-btn ${m==="original"?"active":""}`,onClick:()=>y("original"),children:"Original"})]}),u.jsx("div",{className:"primary-actions",children:u.jsx("button",{className:"action-btn primary",onClick:o,disabled:l,children:l?u.jsxs(u.Fragment,{children:[u.jsx("span",{className:"spinner",style:{width:"14px",height:"14px"}}),"Saving..."]}):u.jsxs(u.Fragment,{children:[u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"}),u.jsx("polyline",{points:"17 8 12 3 7 8"}),u.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]}),"Save to Storyblok"]})})})]})]})}),u.jsx("div",{style:{background:"var(--surface)",border:"1px solid var(--border-light)",borderRadius:"var(--radius)",padding:"var(--space-4)",marginTop:"var(--space-4)"},children:u.jsxs("div",{style:{display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(200px, 1fr))",gap:"var(--space-4)"},children:[u.jsxs("div",{children:[u.jsx("div",{style:{fontSize:"var(--text-xs)",fontWeight:"600",color:"var(--muted)",marginBottom:"var(--space-1)",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Method"}),u.jsx("div",{style:{fontSize:"var(--text-sm)",fontWeight:"500",color:"var(--stone-800)"},children:d()})]}),u.jsxs("div",{children:[u.jsx("div",{style:{fontSize:"var(--text-xs)",fontWeight:"600",color:"var(--muted)",marginBottom:"var(--space-1)",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Prompt"}),u.jsxs("div",{style:{fontSize:"var(--text-sm)",color:"var(--stone-700)",lineHeight:"1.4"},children:['"',n,'"']})]}),u.jsxs("div",{children:[u.jsx("div",{style:{fontSize:"var(--text-xs)",fontWeight:"600",color:"var(--muted)",marginBottom:"var(--space-1)",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Alt Text"}),u.jsx("div",{style:{fontSize:"var(--text-sm)",color:"var(--stone-700)",lineHeight:"1.4"},children:c?u.jsxs("div",{style:{display:"flex",alignItems:"center",gap:"var(--space-2)"},children:[u.jsx("span",{className:"spinner",style:{width:"12px",height:"12px"}}),u.jsx("span",{style:{color:"var(--muted)"},children:"Generating alt text..."})]}):r||u.jsx("span",{style:{color:"var(--muted)"},children:"No alt text available"})})]})]})}),g.length>0&&u.jsxs("div",{style:{marginTop:"var(--space-6)"},children:[u.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:"var(--space-4)"},children:[u.jsx("h3",{style:{margin:0,fontSize:"var(--text-lg)",fontWeight:"600",color:"var(--stone-900)"},children:"Version History"}),u.jsxs("button",{className:"btn btn-small btn-secondary",onClick:()=>w(!x),children:[u.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 12a9 9 0 10.9-4"}),u.jsx("path",{d:"M21 12a9 9 0 10-.9 4"}),u.jsx("path",{d:"M8 12l4-4 4 4"})]}),x?"Hide":"Show"," (",g.length,")"]})]}),x&&u.jsx(hv,{versions:g,onRestore:h})]}),u.jsx("div",{className:"step-actions",children:u.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:a,disabled:l,children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 12a9 9 0 01.9-4M21 12a9 9 0 01-.9 4"}),u.jsx("path",{d:"M8 12l4-4 4 4"})]}),"Start Over"]})})]})},mv=({error:e,onStartOver:t,onRetry:n,showRetry:r=!1})=>{const i=(o=>o.includes("Content policy rejection")?{title:"Content Policy Restriction",icon:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("path",{d:"M4.93 4.93l14.14 14.14"})]}),message:o.replace("Content policy rejection: ",""),suggestions:["Try rephrasing your prompt with more appropriate language","Avoid requesting content involving people, violence, or adult themes","Use general descriptions rather than specific instructions","Focus on objects, landscapes, or abstract concepts"]}:o.includes("API key")?{title:"API Key Issue",icon:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M12 1a3 3 0 003 3 3 3 0 003 3 3 3 0 00-3 3 3 3 0 00-3 3 3 3 0 00-3-3 3 3 0 00-3-3 3 3 0 003-3 3 3 0 003-3z"}),u.jsx("path",{d:"M9 21H5a2 2 0 01-2-2v-4l6-6 2-2 3-3"})]}),message:o,suggestions:["Check that your OpenAI API key is valid","Ensure you have sufficient credits","Verify your organization has access to image generation"]}:o.includes("Failed to upload mask")?{title:"Mask Upload Failed",icon:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"}),u.jsx("polyline",{points:"17 8 12 3 7 8"}),u.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"}),u.jsx("line",{x1:"8",y1:"8",x2:"16",y2:"16"})]}),message:"There was an issue uploading your mask for inpainting",suggestions:["Try creating a simpler mask with fewer details","Ensure your internet connection is stable","Check that your mask has clear white areas"]}:o.includes("No final image generated")?{title:"Generation Incomplete",icon:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("polyline",{points:"10,6 10,12 14,16"}),u.jsx("line",{x1:"16",y1:"8",x2:"8",y2:"16"})]}),message:"The image generation process was interrupted",suggestions:["Check your internet connection","Try a simpler prompt","Ensure your API key has sufficient credits"]}:{title:"Processing Error",icon:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"}),u.jsx("line",{x1:"12",y1:"9",x2:"12",y2:"13"}),u.jsx("line",{x1:"12",y1:"17",x2:"12.01",y2:"17"})]}),message:o,suggestions:["Check your internet connection","Try again with a different prompt","Ensure your API key is valid and has credits"]})(e);return u.jsxs("div",{className:"error-display",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Something went wrong"}),u.jsx("p",{children:"We encountered an issue while processing your request."})]}),u.jsxs("div",{style:{background:"var(--surface)",border:"1px solid var(--border)",borderRadius:"var(--radius-md)",padding:"var(--space-6)",marginBottom:"var(--space-6)"},children:[u.jsxs("div",{style:{display:"flex",gap:"var(--space-4)",marginBottom:"var(--space-4)"},children:[u.jsx("div",{style:{color:"var(--accent-red)",flexShrink:0},children:i.icon}),u.jsxs("div",{style:{flex:1},children:[u.jsx("h3",{style:{margin:"0 0 var(--space-2) 0",fontSize:"var(--text-lg)",fontWeight:"600",color:"var(--stone-900)"},children:i.title}),u.jsx("p",{style:{margin:0,fontSize:"var(--text-base)",color:"var(--stone-700)",lineHeight:"1.5"},children:i.message})]})]}),u.jsxs("div",{style:{marginBottom:"var(--space-4)"},children:[u.jsxs("h4",{style:{margin:"0 0 var(--space-3) 0",fontSize:"var(--text-sm)",fontWeight:"600",color:"var(--stone-800)",display:"flex",alignItems:"center",gap:"var(--space-2)"},children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3"}),u.jsx("path",{d:"M12 17h.01"})]}),"What you can try:"]}),u.jsx("ul",{style:{margin:0,paddingLeft:"var(--space-5)",color:"var(--stone-700)",fontSize:"var(--text-sm)",lineHeight:"1.5"},children:i.suggestions.map((o,a)=>u.jsx("li",{style:{marginBottom:"var(--space-1)"},children:o},a))})]}),u.jsxs("details",{style:{padding:"var(--space-3)",background:"var(--stone-50)",borderRadius:"var(--radius)",fontSize:"var(--text-sm)"},children:[u.jsx("summary",{style:{cursor:"pointer",fontWeight:"500",color:"var(--stone-700)",marginBottom:"var(--space-2)"},children:"Technical Details"}),u.jsx("pre",{style:{margin:0,fontFamily:"monospace",fontSize:"var(--text-xs)",color:"var(--stone-600)",whiteSpace:"pre-wrap",wordWrap:"break-word"},children:e})]})]}),u.jsxs("div",{className:"step-actions",children:[r&&n&&u.jsxs("button",{type:"button",className:"btn btn-secondary",onClick:n,children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 12a9 9 0 10.9-4"}),u.jsx("path",{d:"M21 12a9 9 0 10-.9 4"}),u.jsx("path",{d:"M8 12l4-4 4 4"})]}),"Try Again"]}),u.jsxs("button",{type:"button",className:"btn btn-primary",onClick:t,children:[u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M3 12a9 9 0 01.9-4M21 12a9 9 0 01-.9 4"}),u.jsx("path",{d:"M8 12l4-4 4 4"})]}),"Start Over"]})]})]})};function W(e,t,n,r,s){if(typeof t=="function"?e!==t||!0:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,n),n}function S(e,t,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?e!==t||!r:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(e):r?r.value:t.get(e)}let wh=function(){const{crypto:e}=globalThis;if(e!=null&&e.randomUUID)return wh=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function Fa(e){return typeof e=="object"&&e!==null&&("name"in e&&e.name==="AbortError"||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const Da=e=>{if(e instanceof Error)return e;if(typeof e=="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class B extends Error{}class Ee extends B{constructor(t,n,r,s){super(`${Ee.makeMessage(t,n,r)}`),this.status=t,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=n;const i=n;this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(t,n,r){const s=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return t&&s?`${t} ${s}`:t?`${t} status code (no body)`:s||"(no status code or body)"}static generate(t,n,r,s){if(!t||!s)return new to({message:r,cause:Da(n)});const i=n==null?void 0:n.error;return t===400?new xh(t,i,r,s):t===401?new _h(t,i,r,s):t===403?new kh(t,i,r,s):t===404?new Sh(t,i,r,s):t===409?new Ch(t,i,r,s):t===422?new Eh(t,i,r,s):t===429?new Ih(t,i,r,s):t>=500?new jh(t,i,r,s):new Ee(t,i,r,s)}}class it extends Ee{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0)}}class to extends Ee{constructor({message:t,cause:n}){super(void 0,void 0,t||"Connection error.",void 0),n&&(this.cause=n)}}class Vl extends to{constructor({message:t}={}){super({message:t??"Request timed out."})}}class xh extends Ee{}class _h extends Ee{}class kh extends Ee{}class Sh extends Ee{}class Ch extends Ee{}class Eh extends Ee{}class Ih extends Ee{}class jh extends Ee{}class Nh extends B{constructor(){super("Could not parse response content as the length limit was reached")}}class Ph extends B{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const gv=/^[a-z][a-z0-9+.-]*:/i,yv=e=>gv.test(e);let be=e=>(be=Array.isArray,be(e)),Ac=be;function vv(e){return typeof e!="object"?{}:e??{}}function wv(e){if(!e)return!0;for(const t in e)return!1;return!0}function xv(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function $o(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}const _v=(e,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new B(`${e} must be an integer`);if(t<0)throw new B(`${e} must be a positive integer`);return t},kv=e=>{try{return JSON.parse(e)}catch{return}},fs=e=>new Promise(t=>setTimeout(t,e)),Rn="5.5.1",Sv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Cv(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Ev=()=>{var n;const e=Cv();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rn,"X-Stainless-OS":Mc(Deno.build.os),"X-Stainless-Arch":Rc(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rn,"X-Stainless-OS":Mc(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Rc(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=Iv();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Rn,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Iv(){if(typeof navigator>"u"||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const r=n.exec(navigator.userAgent);if(r){const s=r[1]||0,i=r[2]||0,o=r[3]||0;return{browser:t,version:`${s}.${i}.${o}`}}}return null}const Rc=e=>e==="x32"?"x32":e==="x86_64"||e==="x64"?"x64":e==="arm"?"arm":e==="aarch64"||e==="arm64"?"arm64":e?`other:${e}`:"unknown",Mc=e=>(e=e.toLowerCase(),e.includes("ios")?"iOS":e==="android"?"Android":e==="darwin"?"MacOS":e==="win32"?"Windows":e==="freebsd"?"FreeBSD":e==="openbsd"?"OpenBSD":e==="linux"?"Linux":e?`Other:${e}`:"Unknown");let Oc;const jv=()=>Oc??(Oc=Ev());function Nv(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ah(...e){const t=globalThis.ReadableStream;if(typeof t>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function Rh(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Ah({start(){},async pull(n){const{done:r,value:s}=await t.next();r?n.close():n.enqueue(s)},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}function Mh(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const n=await t.read();return n!=null&&n.done&&t.releaseLock(),n}catch(n){throw t.releaseLock(),n}},async return(){const n=t.cancel();return t.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Pv(e){var r,s;if(e===null||typeof e!="object")return;if(e[Symbol.asyncIterator]){await((s=(r=e[Symbol.asyncIterator]()).return)==null?void 0:s.call(r));return}const t=e.getReader(),n=t.cancel();t.releaseLock(),await n}const Av=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),Oh="RFC3986",Th=e=>String(e),Tc={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Th},Rv="RFC1738";let za=(e,t)=>(za=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),za(e,t));const wt=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),bo=1024,Mv=(e,t,n,r,s)=>{if(e.length===0)return e;let i=e;if(typeof e=="symbol"?i=Symbol.prototype.toString.call(e):typeof e!="string"&&(i=String(e)),n==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a=bo?i.slice(a,a+bo):i,c=[];for(let g=0;g=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||s===Rv&&(h===40||h===41)){c[c.length]=l.charAt(g);continue}if(h<128){c[c.length]=wt[h];continue}if(h<2048){c[c.length]=wt[192|h>>6]+wt[128|h&63];continue}if(h<55296||h>=57344){c[c.length]=wt[224|h>>12]+wt[128|h>>6&63]+wt[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|l.charCodeAt(g)&1023),c[c.length]=wt[240|h>>18]+wt[128|h>>12&63]+wt[128|h>>6&63]+wt[128|h&63]}o+=c.join("")}return o};function Ov(e){return!e||typeof e!="object"?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function Lc(e,t){if(be(e)){const n=[];for(let r=0;r"u"&&(v=0)}if(typeof c=="function"?d=c(t,d):d instanceof Date?d=m==null?void 0:m(d):n==="comma"&&be(d)&&(d=Lc(d,function(j){return j instanceof Date?m==null?void 0:m(j):j})),d===null){if(i)return l&&!w?l(t,me.encoder,k,"key",y):t;d=""}if(Tv(d)||Ov(d)){if(l){const j=w?t:l(t,me.encoder,k,"key",y);return[(x==null?void 0:x(j))+"="+(x==null?void 0:x(l(d,me.encoder,k,"value",y)))]}return[(x==null?void 0:x(t))+"="+(x==null?void 0:x(String(d)))]}const _=[];if(typeof d>"u")return _;let C;if(n==="comma"&&be(d))w&&l&&(d=Lc(d,l)),C=[{value:d.length>0?d.join(",")||null:void 0}];else if(be(c))C=c;else{const j=Object.keys(d);C=g?j.sort(g):j}const I=a?String(t).replace(/\./g,"%2E"):String(t),O=r&&be(d)&&d.length===1?I+"[]":I;if(s&&be(d)&&d.length===0)return O+"[]";for(let j=0;j"u"?e.encodeDotInKeys?!0:me.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix=="boolean"?e.addQueryPrefix:me.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays=="boolean"?!!e.allowEmptyArrays:me.allowEmptyArrays,arrayFormat:i,charset:t,charsetSentinel:typeof e.charsetSentinel=="boolean"?e.charsetSentinel:me.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?me.delimiter:e.delimiter,encode:typeof e.encode=="boolean"?e.encode:me.encode,encodeDotInKeys:typeof e.encodeDotInKeys=="boolean"?e.encodeDotInKeys:me.encodeDotInKeys,encoder:typeof e.encoder=="function"?e.encoder:me.encoder,encodeValuesOnly:typeof e.encodeValuesOnly=="boolean"?e.encodeValuesOnly:me.encodeValuesOnly,filter:s,format:n,formatter:r,serializeDate:typeof e.serializeDate=="function"?e.serializeDate:me.serializeDate,skipNulls:typeof e.skipNulls=="boolean"?e.skipNulls:me.skipNulls,sort:typeof e.sort=="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling=="boolean"?e.strictNullHandling:me.strictNullHandling}}function $v(e,t={}){let n=e;const r=Lv(t);let s,i;typeof r.filter=="function"?(i=r.filter,n=i("",n)):be(r.filter)&&(i=r.filter,s=i);const o=[];if(typeof n!="object"||n===null)return"";const a=Lh[r.arrayFormat],l=a==="comma"&&r.commaRoundTrip;s||(s=Object.keys(n)),r.sort&&s.sort(r.sort);const c=new WeakMap;for(let m=0;m0?h+g:""}function bv(e){let t=0;for(const s of e)t+=s.length;const n=new Uint8Array(t);let r=0;for(const s of e)n.set(s,r),r+=s.length;return n}let bc;function Ql(e){let t;return(bc??(t=new globalThis.TextEncoder,bc=t.encode.bind(t)))(e)}let Fc;function Dc(e){let t;return(Fc??(t=new globalThis.TextDecoder,Fc=t.decode.bind(t)))(e)}var Ve,Qe;class no{constructor(){Ve.set(this,void 0),Qe.set(this,void 0),W(this,Ve,new Uint8Array),W(this,Qe,null)}decode(t){if(t==null)return[];const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ql(t):t;W(this,Ve,bv([S(this,Ve,"f"),n]));const r=[];let s;for(;(s=Fv(S(this,Ve,"f"),S(this,Qe,"f")))!=null;){if(s.carriage&&S(this,Qe,"f")==null){W(this,Qe,s.index);continue}if(S(this,Qe,"f")!=null&&(s.index!==S(this,Qe,"f")+1||s.carriage)){r.push(Dc(S(this,Ve,"f").subarray(0,S(this,Qe,"f")-1))),W(this,Ve,S(this,Ve,"f").subarray(S(this,Qe,"f"))),W(this,Qe,null);continue}const i=S(this,Qe,"f")!==null?s.preceding-1:s.preceding,o=Dc(S(this,Ve,"f").subarray(0,i));r.push(o),W(this,Ve,S(this,Ve,"f").subarray(s.index)),W(this,Qe,null)}return r}flush(){return S(this,Ve,"f").length?this.decode(` `):[]}}Ve=new WeakMap,Qe=new WeakMap;no.NEWLINE_CHARS=new Set([` `,"\r"]);no.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Fv(e,t){for(let s=t??0;s({next:()=>{if(i.length===0){const o=r.next();t.push(o),n.push(o)}return i.shift()}});return[new St(()=>s(t),this.controller),new St(()=>s(n),this.controller)]}toReadableStream(){const t=this;let n;return Ah({async start(){n=t[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:i}=await n.next();if(i)return r.close();const o=Ql(JSON.stringify(s)+` `);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*zv(e,t){if(!e.body)throw t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new B("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new B("Attempted to iterate over a response with no body");const n=new Bv,r=new no,s=Mh(e.body);for await(const i of Uv(s))for(const o of r.decode(i)){const a=n.decode(o);a&&(yield a)}for(const i of r.flush()){const o=n.decode(i);o&&(yield o)}}async function*Uv(e){let t=new Uint8Array;for await(const n of e){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?Ql(n):n;let s=new Uint8Array(t.length+r.length);s.set(t),s.set(r,t.length),t=s;let i;for(;(i=Dv(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}class Bv{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(` `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[n,r,s]=Wv(t,":");return s.startsWith(" ")&&(s=s.substring(1)),n==="event"?this.event=s:n==="data"&&this.data.push(s),null}}function Wv(e,t){const n=e.indexOf(t);return n!==-1?[e.substring(0,n),t,e.substring(n+t.length)]:[e,"",""]}const Mi={off:0,error:200,warn:300,info:400,debug:500},zc=(e,t,n)=>{if(e){if(xv(Mi,e))return e;Pe(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Mi))}`)}};function Sr(){}function Ls(e,t,n){return!t||Mi[e]>Mi[n]?Sr:t[e].bind(t)}const Hv={error:Sr,warn:Sr,info:Sr,debug:Sr};let Uc=new WeakMap;function Pe(e){const t=e.logger,n=e.logLevel??"off";if(!t)return Hv;const r=Uc.get(t);if(r&&r[0]===n)return r[1];const s={error:Ls("error",t,n),warn:Ls("warn",t,n),info:Ls("info",t,n),debug:Ls("debug",t,n)};return Uc.set(t,[n,s]),s}const un=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,n])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);async function Fh(e,t){const{response:n,requestLogID:r,retryOfRequestLogID:s,startTime:i}=t,o=await(async()=>{var h;if(t.options.stream)return Pe(e).debug("response",n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller):St.fromSSEResponse(n,t.controller);if(n.status===204)return null;if(t.options.__binaryResponse)return n;const a=n.headers.get("content-type"),l=(h=a==null?void 0:a.split(";")[0])==null?void 0:h.trim();if((l==null?void 0:l.includes("application/json"))||(l==null?void 0:l.endsWith("+json"))){const m=await n.json();return Dh(m,n)}return await n.text()})();return Pe(e).debug(`[${r}] response parsed`,un({retryOfRequestLogID:s,url:n.url,status:n.status,body:o,durationMs:Date.now()-i})),o}function Dh(e,t){return!e||typeof e!="object"||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Cr;class ro extends Promise{constructor(t,n,r=Fh){super(s=>{s(null)}),this.responsePromise=n,this.parseResponse=r,Cr.set(this,void 0),W(this,Cr,t)}_thenUnwrap(t){return new ro(S(this,Cr,"f"),this.responsePromise,async(n,r)=>Dh(t(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(t=>this.parseResponse(S(this,Cr,"f"),t))),this.parsedPromise}then(t,n){return this.parse().then(t,n)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}Cr=new WeakMap;var $s;class zh{constructor(t,n,r,s){$s.set(this,void 0),W(this,$s,t),this.options=s,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const t=this.nextPageRequestOptions();if(!t)throw new B("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await S(this,$s,"f").requestAPIList(this.constructor,t)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[($s=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const n of t.getPaginatedItems())yield n}}class Vv extends ro{constructor(t,n,r){super(t,n,async(s,i)=>new r(s,i.response,await Fh(s,i),i.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const n of t)yield n}}class so extends zh{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class de extends zh{constructor(t,n,r,s){super(t,n,r,s),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const t=this.getPaginatedItems(),n=(r=t[t.length-1])==null?void 0:r.id;return n?{...this.options,query:{...vv(this.options.query),after:n}}:null}}const Uh=()=>{var e;if(typeof File>"u"){const{process:t}=globalThis,n=typeof((e=t==null?void 0:t.versions)==null?void 0:e.node)=="string"&&parseInt(t.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function zr(e,t,n){return Uh(),new File(e,t??"unknown_file",n)}function ei(e){return(typeof e=="object"&&e!==null&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const Bh=e=>e!=null&&typeof e=="object"&&typeof e[Symbol.asyncIterator]=="function",Sn=async(e,t)=>({...e,body:await Xv(e.body,t)}),Bc=new WeakMap;function Qv(e){const t=typeof e=="function"?e:e.fetch,n=Bc.get(t);if(n)return n;const r=(async()=>{try{const s="Response"in t?t.Response:(await t("data:,")).constructor,i=new FormData;return i.toString()!==await new s(i).text()}catch{return!0}})();return Bc.set(t,r),r}const Xv=async(e,t)=>{if(!await Qv(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(e||{}).map(([r,s])=>Ua(n,r,s))),n},Kv=e=>e instanceof Blob&&"name"in e,Ua=async(e,t,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")e.append(t,String(n));else if(n instanceof Response)e.append(t,zr([await n.blob()],ei(n)));else if(Bh(n))e.append(t,zr([await new Response(Rh(n)).blob()],ei(n)));else if(Kv(n))e.append(t,n,ei(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Ua(e,t+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,s])=>Ua(e,`${t}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Wh=e=>e!=null&&typeof e=="object"&&typeof e.size=="number"&&typeof e.type=="string"&&typeof e.text=="function"&&typeof e.slice=="function"&&typeof e.arrayBuffer=="function",qv=e=>e!=null&&typeof e=="object"&&typeof e.name=="string"&&typeof e.lastModified=="number"&&Wh(e),Gv=e=>e!=null&&typeof e=="object"&&typeof e.url=="string"&&typeof e.blob=="function";async function Jv(e,t,n){if(Uh(),e=await e,qv(e))return e instanceof File?e:zr([await e.arrayBuffer()],e.name);if(Gv(e)){const s=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),zr(await Ba(s),t,n)}const r=await Ba(e);if(t||(t=ei(e)),!(n!=null&&n.type)){const s=r.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof s=="string"&&(n={...n,type:s})}return zr(r,t,n)}async function Ba(e){var n;let t=[];if(typeof e=="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Wh(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Bh(e))for await(const r of e)t.push(...await Ba(r));else{const r=(n=e==null?void 0:e.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${Yv(e)}`)}return t}function Yv(e){return typeof e!="object"||e===null?"":`; props: [${Object.getOwnPropertyNames(e).map(n=>`"${n}"`).join(", ")}]`}class H{constructor(t){this._client=t}}function Hh(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Zv=(e=Hh)=>function(n,...r){if(n.length===1)return n[0];let s=!1;const i=n.reduce((g,h,m)=>(/[?#]/.test(h)&&(s=!0),g+h+(m===r.length?"":(s?encodeURIComponent:e)(String(r[m])))),""),o=i.split(/[?#]/,1)[0],a=[],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=l.exec(o))!==null;)a.push({start:c.index,length:c[0].length});if(a.length>0){let g=0;const h=a.reduce((m,y)=>{const x=" ".repeat(y.start-g),w="^".repeat(y.length);return g=y.start+y.length,m+x+w},"");throw new B(`Path parameters result in path with invalid segments: ${i} ${h}`)}return i},M=Zv(Hh);let Vh=class extends H{list(t,n={},r){return this._client.getAPIList(M`/chat/completions/${t}/messages`,de,{query:n,...r})}};function e0(e){return typeof e.parse=="function"}const Oi=e=>(e==null?void 0:e.role)==="assistant",Qh=e=>(e==null?void 0:e.role)==="tool";var Wa,ti,ni,Er,Ir,ri,jr,jt,Nr,Ti,Li,Mn,Xh;class Xl{constructor(){Wa.add(this),this.controller=new AbortController,ti.set(this,void 0),ni.set(this,()=>{}),Er.set(this,()=>{}),Ir.set(this,void 0),ri.set(this,()=>{}),jr.set(this,()=>{}),jt.set(this,{}),Nr.set(this,!1),Ti.set(this,!1),Li.set(this,!1),Mn.set(this,!1),W(this,ti,new Promise((t,n)=>{W(this,ni,t,"f"),W(this,Er,n,"f")})),W(this,Ir,new Promise((t,n)=>{W(this,ri,t,"f"),W(this,jr,n,"f")})),S(this,ti,"f").catch(()=>{}),S(this,Ir,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},S(this,Wa,"m",Xh).bind(this))},0)}_connected(){this.ended||(S(this,ni,"f").call(this),this._emit("connect"))}get ended(){return S(this,Nr,"f")}get errored(){return S(this,Ti,"f")}get aborted(){return S(this,Li,"f")}abort(){this.controller.abort()}on(t,n){return(S(this,jt,"f")[t]||(S(this,jt,"f")[t]=[])).push({listener:n}),this}off(t,n){const r=S(this,jt,"f")[t];if(!r)return this;const s=r.findIndex(i=>i.listener===n);return s>=0&&r.splice(s,1),this}once(t,n){return(S(this,jt,"f")[t]||(S(this,jt,"f")[t]=[])).push({listener:n,once:!0}),this}emitted(t){return new Promise((n,r)=>{W(this,Mn,!0),t!=="error"&&this.once("error",r),this.once(t,n)})}async done(){W(this,Mn,!0),await S(this,Ir,"f")}_emit(t,...n){if(S(this,Nr,"f"))return;t==="end"&&(W(this,Nr,!0),S(this,ri,"f").call(this));const r=S(this,jt,"f")[t];if(r&&(S(this,jt,"f")[t]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...n))),t==="abort"){const s=n[0];!S(this,Mn,"f")&&!(r!=null&&r.length)&&Promise.reject(s),S(this,Er,"f").call(this,s),S(this,jr,"f").call(this,s),this._emit("end");return}if(t==="error"){const s=n[0];!S(this,Mn,"f")&&!(r!=null&&r.length)&&Promise.reject(s),S(this,Er,"f").call(this,s),S(this,jr,"f").call(this,s),this._emit("end")}}_emitFinal(){}}ti=new WeakMap,ni=new WeakMap,Er=new WeakMap,Ir=new WeakMap,ri=new WeakMap,jr=new WeakMap,jt=new WeakMap,Nr=new WeakMap,Ti=new WeakMap,Li=new WeakMap,Mn=new WeakMap,Wa=new WeakSet,Xh=function(t){if(W(this,Ti,!0),t instanceof Error&&t.name==="AbortError"&&(t=new it),t instanceof it)return W(this,Li,!0),this._emit("abort",t);if(t instanceof B)return this._emit("error",t);if(t instanceof Error){const n=new B(t.message);return n.cause=t,this._emit("error",n)}return this._emit("error",new B(String(t)))};function Kl(e){return(e==null?void 0:e.$brand)==="auto-parseable-response-format"}function hs(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function t0(e,t){return!t||!Kh(t)?{...e,choices:e.choices.map(n=>({...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:ql(e,t)}function ql(e,t){const n=e.choices.map(r=>{var s;if(r.finish_reason==="length")throw new Nh;if(r.finish_reason==="content_filter")throw new Ph;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((s=r.message.tool_calls)==null?void 0:s.map(i=>r0(t,i)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?n0(t,r.message.content):null}}});return{...e,choices:n}}function n0(e,t){var n,r;return((n=e.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=e.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function r0(e,t){var r;const n=(r=e.tools)==null?void 0:r.find(s=>{var i;return((i=s.function)==null?void 0:i.name)===t.function.name});return{...t,function:{...t.function,parsed_arguments:hs(n)?n.$parseRaw(t.function.arguments):n!=null&&n.function.strict?JSON.parse(t.function.arguments):null}}}function s0(e,t){var r;if(!e)return!1;const n=(r=e.tools)==null?void 0:r.find(s=>{var i;return((i=s.function)==null?void 0:i.name)===t.function.name});return hs(n)||(n==null?void 0:n.function.strict)||!1}function Kh(e){var t;return Kl(e.response_format)?!0:((t=e.tools)==null?void 0:t.some(n=>hs(n)||n.type==="function"&&n.function.strict===!0))??!1}function i0(e){for(const t of e??[]){if(t.type!=="function")throw new B(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new B(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Me,Ha,$i,Va,Qa,Xa,qh,Gh;const o0=10;class Jh extends Xl{constructor(){super(...arguments),Me.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(t){var r;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(r=t.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),t}_addMessage(t,n=!0){if("content"in t||(t.content=null),this.messages.push(t),n){if(this._emit("message",t),Qh(t)&&t.content)this._emit("functionToolCallResult",t.content);else if(Oi(t)&&t.tool_calls)for(const r of t.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new B("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),S(this,Me,"m",Ha).call(this)}async finalMessage(){return await this.done(),S(this,Me,"m",$i).call(this)}async finalFunctionToolCall(){return await this.done(),S(this,Me,"m",Va).call(this)}async finalFunctionToolCallResult(){return await this.done(),S(this,Me,"m",Qa).call(this)}async totalUsage(){return await this.done(),S(this,Me,"m",Xa).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const n=S(this,Me,"m",$i).call(this);n&&this._emit("finalMessage",n);const r=S(this,Me,"m",Ha).call(this);r&&this._emit("finalContent",r);const s=S(this,Me,"m",Va).call(this);s&&this._emit("finalFunctionToolCall",s);const i=S(this,Me,"m",Qa).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",S(this,Me,"m",Xa).call(this))}async _createChatCompletion(t,n,r){const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),S(this,Me,"m",qh).call(this,n);const i=await t.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ql(i,n))}async _runChatCompletion(t,n,r){for(const s of n.messages)this._addMessage(s,!1);return await this._createChatCompletion(t,n,r)}async _runTools(t,n,r){var y,x,w;const s="tool",{tool_choice:i="auto",stream:o,...a}=n,l=typeof i!="string"&&((y=i==null?void 0:i.function)==null?void 0:y.name),{maxChatCompletions:c=o0}=r||{},g=n.tools.map(k=>{if(hs(k)){if(!k.$callback)throw new B("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:k.$callback,name:k.function.name,description:k.function.description||"",parameters:k.function.parameters,parse:k.$parseRaw,strict:!0}}}return k}),h={};for(const k of g)k.type==="function"&&(h[k.function.name||k.function.function.name]=k.function);const m="tools"in n?g.map(k=>k.type==="function"?{type:"function",function:{name:k.function.name||k.function.function.name,parameters:k.function.parameters,description:k.function.description,strict:k.function.strict}}:k):void 0;for(const k of n.messages)this._addMessage(k,!1);for(let k=0;kJSON.stringify(b)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:P});continue}let I;try{I=e0(C)?await C.parse(_):_}catch(P){const b=P instanceof Error?P.message:String(P);this._addMessage({role:s,tool_call_id:v,content:b});continue}const O=await C.function(I,this),j=S(this,Me,"m",Gh).call(this,O);if(this._addMessage({role:s,tool_call_id:v,content:j}),l)return}}}}Me=new WeakSet,Ha=function(){return S(this,Me,"m",$i).call(this).content??null},$i=function(){let t=this.messages.length;for(;t-- >0;){const n=this.messages[t];if(Oi(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new B("stream ended without producing a ChatCompletionMessage with role=assistant")},Va=function(){var t,n;for(let r=this.messages.length-1;r>=0;r--){const s=this.messages[r];if(Oi(s)&&((t=s==null?void 0:s.tool_calls)!=null&&t.length))return(n=s.tool_calls.at(-1))==null?void 0:n.function}},Qa=function(){for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(Qh(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>{var s;return r.role==="assistant"&&((s=r.tool_calls)==null?void 0:s.some(i=>i.type==="function"&&i.id===n.tool_call_id))}))return n.content}},Xa=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(t.completion_tokens+=n.completion_tokens,t.prompt_tokens+=n.prompt_tokens,t.total_tokens+=n.total_tokens);return t},qh=function(t){if(t.n!=null&&t.n>1)throw new B("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Gh=function(t){return typeof t=="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Gl extends Jh{static runTools(t,n,r){const s=new Gl,i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,i)),s}_addMessage(t,n=!0){super._addMessage(t,n),Oi(t)&&t.content&&this._emit("content",t.content)}}const Yh=1,Zh=2,ep=4,tp=8,np=16,rp=32,sp=64,ip=128,op=256,ap=ip|op,lp=np|rp|ap|sp,up=Yh|Zh|lp,cp=ep|tp,a0=up|cp,ve={STR:Yh,NUM:Zh,ARR:ep,OBJ:tp,NULL:np,BOOL:rp,NAN:sp,INFINITY:ip,MINUS_INFINITY:op,INF:ap,SPECIAL:lp,ATOM:up,COLLECTION:cp,ALL:a0};class l0 extends Error{}class u0 extends Error{}function c0(e,t=ve.ALL){if(typeof e!="string")throw new TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw new Error(`${e} is empty`);return d0(e.trim(),t)}const d0=(e,t)=>{const n=e.length;let r=0;const s=m=>{throw new l0(`${m} at position ${r}`)},i=m=>{throw new u0(`${m} at position ${r}`)},o=()=>(h(),r>=n&&s("Unexpected end of input"),e[r]==='"'?a():e[r]==="{"?l():e[r]==="["?c():e.substring(r,r+4)==="null"||ve.NULL&t&&n-r<4&&"null".startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)==="true"||ve.BOOL&t&&n-r<4&&"true".startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)==="false"||ve.BOOL&t&&n-r<5&&"false".startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)==="Infinity"||ve.INFINITY&t&&n-r<8&&"Infinity".startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)==="-Infinity"||ve.MINUS_INFINITY&t&&1{const m=r;let y=!1;for(r++;r{r++,h();const m={};try{for(;e[r]!=="}";){if(h(),r>=n&&ve.OBJ&t)return m;const y=a();h(),r++;try{const x=o();Object.defineProperty(m,y,{value:x,writable:!0,enumerable:!0,configurable:!0})}catch(x){if(ve.OBJ&t)return m;throw x}h(),e[r]===","&&r++}}catch{if(ve.OBJ&t)return m;s("Expected '}' at end of object")}return r++,m},c=()=>{r++;const m=[];try{for(;e[r]!=="]";)m.push(o()),h(),e[r]===","&&r++}catch{if(ve.ARR&t)return m;s("Expected ']' at end of array")}return r++,m},g=()=>{if(r===0){e==="-"&&ve.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e)}catch(y){if(ve.NUM&t)try{return e[e.length-1]==="."?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch{}i(String(y))}}const m=r;for(e[r]==="-"&&r++;e[r]&&!",]}".includes(e[r]);)r++;r==n&&!(ve.NUM&t)&&s("Unterminated number literal");try{return JSON.parse(e.substring(m,r))}catch{e.substring(m,r)==="-"&&ve.NUM&t&&s("Not sure what '-' is");try{return JSON.parse(e.substring(m,e.lastIndexOf("e")))}catch(x){i(String(x))}}},h=()=>{for(;rc0(e,ve.ALL^ve.NUM);var pe,It,Pn,Dt,Do,bs,zo,Uo,Bo,Fs,Wo,Hc;class os extends Jh{constructor(t){super(),pe.add(this),It.set(this,void 0),Pn.set(this,void 0),Dt.set(this,void 0),W(this,It,t),W(this,Pn,[])}get currentChatCompletionSnapshot(){return S(this,Dt,"f")}static fromReadableStream(t){const n=new os(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){const s=new os(n);return s._run(()=>s._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(t,n,r){var o;super._createChatCompletion;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),S(this,pe,"m",Do).call(this);const i=await t.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const a of i)S(this,pe,"m",zo).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new it;return this._addChatCompletion(S(this,pe,"m",Fs).call(this))}async _fromReadableStream(t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),S(this,pe,"m",Do).call(this),this._connected();const s=St.fromReadableStream(t,this.controller);let i;for await(const a of s)i&&i!==a.id&&this._addChatCompletion(S(this,pe,"m",Fs).call(this)),S(this,pe,"m",zo).call(this,a),i=a.id;if((o=s.controller.signal)!=null&&o.aborted)throw new it;return this._addChatCompletion(S(this,pe,"m",Fs).call(this))}[(It=new WeakMap,Pn=new WeakMap,Dt=new WeakMap,pe=new WeakSet,Do=function(){this.ended||W(this,Dt,void 0)},bs=function(n){let r=S(this,Pn,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},S(this,Pn,"f")[n.index]=r,r)},zo=function(n){var s,i,o,a,l,c,g,h,m,y,x,w,k,f,d;if(this.ended)return;const r=S(this,pe,"m",Hc).call(this,n);this._emit("chunk",n,r);for(const p of n.choices){const v=r.choices[p.index];p.delta.content!=null&&((s=v.message)==null?void 0:s.role)==="assistant"&&((i=v.message)!=null&&i.content)&&(this._emit("content",p.delta.content,v.message.content),this._emit("content.delta",{delta:p.delta.content,snapshot:v.message.content,parsed:v.message.parsed})),p.delta.refusal!=null&&((o=v.message)==null?void 0:o.role)==="assistant"&&((a=v.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:p.delta.refusal,snapshot:v.message.refusal}),((l=p.logprobs)==null?void 0:l.content)!=null&&((c=v.message)==null?void 0:c.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(g=p.logprobs)==null?void 0:g.content,snapshot:((h=v.logprobs)==null?void 0:h.content)??[]}),((m=p.logprobs)==null?void 0:m.refusal)!=null&&((y=v.message)==null?void 0:y.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(x=p.logprobs)==null?void 0:x.refusal,snapshot:((w=v.logprobs)==null?void 0:w.refusal)??[]});const E=S(this,pe,"m",bs).call(this,v);v.finish_reason&&(S(this,pe,"m",Bo).call(this,v),E.current_tool_call_index!=null&&S(this,pe,"m",Uo).call(this,v,E.current_tool_call_index));for(const _ of p.delta.tool_calls??[])E.current_tool_call_index!==_.index&&(S(this,pe,"m",Bo).call(this,v),E.current_tool_call_index!=null&&S(this,pe,"m",Uo).call(this,v,E.current_tool_call_index)),E.current_tool_call_index=_.index;for(const _ of p.delta.tool_calls??[]){const C=(k=v.message.tool_calls)==null?void 0:k[_.index];C!=null&&C.type&&((C==null?void 0:C.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(f=C.function)==null?void 0:f.name,index:_.index,arguments:C.function.arguments,parsed_arguments:C.function.parsed_arguments,arguments_delta:((d=_.function)==null?void 0:d.arguments)??""}):(C==null||C.type,void 0))}}},Uo=function(n,r){var o,a,l;if(S(this,pe,"m",bs).call(this,n).done_tool_calls.has(r))return;const i=(o=n.message.tool_calls)==null?void 0:o[r];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const c=(l=(a=S(this,It,"f"))==null?void 0:a.tools)==null?void 0:l.find(g=>g.type==="function"&&g.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:r,arguments:i.function.arguments,parsed_arguments:hs(c)?c.$parseRaw(i.function.arguments):c!=null&&c.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Bo=function(n){var s,i;const r=S(this,pe,"m",bs).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const o=S(this,pe,"m",Wo).call(this);this._emit("content.done",{content:n.message.content,parsed:o?o.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(s=n.logprobs)!=null&&s.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(i=n.logprobs)!=null&&i.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Fs=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");const n=S(this,Dt,"f");if(!n)throw new B("request ended without sending any chunks");return W(this,Dt,void 0),W(this,Pn,[]),f0(n,S(this,It,"f"))},Wo=function(){var r;const n=(r=S(this,It,"f"))==null?void 0:r.response_format;return Kl(n)?n:null},Hc=function(n){var r,s,i,o;let a=S(this,Dt,"f");const{choices:l,...c}=n;a?Object.assign(a,c):a=W(this,Dt,{...c,choices:[]});for(const{delta:g,finish_reason:h,index:m,logprobs:y=null,...x}of n.choices){let w=a.choices[m];if(w||(w=a.choices[m]={finish_reason:h,index:m,message:{},logprobs:y,...x}),y)if(!w.logprobs)w.logprobs=Object.assign({},y);else{const{content:_,refusal:C,...I}=y;Object.assign(w.logprobs,I),_&&((r=w.logprobs).content??(r.content=[]),w.logprobs.content.push(..._)),C&&((s=w.logprobs).refusal??(s.refusal=[]),w.logprobs.refusal.push(...C))}if(h&&(w.finish_reason=h,S(this,It,"f")&&Kh(S(this,It,"f")))){if(h==="length")throw new Nh;if(h==="content_filter")throw new Ph}if(Object.assign(w,x),!g)continue;const{content:k,refusal:f,function_call:d,role:p,tool_calls:v,...E}=g;if(Object.assign(w.message,E),f&&(w.message.refusal=(w.message.refusal||"")+f),p&&(w.message.role=p),d&&(w.message.function_call?(d.name&&(w.message.function_call.name=d.name),d.arguments&&((i=w.message.function_call).arguments??(i.arguments=""),w.message.function_call.arguments+=d.arguments)):w.message.function_call=d),k&&(w.message.content=(w.message.content||"")+k,!w.message.refusal&&S(this,pe,"m",Wo).call(this)&&(w.message.parsed=Wc(w.message.content))),v){w.message.tool_calls||(w.message.tool_calls=[]);for(const{index:_,id:C,type:I,function:O,...j}of v){const P=(o=w.message.tool_calls)[_]??(o[_]={});Object.assign(P,j),C&&(P.id=C),I&&(P.type=I),O&&(P.function??(P.function={name:O.name??"",arguments:""})),O!=null&&O.name&&(P.function.name=O.name),O!=null&&O.arguments&&(P.function.arguments+=O.arguments,s0(S(this,It,"f"),P)&&(P.function.parsed_arguments=Wc(P.function.arguments)))}}}return a},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("chunk",s=>{const i=n.shift();i?i.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>n.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new St(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function f0(e,t){const{id:n,choices:r,created:s,model:i,system_fingerprint:o,...a}=e,l={...a,id:n,choices:r.map(({message:c,finish_reason:g,index:h,logprobs:m,...y})=>{if(!g)throw new B(`missing finish_reason for choice ${h}`);const{content:x=null,function_call:w,tool_calls:k,...f}=c,d=c.role;if(!d)throw new B(`missing role for choice ${h}`);if(w){const{arguments:p,name:v}=w;if(p==null)throw new B(`missing function_call.arguments for choice ${h}`);if(!v)throw new B(`missing function_call.name for choice ${h}`);return{...y,message:{content:x,function_call:{arguments:p,name:v},role:d,refusal:c.refusal??null},finish_reason:g,index:h,logprobs:m}}return k?{...y,index:h,finish_reason:g,logprobs:m,message:{...f,role:d,content:x,refusal:c.refusal??null,tool_calls:k.map((p,v)=>{const{function:E,type:_,id:C,...I}=p,{arguments:O,name:j,...P}=E||{};if(C==null)throw new B(`missing choices[${h}].tool_calls[${v}].id ${Ds(e)}`);if(_==null)throw new B(`missing choices[${h}].tool_calls[${v}].type ${Ds(e)}`);if(j==null)throw new B(`missing choices[${h}].tool_calls[${v}].function.name ${Ds(e)}`);if(O==null)throw new B(`missing choices[${h}].tool_calls[${v}].function.arguments ${Ds(e)}`);return{...I,id:C,type:_,function:{...P,name:j,arguments:O}}})}}:{...y,message:{...f,content:x,role:d,refusal:c.refusal??null},finish_reason:g,index:h,logprobs:m}}),created:s,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}};return t0(l,t)}function Ds(e){return JSON.stringify(e)}class bi extends os{static fromReadableStream(t){const n=new bi(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){const s=new bi(n),i={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(t,n,i)),s}}let Jl=class extends H{constructor(){super(...arguments),this.messages=new Vh(this._client)}create(t,n){return this._client.post("/chat/completions",{body:t,...n,stream:t.stream??!1})}retrieve(t,n){return this._client.get(M`/chat/completions/${t}`,n)}update(t,n,r){return this._client.post(M`/chat/completions/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/chat/completions",de,{query:t,...n})}delete(t,n){return this._client.delete(M`/chat/completions/${t}`,n)}parse(t,n){return i0(t.tools),this._client.chat.completions.create(t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ql(r,t))}runTools(t,n){return t.stream?bi.runTools(this._client,t,n):Gl.runTools(this._client,t,n)}stream(t,n){return os.createChatCompletion(this._client,t,n)}};Jl.Messages=Vh;class Yl extends H{constructor(){super(...arguments),this.completions=new Jl(this._client)}}Yl.Completions=Jl;const dp=Symbol("brand.privateNullableHeaders");function*h0(e){if(!e)return;if(dp in e){const{values:r,nulls:s}=e;yield*r.entries();for(const i of s)yield[i,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Ac(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let r of n){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const i=Ac(r[1])?r[1]:[r[1]];let o=!1;for(const a of i)a!==void 0&&(t&&!o&&(o=!0,yield[s,null]),yield[s,a])}}const z=e=>{const t=new Headers,n=new Set;for(const r of e){const s=new Set;for(const[i,o]of h0(r)){const a=i.toLowerCase();s.has(a)||(t.delete(i),s.add(a)),o===null?(t.delete(i),n.add(a)):(t.append(i,o),n.delete(a))}}return{[dp]:!0,values:t,nulls:n}};class fp extends H{create(t,n){return this._client.post("/audio/speech",{body:t,...n,headers:z([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__binaryResponse:!0})}}class hp extends H{create(t,n){return this._client.post("/audio/transcriptions",Sn({body:t,...n,stream:t.stream??!1,__metadata:{model:t.model}},this._client))}}class pp extends H{create(t,n){return this._client.post("/audio/translations",Sn({body:t,...n,__metadata:{model:t.model}},this._client))}}class ps extends H{constructor(){super(...arguments),this.transcriptions=new hp(this._client),this.translations=new pp(this._client),this.speech=new fp(this._client)}}ps.Transcriptions=hp;ps.Translations=pp;ps.Speech=fp;class mp extends H{create(t,n){return this._client.post("/batches",{body:t,...n})}retrieve(t,n){return this._client.get(M`/batches/${t}`,n)}list(t={},n){return this._client.getAPIList("/batches",de,{query:t,...n})}cancel(t,n){return this._client.post(M`/batches/${t}/cancel`,n)}}class gp extends H{create(t,n){return this._client.post("/assistants",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(M`/assistants/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(M`/assistants/${t}`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/assistants",de,{query:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(M`/assistants/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class yp extends H{create(t,n){return this._client.post("/realtime/sessions",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class vp extends H{create(t,n){return this._client.post("/realtime/transcription_sessions",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class io extends H{constructor(){super(...arguments),this.sessions=new yp(this._client),this.transcriptionSessions=new vp(this._client)}}io.Sessions=yp;io.TranscriptionSessions=vp;class wp extends H{create(t,n,r){return this._client.post(M`/threads/${t}/messages`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(M`/threads/${s}/messages/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...i}=n;return this._client.post(M`/threads/${s}/messages/${t}`,{body:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(M`/threads/${t}/messages`,de,{query:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{thread_id:s}=n;return this._client.delete(M`/threads/${s}/messages/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class xp extends H{retrieve(t,n,r){const{thread_id:s,run_id:i,...o}=n;return this._client.get(M`/threads/${s}/runs/${i}/steps/${t}`,{query:o,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n,r){const{thread_id:s,...i}=n;return this._client.getAPIList(M`/threads/${s}/runs/${t}/steps`,de,{query:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}const p0=e=>{if(typeof Buffer<"u"){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{const t=atob(e),n=t.length,r=new Uint8Array(n);for(let s=0;s{var t,n,r,s;if(typeof globalThis.process<"u")return((t=Ho==null?void 0:Ho[e])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(s=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,e))==null?void 0:s.trim()};var ke,pn,Ka,_t,si,dt,mn,Vn,cn,Fi,Xe,ii,oi,Ur,Pr,Ar,Vc,Qc,Xc,Kc,qc,Gc,Jc;class Br extends Xl{constructor(){super(...arguments),ke.add(this),Ka.set(this,[]),_t.set(this,{}),si.set(this,{}),dt.set(this,void 0),mn.set(this,void 0),Vn.set(this,void 0),cn.set(this,void 0),Fi.set(this,void 0),Xe.set(this,void 0),ii.set(this,void 0),oi.set(this,void 0),Ur.set(this,void 0)}[(Ka=new WeakMap,_t=new WeakMap,si=new WeakMap,dt=new WeakMap,mn=new WeakMap,Vn=new WeakMap,cn=new WeakMap,Fi=new WeakMap,Xe=new WeakMap,ii=new WeakMap,oi=new WeakMap,Ur=new WeakMap,ke=new WeakSet,Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("event",s=>{const i=n.shift();i?i.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>n.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const n=new pn;return n._run(()=>n._fromReadableStream(t)),n}async _fromReadableStream(t,n){var i;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=St.fromReadableStream(t,this.controller);for await(const o of s)S(this,ke,"m",Pr).call(this,o);if((i=s.controller.signal)!=null&&i.aborted)throw new it;return this._addRun(S(this,ke,"m",Ar).call(this))}toReadableStream(){return new St(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,n,r,s){const i=new pn;return i._run(()=>i._runToolAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(t,n,r,s){var l;const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...r,stream:!0},a=await t.submitToolOutputs(n,o,{...s,signal:this.controller.signal});this._connected();for await(const c of a)S(this,ke,"m",Pr).call(this,c);if((l=a.controller.signal)!=null&&l.aborted)throw new it;return this._addRun(S(this,ke,"m",Ar).call(this))}static createThreadAssistantStream(t,n,r){const s=new pn;return s._run(()=>s._threadAssistantStream(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(t,n,r,s){const i=new pn;return i._run(()=>i._runAssistantStream(t,n,r,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return S(this,ii,"f")}currentRun(){return S(this,oi,"f")}currentMessageSnapshot(){return S(this,dt,"f")}currentRunStepSnapshot(){return S(this,Ur,"f")}async finalRunSteps(){return await this.done(),Object.values(S(this,_t,"f"))}async finalMessages(){return await this.done(),Object.values(S(this,si,"f"))}async finalRun(){if(await this.done(),!S(this,mn,"f"))throw Error("Final run was not received.");return S(this,mn,"f")}async _createThreadAssistantStream(t,n,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await t.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const l of o)S(this,ke,"m",Pr).call(this,l);if((a=o.controller.signal)!=null&&a.aborted)throw new it;return this._addRun(S(this,ke,"m",Ar).call(this))}async _createAssistantStream(t,n,r,s){var l;const i=s==null?void 0:s.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...r,stream:!0},a=await t.create(n,o,{...s,signal:this.controller.signal});this._connected();for await(const c of a)S(this,ke,"m",Pr).call(this,c);if((l=a.controller.signal)!=null&&l.aborted)throw new it;return this._addRun(S(this,ke,"m",Ar).call(this))}static accumulateDelta(t,n){for(const[r,s]of Object.entries(n)){if(!t.hasOwnProperty(r)){t[r]=s;continue}let i=t[r];if(i==null){t[r]=s;continue}if(r==="index"||r==="type"){t[r]=s;continue}if(typeof i=="string"&&typeof s=="string")i+=s;else if(typeof i=="number"&&typeof s=="number")i+=s;else if($o(i)&&$o(s))i=this.accumulateDelta(i,s);else if(Array.isArray(i)&&Array.isArray(s)){if(i.every(o=>typeof o=="string"||typeof o=="number")){i.push(...s);continue}for(const o of s){if(!$o(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);const a=o.index;if(a==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);const l=i[a];l==null?i.push(o):i[a]=this.accumulateDelta(l,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${i}`);t[r]=i}return t}_addRun(t){return t}async _threadAssistantStream(t,n,r){return await this._createThreadAssistantStream(n,t,r)}async _runAssistantStream(t,n,r,s){return await this._createAssistantStream(n,t,r,s)}async _runToolAssistantStream(t,n,r,s){return await this._createToolAssistantStream(n,t,r,s)}}pn=Br,Pr=function(t){if(!this.ended)switch(W(this,ii,t),S(this,ke,"m",Xc).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":S(this,ke,"m",Jc).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":S(this,ke,"m",Qc).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":S(this,ke,"m",Vc).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ar=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");if(!S(this,mn,"f"))throw Error("Final run has not been received");return S(this,mn,"f")},Vc=function(t){const[n,r]=S(this,ke,"m",qc).call(this,t,S(this,dt,"f"));W(this,dt,n),S(this,si,"f")[n.id]=n;for(const s of r){const i=n.content[s.index];(i==null?void 0:i.type)=="text"&&this._emit("textCreated",i.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,n),t.data.delta.content)for(const s of t.data.delta.content){if(s.type=="text"&&s.text){let i=s.text,o=n.content[s.index];if(o&&o.type=="text")this._emit("textDelta",i,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=S(this,Vn,"f")){if(S(this,cn,"f"))switch(S(this,cn,"f").type){case"text":this._emit("textDone",S(this,cn,"f").text,S(this,dt,"f"));break;case"image_file":this._emit("imageFileDone",S(this,cn,"f").image_file,S(this,dt,"f"));break}W(this,Vn,s.index)}W(this,cn,n.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(S(this,Vn,"f")!==void 0){const s=t.data.content[S(this,Vn,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,S(this,dt,"f"));break;case"text":this._emit("textDone",s.text,S(this,dt,"f"));break}}S(this,dt,"f")&&this._emit("messageDone",t.data),W(this,dt,void 0)}},Qc=function(t){const n=S(this,ke,"m",Kc).call(this,t);switch(W(this,Ur,n),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const r=t.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const i of r.step_details.tool_calls)i.index==S(this,Fi,"f")?this._emit("toolCallDelta",i,n.step_details.tool_calls[i.index]):(S(this,Xe,"f")&&this._emit("toolCallDone",S(this,Xe,"f")),W(this,Fi,i.index),W(this,Xe,n.step_details.tool_calls[i.index]),S(this,Xe,"f")&&this._emit("toolCallCreated",S(this,Xe,"f")));this._emit("runStepDelta",t.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":W(this,Ur,void 0),t.data.step_details.type=="tool_calls"&&S(this,Xe,"f")&&(this._emit("toolCallDone",S(this,Xe,"f")),W(this,Xe,void 0)),this._emit("runStepDone",t.data,n);break}},Xc=function(t){S(this,Ka,"f").push(t),this._emit("event",t)},Kc=function(t){switch(t.event){case"thread.run.step.created":return S(this,_t,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let n=S(this,_t,"f")[t.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=t.data;if(r.delta){const s=pn.accumulateDelta(n,r.delta);S(this,_t,"f")[t.data.id]=s}return S(this,_t,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":S(this,_t,"f")[t.data.id]=t.data;break}if(S(this,_t,"f")[t.data.id])return S(this,_t,"f")[t.data.id];throw new Error("No snapshot available")},qc=function(t,n){let r=[];switch(t.event){case"thread.message.created":return[t.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=t.data;if(s.delta.content)for(const i of s.delta.content)if(i.index in n.content){let o=n.content[i.index];n.content[i.index]=S(this,ke,"m",Gc).call(this,i,o)}else n.content[i.index]=i,r.push(i);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Gc=function(t,n){return pn.accumulateDelta(n,t)},Jc=function(t){switch(W(this,oi,t.data),t.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":W(this,mn,t.data),S(this,Xe,"f")&&(this._emit("toolCallDone",S(this,Xe,"f")),W(this,Xe,void 0));break}};let Zl=class extends H{constructor(){super(...arguments),this.steps=new xp(this._client)}create(t,n,r){const{include:s,...i}=n;return this._client.post(M`/threads/${t}/runs`,{query:{include:s},body:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}retrieve(t,n,r){const{thread_id:s}=n;return this._client.get(M`/threads/${s}/runs/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{thread_id:s,...i}=n;return this._client.post(M`/threads/${s}/runs/${t}`,{body:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(M`/threads/${t}/runs`,de,{query:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{thread_id:s}=n;return this._client.post(M`/threads/${s}/runs/${t}/cancel`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(s.id,{thread_id:t},r)}createAndStream(t,n,r){return Br.createAssistantStream(t,this._client.beta.threads.runs,n,r)}async poll(t,n,r){var i;const s=z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const{data:o,response:a}=await this.retrieve(t,n,{...r,headers:{...r==null?void 0:r.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r!=null&&r.pollIntervalMs)l=r.pollIntervalMs;else{const c=a.headers.get("openai-poll-after-ms");if(c){const g=parseInt(c);isNaN(g)||(l=g)}}await fs(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(t,n,r){return Br.createAssistantStream(t,this._client.beta.threads.runs,n,r)}submitToolOutputs(t,n,r){const{thread_id:s,...i}=n;return this._client.post(M`/threads/${s}/runs/${t}/submit_tool_outputs`,{body:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(t,n,r){const s=await this.submitToolOutputs(t,n,r);return await this.poll(s.id,n,r)}submitToolOutputsStream(t,n,r){return Br.createToolAssistantStream(t,this._client.beta.threads.runs,n,r)}};Zl.Steps=xp;class oo extends H{constructor(){super(...arguments),this.runs=new Zl(this._client),this.messages=new wp(this._client)}create(t={},n){return this._client.post("/threads",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(M`/threads/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(M`/threads/${t}`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n){return this._client.delete(M`/threads/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}createAndRun(t,n){return this._client.post("/threads/runs",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:t.stream??!1})}async createAndRunPoll(t,n){const r=await this.createAndRun(t,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(t,n){return Br.createThreadAssistantStream(t,this._client.beta.threads,n)}}oo.Runs=Zl;oo.Messages=wp;class ms extends H{constructor(){super(...arguments),this.realtime=new io(this._client),this.assistants=new gp(this._client),this.threads=new oo(this._client)}}ms.Realtime=io;ms.Assistants=gp;ms.Threads=oo;class _p extends H{create(t,n){return this._client.post("/completions",{body:t,...n,stream:t.stream??!1})}}class kp extends H{retrieve(t,n,r){const{container_id:s}=n;return this._client.get(M`/containers/${s}/files/${t}/content`,{...r,headers:z([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}}let eu=class extends H{constructor(){super(...arguments),this.content=new kp(this._client)}create(t,n,r){return this._client.post(M`/containers/${t}/files`,Sn({body:n,...r},this._client))}retrieve(t,n,r){const{container_id:s}=n;return this._client.get(M`/containers/${s}/files/${t}`,r)}list(t,n={},r){return this._client.getAPIList(M`/containers/${t}/files`,de,{query:n,...r})}delete(t,n,r){const{container_id:s}=n;return this._client.delete(M`/containers/${s}/files/${t}`,{...r,headers:z([{Accept:"*/*"},r==null?void 0:r.headers])})}};eu.Content=kp;class tu extends H{constructor(){super(...arguments),this.files=new eu(this._client)}create(t,n){return this._client.post("/containers",{body:t,...n})}retrieve(t,n){return this._client.get(M`/containers/${t}`,n)}list(t={},n){return this._client.getAPIList("/containers",de,{query:t,...n})}delete(t,n){return this._client.delete(M`/containers/${t}`,{...n,headers:z([{Accept:"*/*"},n==null?void 0:n.headers])})}}tu.Files=eu;class Sp extends H{create(t,n){const r=!!t.encoding_format;let s=r?t.encoding_format:"base64";r&&Pe(this._client).debug("embeddings/user defined encoding_format:",t.encoding_format);const i=this._client.post("/embeddings",{body:{...t,encoding_format:s},...n});return r?i:(Pe(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(o=>(o&&o.data&&o.data.forEach(a=>{const l=a.embedding;a.embedding=p0(l)}),o)))}}class Cp extends H{retrieve(t,n,r){const{eval_id:s,run_id:i}=n;return this._client.get(M`/evals/${s}/runs/${i}/output_items/${t}`,r)}list(t,n,r){const{eval_id:s,...i}=n;return this._client.getAPIList(M`/evals/${s}/runs/${t}/output_items`,de,{query:i,...r})}}class nu extends H{constructor(){super(...arguments),this.outputItems=new Cp(this._client)}create(t,n,r){return this._client.post(M`/evals/${t}/runs`,{body:n,...r})}retrieve(t,n,r){const{eval_id:s}=n;return this._client.get(M`/evals/${s}/runs/${t}`,r)}list(t,n={},r){return this._client.getAPIList(M`/evals/${t}/runs`,de,{query:n,...r})}delete(t,n,r){const{eval_id:s}=n;return this._client.delete(M`/evals/${s}/runs/${t}`,r)}cancel(t,n,r){const{eval_id:s}=n;return this._client.post(M`/evals/${s}/runs/${t}`,r)}}nu.OutputItems=Cp;class ru extends H{constructor(){super(...arguments),this.runs=new nu(this._client)}create(t,n){return this._client.post("/evals",{body:t,...n})}retrieve(t,n){return this._client.get(M`/evals/${t}`,n)}update(t,n,r){return this._client.post(M`/evals/${t}`,{body:n,...r})}list(t={},n){return this._client.getAPIList("/evals",de,{query:t,...n})}delete(t,n){return this._client.delete(M`/evals/${t}`,n)}}ru.Runs=nu;let Ep=class extends H{create(t,n){return this._client.post("/files",Sn({body:t,...n},this._client))}retrieve(t,n){return this._client.get(M`/files/${t}`,n)}list(t={},n){return this._client.getAPIList("/files",de,{query:t,...n})}delete(t,n){return this._client.delete(M`/files/${t}`,n)}content(t,n){return this._client.get(M`/files/${t}/content`,{...n,headers:z([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}async waitForProcessing(t,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),i=Date.now();let o=await this.retrieve(t);for(;!o.status||!s.has(o.status);)if(await fs(n),o=await this.retrieve(t),Date.now()-i>r)throw new Vl({message:`Giving up on waiting for file ${t} to finish processing after ${r} milliseconds.`});return o}};class Ip extends H{}let jp=class extends H{run(t,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:t,...n})}validate(t,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:t,...n})}};class su extends H{constructor(){super(...arguments),this.graders=new jp(this._client)}}su.Graders=jp;class Np extends H{create(t,n,r){return this._client.getAPIList(M`/fine_tuning/checkpoints/${t}/permissions`,so,{body:n,method:"post",...r})}retrieve(t,n={},r){return this._client.getAPIList(M`/fine_tuning/checkpoints/${t}/permissions`,de,{query:n,...r})}delete(t,n,r){const{fine_tuned_model_checkpoint:s}=n;return this._client.delete(M`/fine_tuning/checkpoints/${s}/permissions/${t}`,r)}}let iu=class extends H{constructor(){super(...arguments),this.permissions=new Np(this._client)}};iu.Permissions=Np;class Pp extends H{list(t,n={},r){return this._client.getAPIList(M`/fine_tuning/jobs/${t}/checkpoints`,de,{query:n,...r})}}class ou extends H{constructor(){super(...arguments),this.checkpoints=new Pp(this._client)}create(t,n){return this._client.post("/fine_tuning/jobs",{body:t,...n})}retrieve(t,n){return this._client.get(M`/fine_tuning/jobs/${t}`,n)}list(t={},n){return this._client.getAPIList("/fine_tuning/jobs",de,{query:t,...n})}cancel(t,n){return this._client.post(M`/fine_tuning/jobs/${t}/cancel`,n)}listEvents(t,n={},r){return this._client.getAPIList(M`/fine_tuning/jobs/${t}/events`,de,{query:n,...r})}pause(t,n){return this._client.post(M`/fine_tuning/jobs/${t}/pause`,n)}resume(t,n){return this._client.post(M`/fine_tuning/jobs/${t}/resume`,n)}}ou.Checkpoints=Pp;class lr extends H{constructor(){super(...arguments),this.methods=new Ip(this._client),this.jobs=new ou(this._client),this.checkpoints=new iu(this._client),this.alpha=new su(this._client)}}lr.Methods=Ip;lr.Jobs=ou;lr.Checkpoints=iu;lr.Alpha=su;class Ap extends H{}class au extends H{constructor(){super(...arguments),this.graderModels=new Ap(this._client)}}au.GraderModels=Ap;class Rp extends H{createVariation(t,n){return this._client.post("/images/variations",Sn({body:t,...n},this._client))}edit(t,n){return this._client.post("/images/edits",Sn({body:t,...n},this._client))}generate(t,n){return this._client.post("/images/generations",{body:t,...n})}}class Mp extends H{retrieve(t,n){return this._client.get(M`/models/${t}`,n)}list(t){return this._client.getAPIList("/models",so,t)}delete(t,n){return this._client.delete(M`/models/${t}`,n)}}class Op extends H{create(t,n){return this._client.post("/moderations",{body:t,...n})}}function m0(e,t){return!t||!y0(t)?{...e,output_parsed:null,output:e.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:Tp(e,t)}function Tp(e,t){const n=e.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:x0(t,s)};if(s.type==="message"){const i=s.content.map(o=>o.type==="output_text"?{...o,parsed:g0(t,o.text)}:o);return{...s,content:i}}return s}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||Lp(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const i of s.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),r}function g0(e,t){var n,r,s,i;return((r=(n=e.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((s=e.text)==null?void 0:s.format)?((i=e.text)==null?void 0:i.format).$parseRaw(t):JSON.parse(t)}function y0(e){var t;return!!Kl((t=e.text)==null?void 0:t.format)}function v0(e){return(e==null?void 0:e.$brand)==="auto-parseable-tool"}function w0(e,t){return e.find(n=>n.type==="function"&&n.name===t)}function x0(e,t){const n=w0(e.tools??[],t.name);return{...t,...t,parsed_arguments:v0(n)?n.$parseRaw(t.arguments):n!=null&&n.strict?JSON.parse(t.arguments):null}}function Lp(e){const t=[];for(const n of e.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&t.push(r.text);e.output_text=t.join("")}var An,zs,zt,Us,Yc,Zc,ed,td;class lu extends Xl{constructor(t){super(),An.add(this),zs.set(this,void 0),zt.set(this,void 0),Us.set(this,void 0),W(this,zs,t)}static createResponse(t,n,r){const s=new lu(n);return s._run(()=>s._createOrRetrieveResponse(t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(t,n,r){var a;const s=r==null?void 0:r.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),S(this,An,"m",Yc).call(this);let i,o=null;"response_id"in n?(i=await t.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=n.starting_after??null):i=await t.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const l of i)S(this,An,"m",Zc).call(this,l,o);if((a=i.controller.signal)!=null&&a.aborted)throw new it;return S(this,An,"m",ed).call(this)}[(zs=new WeakMap,zt=new WeakMap,Us=new WeakMap,An=new WeakSet,Yc=function(){this.ended||W(this,zt,void 0)},Zc=function(n,r){if(this.ended)return;const s=(o,a)=>{(r==null||a.sequence_number>r)&&this._emit(o,a)},i=S(this,An,"m",td).call(this,n);switch(s("event",n),n.type){case"response.output_text.delta":{const o=i.output[n.output_index];if(!o)throw new B(`missing output at index ${n.output_index}`);if(o.type==="message"){const a=o.content[n.content_index];if(!a)throw new B(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new B(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...n,snapshot:a.text})}break}case"response.function_call_arguments.delta":{const o=i.output[n.output_index];if(!o)throw new B(`missing output at index ${n.output_index}`);o.type==="function_call"&&s("response.function_call_arguments.delta",{...n,snapshot:o.arguments});break}default:s(n.type,n);break}},ed=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");const n=S(this,zt,"f");if(!n)throw new B("request ended without sending any events");W(this,zt,void 0);const r=_0(n,S(this,zs,"f"));return W(this,Us,r),r},td=function(n){let r=S(this,zt,"f");if(!r){if(n.type!=="response.created")throw new B(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=W(this,zt,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const s=r.output[n.output_index];if(!s)throw new B(`missing output at index ${n.output_index}`);s.type==="message"&&s.content.push(n.part);break}case"response.output_text.delta":{const s=r.output[n.output_index];if(!s)throw new B(`missing output at index ${n.output_index}`);if(s.type==="message"){const i=s.content[n.content_index];if(!i)throw new B(`missing content at index ${n.content_index}`);if(i.type!=="output_text")throw new B(`expected content to be 'output_text', got ${i.type}`);i.text+=n.delta}break}case"response.function_call_arguments.delta":{const s=r.output[n.output_index];if(!s)throw new B(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.completed":{W(this,zt,n.response);break}}return r},Symbol.asyncIterator)](){const t=[],n=[];let r=!1;return this.on("event",s=>{const i=n.shift();i?i.resolve(s):t.push(s)}),this.on("end",()=>{r=!0;for(const s of n)s.resolve(void 0);n.length=0}),this.on("abort",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),this.on("error",s=>{r=!0;for(const i of n)i.reject(s);n.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((i,o)=>n.push({resolve:i,reject:o})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const t=S(this,Us,"f");if(!t)throw new B("stream ended without producing a ChatCompletion");return t}}function _0(e,t){return m0(e,t)}class $p extends H{list(t,n={},r){return this._client.getAPIList(M`/responses/${t}/input_items`,de,{query:n,...r})}}class uu extends H{constructor(){super(...arguments),this.inputItems=new $p(this._client)}create(t,n){return this._client.post("/responses",{body:t,...n,stream:t.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Lp(r),r))}retrieve(t,n={},r){return this._client.get(M`/responses/${t}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1})}delete(t,n){return this._client.delete(M`/responses/${t}`,{...n,headers:z([{Accept:"*/*"},n==null?void 0:n.headers])})}parse(t,n){return this._client.responses.create(t,n)._thenUnwrap(r=>Tp(r,t))}stream(t,n){return lu.createResponse(this._client,t,n)}cancel(t,n){return this._client.post(M`/responses/${t}/cancel`,n)}}uu.InputItems=$p;class bp extends H{create(t,n,r){return this._client.post(M`/uploads/${t}/parts`,Sn({body:n,...r},this._client))}}class cu extends H{constructor(){super(...arguments),this.parts=new bp(this._client)}create(t,n){return this._client.post("/uploads",{body:t,...n})}cancel(t,n){return this._client.post(M`/uploads/${t}/cancel`,n)}complete(t,n,r){return this._client.post(M`/uploads/${t}/complete`,{body:n,...r})}}cu.Parts=bp;const k0=async e=>{const t=await Promise.allSettled(e),n=t.filter(s=>s.status==="rejected");if(n.length){for(const s of n)console.error(s.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const s of t)s.status==="fulfilled"&&r.push(s.value);return r};class Fp extends H{create(t,n,r){return this._client.post(M`/vector_stores/${t}/file_batches`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(M`/vector_stores/${s}/file_batches/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}cancel(t,n,r){const{vector_store_id:s}=n;return this._client.post(M`/vector_stores/${s}/file_batches/${t}/cancel`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n);return await this.poll(t,s.id,r)}listFiles(t,n,r){const{vector_store_id:s,...i}=n;return this._client.getAPIList(M`/vector_stores/${s}/file_batches/${t}/files`,de,{query:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async poll(t,n,r){var i;const s=z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const{data:o,response:a}=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r!=null&&r.pollIntervalMs)l=r.pollIntervalMs;else{const c=a.headers.get("openai-poll-after-ms");if(c){const g=parseInt(c);isNaN(g)||(l=g)}}await fs(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(t,{files:n,fileIds:r=[]},s){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=(s==null?void 0:s.maxConcurrency)??5,o=Math.min(i,n.length),a=this._client,l=n.values(),c=[...r];async function g(m){for(let y of m){const x=await a.files.create({file:y,purpose:"assistants"},s);c.push(x.id)}}const h=Array(o).fill(l).map(g);return await k0(h),await this.createAndPoll(t,{file_ids:c})}}class Dp extends H{create(t,n,r){return this._client.post(M`/vector_stores/${t}/files`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(t,n,r){const{vector_store_id:s}=n;return this._client.get(M`/vector_stores/${s}/files/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(t,n,r){const{vector_store_id:s,...i}=n;return this._client.post(M`/vector_stores/${s}/files/${t}`,{body:i,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t,n={},r){return this._client.getAPIList(M`/vector_stores/${t}/files`,de,{query:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(t,n,r){const{vector_store_id:s}=n;return this._client.delete(M`/vector_stores/${s}/files/${t}`,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}async createAndPoll(t,n,r){const s=await this.create(t,n,r);return await this.poll(t,s.id,r)}async poll(t,n,r){var i;const s=z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((i=r==null?void 0:r.pollIntervalMs)==null?void 0:i.toString())??void 0}]);for(;;){const o=await this.retrieve(n,{vector_store_id:t},{...r,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let l=5e3;if(r!=null&&r.pollIntervalMs)l=r.pollIntervalMs;else{const c=o.response.headers.get("openai-poll-after-ms");if(c){const g=parseInt(c);isNaN(g)||(l=g)}}await fs(l);break;case"failed":case"completed":return a}}}async upload(t,n,r){const s=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(t,{file_id:s.id},r)}async uploadAndPoll(t,n,r){const s=await this.upload(t,n,r);return await this.poll(t,s.id,r)}content(t,n,r){const{vector_store_id:s}=n;return this._client.getAPIList(M`/vector_stores/${s}/files/${t}/content`,so,{...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}class ao extends H{constructor(){super(...arguments),this.files=new Dp(this._client),this.fileBatches=new Fp(this._client)}create(t,n){return this._client.post("/vector_stores",{body:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(t,n){return this._client.get(M`/vector_stores/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(t,n,r){return this._client.post(M`/vector_stores/${t}`,{body:n,...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}list(t={},n){return this._client.getAPIList("/vector_stores",de,{query:t,...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(t,n){return this._client.delete(M`/vector_stores/${t}`,{...n,headers:z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}search(t,n,r){return this._client.getAPIList(M`/vector_stores/${t}/search`,so,{body:n,method:"post",...r,headers:z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}}ao.Files=Dp;ao.FileBatches=Fp;var qa,du,ai,zp;class X{constructor({baseURL:t=vr("OPENAI_BASE_URL"),apiKey:n=vr("OPENAI_API_KEY"),organization:r=vr("OPENAI_ORG_ID")??null,project:s=vr("OPENAI_PROJECT_ID")??null,...i}={}){if(qa.add(this),ai.set(this,void 0),this.completions=new _p(this),this.chat=new Yl(this),this.embeddings=new Sp(this),this.files=new Ep(this),this.images=new Rp(this),this.audio=new ps(this),this.moderations=new Op(this),this.models=new Mp(this),this.fineTuning=new lr(this),this.graders=new au(this),this.vectorStores=new ao(this),this.beta=new ms(this),this.batches=new mp(this),this.uploads=new cu(this),this.responses=new uu(this),this.evals=new ru(this),this.containers=new tu(this),n===void 0)throw new B("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:n,organization:r,project:s,...i,baseURL:t||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Sv())throw new B(`It looks like you're running in a browser-like environment. This is disabled by default, as it risks exposing your secret API credentials to attackers. If you understand the risks and have appropriate mitigations in place, you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety `);this.baseURL=o.baseURL,this.timeout=o.timeout??du.DEFAULT_TIMEOUT,this.logger=o.logger??console;const a="warn";this.logLevel=a,this.logLevel=zc(o.logLevel,"ClientOptions.logLevel",this)??zc(vr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??a,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Nv(),W(this,ai,Av),this._options=o,this.apiKey=n,this.organization=r,this.project=s}withOptions(t){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,...t})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:t,nulls:n}){}authHeaders(t){return z([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(t){return $v(t,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Rn}`}defaultIdempotencyKey(){return`stainless-node-retry-${wh()}`}makeStatusError(t,n,r,s){return Ee.generate(t,n,r,s)}buildURL(t,n,r){const s=!S(this,qa,"m",zp).call(this)&&r||this.baseURL,i=yv(t)?new URL(t):new URL(s+(s.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),o=this.defaultQuery();return wv(o)||(n={...o,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(t){}async prepareRequest(t,{url:n,options:r}){}get(t,n){return this.methodRequest("get",t,n)}post(t,n){return this.methodRequest("post",t,n)}patch(t,n){return this.methodRequest("patch",t,n)}put(t,n){return this.methodRequest("put",t,n)}delete(t,n){return this.methodRequest("delete",t,n)}methodRequest(t,n,r){return this.request(Promise.resolve(r).then(s=>({method:t,path:n,...s})))}request(t,n=null){return new ro(this,this.makeRequest(t,n,void 0))}async makeRequest(t,n,r){var f,d;const s=await t,i=s.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(s);const{req:o,url:a,timeout:l}=this.buildRequest(s,{retryCount:i-n});await this.prepareRequest(o,{url:a,options:s});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(Pe(this).debug(`[${c}] sending request`,un({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),(f=s.signal)!=null&&f.aborted)throw new it;const m=new AbortController,y=await this.fetchWithTimeout(a,o,l,m).catch(Da),x=Date.now();if(y instanceof Error){const p=`retrying, ${n} attempts remaining`;if((d=s.signal)!=null&&d.aborted)throw new it;const v=Fa(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(n)return Pe(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${p}`),Pe(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${p})`,un({retryOfRequestLogID:r,url:a,durationMs:x-h,message:y.message})),this.retryRequest(s,n,r??c);throw Pe(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),Pe(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,un({retryOfRequestLogID:r,url:a,durationMs:x-h,message:y.message})),v?new Vl:new to({cause:y})}const w=[...y.headers.entries()].filter(([p])=>p==="x-request-id").map(([p,v])=>", "+p+": "+JSON.stringify(v)).join(""),k=`[${c}${g}${w}] ${o.method} ${a} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${x-h}ms`;if(!y.ok){const p=this.shouldRetry(y);if(n&&p){const O=`retrying, ${n} attempts remaining`;return await Pv(y.body),Pe(this).info(`${k} - ${O}`),Pe(this).debug(`[${c}] response error (${O})`,un({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:x-h})),this.retryRequest(s,n,r??c,y.headers)}const v=p?"error; no more retries left":"error; not retryable";Pe(this).info(`${k} - ${v}`);const E=await y.text().catch(O=>Da(O).message),_=kv(E),C=_?void 0:E;throw Pe(this).debug(`[${c}] response error (${v})`,un({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:C,durationMs:Date.now()-h})),this.makeStatusError(y.status,_,C,y.headers)}return Pe(this).info(k),Pe(this).debug(`[${c}] response start`,un({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:x-h})),{response:y,options:s,controller:m,requestLogID:c,retryOfRequestLogID:r,startTime:h}}getAPIList(t,n,r){return this.requestAPIList(n,{method:"get",path:t,...r})}requestAPIList(t,n){const r=this.makeRequest(n,null,void 0);return new Vv(this,r,t)}async fetchWithTimeout(t,n,r,s){const{signal:i,method:o,...a}=n||{};i&&i.addEventListener("abort",()=>s.abort());const l=setTimeout(()=>s.abort(),r),c=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,g={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...a};o&&(g.method=o.toUpperCase());try{return await this.fetch.call(void 0,t,g)}finally{clearTimeout(l)}}shouldRetry(t){const n=t.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,n,r,s){let i;const o=s==null?void 0:s.get("retry-after-ms");if(o){const l=parseFloat(o);Number.isNaN(l)||(i=l)}const a=s==null?void 0:s.get("retry-after");if(a&&!i){const l=parseFloat(a);Number.isNaN(l)?i=Date.parse(a)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=t.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(n,l)}return await fs(i),this.makeRequest(t,n-1,r)}calculateDefaultRetryTimeoutMillis(t,n){const i=n-t,o=Math.min(.5*Math.pow(2,i),8),a=1-Math.random()*.25;return o*a*1e3}buildRequest(t,{retryCount:n=0}={}){const r={...t},{method:s,path:i,query:o,defaultBaseURL:a}=r,l=this.buildURL(i,o,a);"timeout"in r&&_v("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:g}=this.buildBody({options:r}),h=this.buildHeaders({options:t,method:s,bodyHeaders:c,retryCount:n});return{req:{method:s,headers:h,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&g instanceof globalThis.ReadableStream&&{duplex:"half"},...g&&{body:g},...this.fetchOptions??{},...r.fetchOptions??{}},url:l,timeout:r.timeout}}buildHeaders({options:t,method:n,bodyHeaders:r,retryCount:s}){let i={};this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=t.idempotencyKey);const o=z([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...t.timeout?{"X-Stainless-Timeout":String(Math.trunc(t.timeout/1e3))}:{},...jv(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this.authHeaders(t),this._options.defaultHeaders,r,t.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:t,headers:n}}){if(!t)return{bodyHeaders:void 0,body:void 0};const r=z([n]);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&r.values.has("content-type")||t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||globalThis.ReadableStream&&t instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:t}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Rh(t)}:S(this,ai,"f").call(this,{body:t,headers:r})}}du=X,ai=new WeakMap,qa=new WeakSet,zp=function(){return this.baseURL!=="https://api.openai.com/v1"};X.OpenAI=du;X.DEFAULT_TIMEOUT=6e5;X.OpenAIError=B;X.APIError=Ee;X.APIConnectionError=to;X.APIConnectionTimeoutError=Vl;X.APIUserAbortError=it;X.NotFoundError=Sh;X.ConflictError=Ch;X.RateLimitError=Ih;X.BadRequestError=xh;X.AuthenticationError=_h;X.InternalServerError=jh;X.PermissionDeniedError=kh;X.UnprocessableEntityError=Eh;X.toFile=Jv;X.Completions=_p;X.Chat=Yl;X.Embeddings=Sp;X.Files=Ep;X.Images=Rp;X.Audio=ps;X.Moderations=Op;X.Models=Mp;X.FineTuning=lr;X.Graders=au;X.VectorStores=ao;X.Beta=ms;X.Batches=mp;X.Uploads=cu;X.Responses=uu;X.Evals=ru;X.Containers=tu;const S0=e=>{const[t,n]=$.useState(null),[r,s]=$.useState(!1),i=$.useCallback(async(h,m)=>{if(!e)throw new Error("OpenAI API key is required");s(!0),n(null);try{const w=(await new X({apiKey:e,dangerouslyAllowBrowser:!0}).responses.create({model:"gpt-4o",input:[{role:"user",content:[{type:"input_text",text:`Edit this image according to the following instruction: ${m} Keep the overall composition and style similar, but make the requested changes. Generate a high-quality edited version of this image.`},{type:"input_image",image_url:h,detail:"high"}]}],tools:[{type:"image_generation",quality:"high"}]})).output.filter(f=>f.type==="image_generation_call").map(f=>f.result);if(w.length===0)throw new Error("No image generated by GPT Image 1");return`data:image/png;base64,${w[0]}`}catch(y){const x=y instanceof Error?y.message:"An error occurred while processing the image";throw n(x),new Error(x)}finally{s(!1)}},[e]),o=$.useCallback(async(h,m,y,x)=>{if(!e)throw new Error("OpenAI API key is required");s(!0),n(null);try{const w=new X({apiKey:e,dangerouslyAllowBrowser:!0});if(h)try{const _=new Image;_.onload=()=>{console.log("Original image dimensions:",{width:_.width,height:_.height,dataUrlLength:h.length})},_.src=h}catch(_){console.warn("Could not load image for dimension check:",_)}let k,f;if(x)try{console.log("Uploading mask and original image as files...");const C=await(await fetch(h)).blob(),I=new File([C],"image.png",{type:"image/png"});console.log("🖼️ ORIGINAL IMAGE BEING UPLOADED:"),console.log("Data URL (copy to browser to view):",h.substring(0,100)+"..."),console.log("Blob size:",C.size,"bytes"),console.log("Blob type:",C.type);const O=await w.files.create({file:I,purpose:"vision"});f=O.id,console.log("Original image uploaded with file ID:",f);let j=x;if(x.startsWith("MASK:")){console.log("Converting compact mask to PNG...");const U=av(x);if(!U)throw new Error("Failed to convert compact mask to PNG");j=U,console.log("Compact mask converted successfully"),console.log("Original compact mask:",x.substring(0,200)+"...")}console.log("🎭 MASK IMAGE BEING UPLOADED:"),console.log("Mask data URL (copy to browser to view):",j),console.log("Mask data length:",j.length),console.log("📥 INSPECT UPLOADED FILES:"),console.log('Right-click and "Save link as..." to download:'),console.log("Original image:",h),console.log("Mask image:",j);const b=await(await fetch(j)).blob();console.log("Mask blob size:",b.size,"bytes"),console.log("Mask blob type:",b.type);try{const U=new Image;U.onload=()=>{console.log("Mask image dimensions:",{width:U.width,height:U.height}),(U.width===0||U.height===0)&&console.error("❌ MASK HAS ZERO DIMENSIONS!");const Y=document.createElement("canvas"),ee=Y.getContext("2d");Y.width=U.width,Y.height=U.height,ee==null||ee.drawImage(U,0,0);const A=ee==null?void 0:ee.getImageData(0,0,Y.width,Y.height);if(A){let D=!1;for(let V=3;V0&&(We>128&&He>128&&et>128?F++:K++)}console.log("Mask pixel analysis:",{whitePixels:F,blackPixels:K,total:F+K}),F===0&&K===0?console.error("❌ MASK APPEARS TO BE COMPLETELY TRANSPARENT!"):F===0?console.error("❌ MASK HAS NO WHITE PIXELS (nothing to edit)!"):K===0&&console.warn("⚠️ MASK HAS NO BLACK PIXELS (will edit entire image)!")}},U.onerror=Y=>{console.error("❌ FAILED TO LOAD MASK IMAGE:",Y)},U.src=j}catch(U){console.warn("Could not load mask for dimension check:",U)}const T=new File([b],"mask.png",{type:"image/png"}),R=await w.files.create({file:T,purpose:"vision"});k=R.id,console.log("Mask uploaded with file ID:",k),console.log("Uploaded files details:",{originalImage:{id:O.id,bytes:O.bytes,filename:O.filename},mask:{id:R.id,bytes:R.bytes,filename:R.filename}})}catch(_){if(console.error("Failed to upload files:",_),_ instanceof Error){if(_.message.includes("size")||_.message.includes("dimension"))throw new Error("File upload failed: The mask dimensions don't match the image. Please try recreating the mask.");if(_.message.includes("format"))throw new Error("File upload failed: Invalid image format. Please ensure the mask is a valid PNG with alpha channel.")}throw new Error("Failed to upload image and mask files. Please try creating a simpler mask.")}const d=x&&f?[{type:"input_text",text:m},{type:"input_image",file_id:f,detail:"high"}]:[{type:"input_text",text:`Generate an edited version of this image: ${m}`},{type:"input_image",image_url:h,detail:"high"}],p=[{type:"image_generation",quality:"high",partial_images:2,...k&&{input_image_mask:{file_id:k}}}];console.log("Tools configuration:",JSON.stringify(p,null,2)),console.log("Input content:",JSON.stringify(d,null,2));const v=await w.responses.create({model:"gpt-4o",input:[{role:"user",content:d}],tools:p,stream:!0});let E=null;for await(const _ of v)if(console.log("Stream event type:",_.type),console.log("Stream event data:",JSON.stringify(_,null,2)),_.type==="response.image_generation_call.partial_image"){const C=`data:image/png;base64,${_.partial_image_b64}`;y({partialImage:C,partialIndex:_.partial_image_index,isComplete:!1})}else if(_.type==="response.completed"){const C=_.response;if(console.log("Response completed:",C),C!=null&&C.output){console.log("Response output:",C.output);const I=C.output.filter(j=>j.type==="message").flatMap(j=>j.content).filter(j=>j.type==="output_text").map(j=>j.text);if(I.length>0){const j=I[0];if(console.log("API text response:",j),j.toLowerCase().includes("unable to")||j.toLowerCase().includes("cannot")||j.toLowerCase().includes("error")||j.toLowerCase().includes("policy")||j.toLowerCase().includes("inappropriate"))throw new Error(`Content policy rejection: ${j}`);console.log("Success message from API:",j)}const O=C.output.filter(j=>j.type==="image_generation_call").map(j=>j.result);console.log("Image data result:",O),O.length>0&&(E=`data:image/png;base64,${O[0]}`,y({finalImage:E,isComplete:!0}))}}else if(_.type==="response.image_generation_call.done"){console.log("Image generation call done:",_);const C=_.image_generation_call;C!=null&&C.result&&(E=`data:image/png;base64,${C.result}`,y({finalImage:E,isComplete:!0}))}else _.type.includes("image_generation")&&console.log("Image generation event:",_);if(k)try{await w.files.delete(k),console.log("Cleaned up mask file:",k)}catch(_){console.warn("Failed to cleanup mask file:",_)}if(f)try{await w.files.delete(f),console.log("Cleaned up original image file:",f)}catch(_){console.warn("Failed to cleanup original image file:",_)}if(!E){console.log("No final image from stream, trying fallback...");try{const _=await v;if(console.log("Stream response:",_),_!=null&&_.output){const C=_.output.filter(I=>I.type==="image_generation_call").map(I=>I.result);if(C.length>0)return E=`data:image/png;base64,${C[0]}`,y({finalImage:E,isComplete:!0}),E}}catch(_){console.error("Fallback failed:",_)}throw new Error("No final image generated from stream")}return E}catch(w){let k="An error occurred while processing the image";throw w instanceof Error&&(w.message.includes("Content policy rejection")?k=w.message:w.message.includes("API key")||w.message.includes("401")?k="API key error: Please check your OpenAI API key and billing status.":w.message.includes("network")||w.message.includes("fetch")||w.message.includes("connection")?k="Network error: Please check your internet connection and try again.":w.message.includes("rate limit")||w.message.includes("429")?k="Rate limit exceeded: Please wait a moment before trying again.":w.message.includes("quota")||w.message.includes("billing")||w.message.includes("insufficient")?k="Billing error: Your OpenAI account may have insufficient credits.":w.message.includes("No final image generated")?k="Image generation incomplete: The AI service failed to generate a complete image. This may be due to content policy restrictions or technical issues.":w.message.includes("Failed to upload files")?k="File upload failed: There was an issue uploading your image and mask for inpainting. Please try creating a simpler mask.":k=`Processing failed: ${w.message}`),console.error("OpenAI streaming error:",w),n(k),new Error(k)}finally{s(!1)}},[e]),a=$.useCallback(async h=>{if(!e)throw new Error("OpenAI API key is required");s(!0),n(null);try{const x=(await new X({apiKey:e,dangerouslyAllowBrowser:!0}).responses.create({model:"gpt-4.1-mini",input:h,tools:[{type:"image_generation",quality:"high"}]})).output.filter(k=>k.type==="image_generation_call").map(k=>k.result);if(x.length===0)throw new Error("No image generated");return`data:image/png;base64,${x[0]}`}catch(m){const y=m instanceof Error?m.message:"An error occurred while generating the image";throw n(y),new Error(y)}finally{s(!1)}},[e]),l=$.useCallback(async(h,m)=>{if(!e)throw new Error("OpenAI API key is required");s(!0),n(null);try{const x=await new X({apiKey:e,dangerouslyAllowBrowser:!0}).responses.create({model:"gpt-4.1",input:h,tools:[{type:"image_generation",quality:"high",partial_images:2}],stream:!0});let w=null;for await(const k of x)if(console.log("Stream event type:",k.type),console.log("Stream event data:",JSON.stringify(k,null,2)),k.type==="response.image_generation_call.partial_image"){const f=`data:image/png;base64,${k.partial_image_b64}`;m({partialImage:f,partialIndex:k.partial_image_index,isComplete:!1})}else if(k.type==="response.completed"){const f=k.response;if(console.log("Response completed:",f),f!=null&&f.output){console.log("Response output:",f.output);const d=f.output.filter(v=>v.type==="message").flatMap(v=>v.content).filter(v=>v.type==="output_text").map(v=>v.text);if(d.length>0){const v=d[0];if(console.log("API text response:",v),v.toLowerCase().includes("unable to")||v.toLowerCase().includes("cannot")||v.toLowerCase().includes("error")||v.toLowerCase().includes("policy")||v.toLowerCase().includes("inappropriate"))throw new Error(`Content policy rejection: ${v}`);console.log("Success message from API:",v)}const p=f.output.filter(v=>v.type==="image_generation_call").map(v=>v.result);console.log("Image data result:",p),p.length>0&&(w=`data:image/png;base64,${p[0]}`,m({finalImage:w,isComplete:!0}))}}else if(k.type==="response.image_generation_call.done"){console.log("Image generation call done:",k);const f=k.image_generation_call;f!=null&&f.result&&(w=`data:image/png;base64,${f.result}`,m({finalImage:w,isComplete:!0}))}else k.type.includes("image_generation")&&console.log("Image generation event:",k);if(!w){console.log("No final image from stream, trying fallback...");try{const k=await x;if(console.log("Stream response:",k),k!=null&&k.output){const f=k.output.filter(d=>d.type==="image_generation_call").map(d=>d.result);if(f.length>0)return w=`data:image/png;base64,${f[0]}`,m({finalImage:w,isComplete:!0}),w}}catch(k){console.error("Fallback failed:",k)}throw new Error("No final image generated from stream")}return w}catch(y){let x="An error occurred while generating the image";throw y instanceof Error&&(y.message.includes("Content policy rejection")?x=y.message:y.message.includes("API key")||y.message.includes("401")?x="API key error: Please check your OpenAI API key and billing status.":y.message.includes("network")||y.message.includes("fetch")||y.message.includes("connection")?x="Network error: Please check your internet connection and try again.":y.message.includes("rate limit")||y.message.includes("429")?x="Rate limit exceeded: Please wait a moment before trying again.":y.message.includes("quota")||y.message.includes("billing")||y.message.includes("insufficient")?x="Billing error: Your OpenAI account may have insufficient credits.":y.message.includes("No final image generated")?x="Image generation incomplete: The AI service failed to generate a complete image. This may be due to content policy restrictions or technical issues.":x=`Generation failed: ${y.message}`),console.error("OpenAI text-to-image error:",y),n(x),new Error(x)}finally{s(!1)}},[e]),c=$.useCallback(async h=>{var m,y,x;if(!e)throw new Error("OpenAI API key is required");try{return((x=(y=(m=(await new X({apiKey:e,dangerouslyAllowBrowser:!0}).chat.completions.create({model:"gpt-4o",messages:[{role:"user",content:[{type:"text",text:"Generate a concise, accessibility-friendly alt text for this image. Focus on the main subject and important visual elements. Keep it under 100 characters and descriptive for screen readers."},{type:"image_url",image_url:{url:h,detail:"low"}}]}],max_tokens:100})).choices[0])==null?void 0:m.message)==null?void 0:y.content)==null?void 0:x.trim())||""}catch(w){return console.error("Error generating alt text:",w),""}},[e]),g=$.useCallback(async()=>{if(!e)return!1;try{return await new X({apiKey:e,dangerouslyAllowBrowser:!0}).models.list(),!0}catch{return!1}},[e]);return{processImage:i,processImageWithStreaming:o,generateImageFromText:a,generateImageFromTextWithStreaming:l,generateAltText:c,testApiKey:g,error:t,isLoading:r}};class C0{constructor(t,n,r){ys(this,"spaceId");ys(this,"managementToken");ys(this,"baseUrl");this.spaceId=t,this.managementToken=n,this.baseUrl=this.getBaseUrl(r)}getBaseUrl(t){switch(t){case"us":return"https://api-us.storyblok.com/v1";case"ca":return"https://api-ca.storyblok.com/v1";case"ap":return"https://api-ap.storyblok.com/v1";case"cn":return"https://api.storyblokchina.cn/v1";case"eu":default:return"https://mapi.storyblok.com/v1"}}get headers(){return{Authorization:this.managementToken,"Content-Type":"application/json"}}async getAssets(t=1,n=25){try{const r=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets?page=${t}&per_page=${n}&search_term=&filter_query[content_type]=image/`,{headers:this.headers});if(!r.ok)throw new Error(`Failed to fetch assets: ${r.statusText}`);const s=await r.json();return{assets:s.assets||[],total:s.total||0}}catch(r){throw console.error("Error fetching assets:",r),new Error("Failed to fetch Storyblok assets")}}async uploadAsset(t,n,r,s,i){try{const o=nv(t),a=await this.getSignedResponse(n,i);return await this.uploadToS3(a,o,n),await this.finalizeUpload(a.id,r,s)}catch(o){throw console.error("Error uploading asset:",o),new Error(`Failed to upload asset to Storyblok: ${o instanceof Error?o.message:"Unknown error"}`)}}async getSignedResponse(t,n){const r={filename:t,validate_upload:1};n&&(r.asset_folder_id=n);const s=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets/`,{method:"POST",headers:this.headers,body:JSON.stringify(r)});if(!s.ok){const i=await s.json().catch(()=>({}));throw new Error(`Failed to get signed response: ${s.statusText}. ${i.message||""}`)}return await s.json()}async uploadToS3(t,n,r){const s=new FormData;for(const o in t.fields)s.append(o,t.fields[o]);s.append("file",n,r);const i=await fetch(t.post_url,{method:"POST",body:s});if(!i.ok)throw new Error(`Failed to upload to S3: ${i.statusText}`)}async finalizeUpload(t,n,r){const s=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets/${t}/finish_upload`,{method:"GET",headers:this.headers});if(!s.ok){const o=await s.json().catch(()=>({}));throw new Error(`Failed to finalize upload: ${s.statusText}. ${o.message||""}`)}let i=await s.json();if(i=i.asset||i,n||r){const o={};n&&(o.alt=n),r&&(o.title=r),console.log("Updating asset with metadata:",o),i=await this.updateAsset(i.id,o),console.log("Asset updated with metadata:",i)}return i}async updateAsset(t,n){try{const r={meta_data:{...n}},s=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets/${t}`,{method:"PUT",headers:this.headers,body:JSON.stringify(r)});if(!s.ok){const i=await s.text();throw new Error(`Failed to update asset: ${s.statusText} - ${i}`)}return console.log("Asset update request successful. Re-fetching asset to ensure fresh data."),this.getAsset(t)}catch(r){throw console.error("Error updating asset:",r),new Error(`Failed to update Storyblok asset: ${r instanceof Error?r.message:"Check console for details"}`)}}async deleteAsset(t){try{const n=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets/${t}`,{method:"DELETE",headers:this.headers});if(!n.ok)throw new Error(`Failed to delete asset: ${n.statusText}`)}catch(n){throw console.error("Error deleting asset:",n),new Error("Failed to delete Storyblok asset")}}async getAsset(t){try{const n=await fetch(`${this.baseUrl}/spaces/${this.spaceId}/assets/${t}`,{headers:this.headers});if(!n.ok)throw new Error(`Failed to fetch asset: ${n.statusText}`);const r=await n.json();return r.asset||r}catch(n){throw console.error("Error fetching asset:",n),new Error("Failed to fetch Storyblok asset")}}}const E0=()=>{var pu,mu,gu,yu,vu;const{type:e,data:t,actions:n}=tv({validateContent:Q=>({content:Q,errors:[]})}),[r,s]=$.useState("mode-choice"),[i,o]=$.useState(((pu=t==null?void 0:t.content)==null?void 0:pu.originalImage)||null),[a,l]=$.useState(((mu=t==null?void 0:t.content)==null?void 0:mu.prompt)||""),[c,g]=$.useState(((gu=t==null?void 0:t.content)==null?void 0:gu.editedImage)||null),[h,m]=$.useState(((yu=t==null?void 0:t.content)==null?void 0:yu.versions)||[]),[y,x]=$.useState(!1),[w,k]=$.useState(!1),[f,d]=$.useState(null),[p,v]=$.useState(0),[E,_]=$.useState(0),[C,I]=$.useState("full"),[O,j]=$.useState(null),[P,b]=$.useState(""),[T,R]=$.useState(""),[U,Y]=$.useState(null),[ee,A]=$.useState(null),{processImageWithStreaming:D,generateImageFromTextWithStreaming:F,generateAltText:K,error:V}=S0(((vu=t==null?void 0:t.options)==null?void 0:vu.openaiApiKey)||"");$.useEffect(()=>{if(ee){const Q=setTimeout(()=>{A(null)},5e3);return()=>clearTimeout(Q)}},[ee]);const We=(Q,fe)=>{A({type:Q,message:fe,timestamp:Date.now()})},He=()=>{var fe;let Q="empty";return V?Q="error":c?Q="completed":y||w?Q="in-progress":(fe=t==null?void 0:t.options)!=null&&fe.openaiApiKey&&(Q="setup"),{originalImage:i,editedImage:c,prompt:a,altText:T,versions:h,editMode:C,mask:O,status:Q,lastUpdated:Date.now()}};if($.useEffect(()=>{if(e==="loaded"&&!(t!=null&&t.content)){const Q={originalImage:null,editedImage:null,prompt:"",altText:"",versions:[],editMode:"full",mask:null,status:"empty",lastUpdated:Date.now()};n.setContent(Q)}},[e,t==null?void 0:t.content,n]),$.useEffect(()=>{if(e==="loaded"){const Q=He();n.setContent(Q)}},[e,i,c,a,T,h,C,O,y,w,V,n]),e!=="loaded")return u.jsx("div",{className:"blockart-container",children:u.jsxs("div",{className:"blockart-content",children:[u.jsx("div",{className:"blockart-title",children:"BlockArt"}),u.jsxs("div",{style:{textAlign:"center",padding:"2rem",color:"var(--muted)"},children:[u.jsx("div",{className:"spinner",style:{margin:"0 auto var(--space-4) auto"}}),u.jsx("p",{children:"Loading plugin..."})]})]})});const et=async Q=>{if(Q==="upload")s("upload");else if(Q==="select-asset"){const fe=await n.selectAsset();fe&&fe.filename&&(o(fe.filename),s("mode-select"))}else I("generate"),s("prompt")},yt=Q=>{o(Q),s("mode-select")},jn=Q=>{I(Q),s(Q==="generate"?"prompt":Q==="inpaint"?"mask-edit":"prompt")},Bp=Q=>{j(Q),s("prompt")},fu=async Q=>{var tt;if(!((tt=t==null?void 0:t.options)!=null&&tt.openaiApiKey)){Y("OpenAI API key is not set. Please configure it in the plugin options."),s("error");return}if(c){const Ie={imageUrl:c,prompt:P,altText:T,timestamp:Date.now(),editMode:C};m(te=>[Ie,...te])}l(Q),s("processing"),x(!0),d(null),v(0),_(0);const fe=Q;b(fe);try{console.log("Starting OpenAI image generation with prompt:",fe);let Ie;if(C==="generate"?(console.log("Using text-to-image generation mode"),Ie=await F(fe,te=>{if(te.partialImage){d(te.partialImage),v(te.partialIndex||0);const gs=20+(te.partialIndex||0)*30;_(gs)}te.finalImage&&(g(te.finalImage),_(100)),te.isComplete&&s("preview")})):(console.log("Using image editing mode"),Ie=await D(i,fe,te=>{if(te.partialImage){d(te.partialImage),v(te.partialIndex||0);const gs=20+(te.partialIndex||0)*30;_(gs)}te.finalImage&&(g(te.finalImage),_(100)),te.isComplete&&s("preview")},O||void 0)),x(!1),Ie){k(!0);try{console.log("Generating alt text for image...");const te=await K(Ie);te?(R(te),console.log("Alt text generated successfully:",te)):console.warn("Alt text generation returned empty result")}catch(te){console.warn("Failed to generate alt text:",(te==null?void 0:te.message)||te)}finally{k(!1)}}}catch(Ie){console.error("Image processing failed:",Ie),Ie instanceof Error?Y(Ie.message):Y("An unknown error occurred during image processing."),s("error"),x(!1)}},hu=()=>{P&&fu(P)},Wp=Q=>{if(c){const fe={imageUrl:c,prompt:a,altText:T,timestamp:Date.now(),editMode:C};m(tt=>[fe,...tt.filter(Ie=>Ie.timestamp!==Q.timestamp)])}g(Q.imageUrl),l(Q.prompt),R(Q.altText||""),I(Q.editMode),m(fe=>fe.filter(tt=>tt.timestamp!==Q.timestamp))},Hp=async()=>{var Q,fe;if(!c||!((Q=t==null?void 0:t.options)!=null&&Q.spaceId)||!((fe=t==null?void 0:t.options)!=null&&fe.managementToken)){We("error","Missing required configuration to save to Storyblok. Please check your plugin settings.");return}try{x(!0),We("info","Uploading image to Storyblok...");const tt=a.slice(0,20).replace(/[^a-zA-Z0-9]/g,"_")||"generated",Ie=Date.now(),te=`blockart_${tt}_${Ie}.png`,Qp=await new C0(t.options.spaceId,t.options.managementToken,t.options.region).uploadAsset(c,te,T||void 0,a||void 0);g(Qp.filename),We("success",T?"Image saved to Storyblok with alt text successfully!":"Image saved to Storyblok successfully!")}catch(tt){console.error("Failed to save to Storyblok:",tt);const Ie=tt instanceof Error?tt.message:"Unknown error occurred";We("error",`Failed to save image to Storyblok: ${Ie}`)}finally{x(!1)}},lo=()=>{s("mode-choice"),o(null),g(null),l(""),R(""),d(null),v(0),_(0),I("full"),j(null),b(""),m([]),Y(null)},Vp=()=>{switch(r){case"mode-choice":return u.jsxs("div",{className:"mode-choice",children:[u.jsxs("div",{className:"step-header",children:[u.jsx("h2",{children:"Get Started"}),u.jsx("p",{children:"Choose how you want to provide an image for AI editing or generate a new one from scratch."})]}),u.jsxs("div",{className:"choice-options",children:[u.jsxs("div",{className:"choice-option",onClick:()=>et("select-asset"),children:[u.jsx("div",{style:{fontSize:"24px",marginBottom:"var(--space-3)",color:"var(--muted)"},children:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[u.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),u.jsx("circle",{cx:"8.5",cy:"8.5",r:"1.5"}),u.jsx("path",{d:"m21 15-3.086-3.086a2 2 0 00-2.828 0L6 21"})]})}),u.jsx("h3",{children:"Select Existing Asset"}),u.jsx("p",{children:"Choose from your Storyblok media library"})]}),u.jsxs("div",{className:"choice-option",onClick:()=>et("upload"),children:[u.jsx("div",{style:{fontSize:"24px",marginBottom:"var(--space-3)",color:"var(--muted)"},children:u.jsxs("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:[u.jsx("path",{d:"M21 15v4a2 2 0 01-2 2H5a2 2 0 01-2-2v-4"}),u.jsx("polyline",{points:"17 8 12 3 7 8"}),u.jsx("line",{x1:"12",y1:"3",x2:"12",y2:"15"})]})}),u.jsx("h3",{children:"Upload New Image"}),u.jsx("p",{children:"Upload an image file from your computer"})]}),u.jsxs("div",{className:"choice-option",onClick:()=>et("generate"),children:[u.jsx("div",{style:{fontSize:"24px",marginBottom:"var(--space-3)",color:"var(--muted)"},children:u.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:u.jsx("path",{d:"M12 2l3.09 6.26L22 9.27l-5 4.87 1.18 6.88L12 17.77l-6.18 3.25L7 14.14 2 9.27l6.91-1.01L12 2z"})})}),u.jsx("h3",{children:"Generate New Image"}),u.jsx("p",{children:"Create an entirely new image from text description"})]})]})]});case"upload":return u.jsx(lv,{onImageUpload:yt,onBack:()=>s("mode-choice")});case"mode-select":return i?u.jsx(uv,{onModeSelect:jn,onBack:()=>s("upload"),originalImage:i,maskData:O}):null;case"mask-edit":return i?u.jsx(cv,{originalImage:i,onMaskCreated:Bp,onBack:()=>s("mode-select")}):null;case"prompt":return u.jsx(dv,{onSubmit:fu,onBack:()=>{s(C==="generate"?"mode-choice":C==="inpaint"?"mask-edit":"mode-select")},originalImage:i,editMode:C,maskData:O,actions:n});case"processing":return u.jsx(fv,{originalImage:i,isProcessing:y,editMode:C,processedImage:c,partialImage:f,partialIndex:p,streamingProgress:E,maskData:O,status:a?`Processing: "${a}"`:"Processing your image...",onRetry:hu,onCancel:lo});case"preview":return c?u.jsx(pv,{originalImage:i,editedImage:c,prompt:a,altText:T,editMode:C,maskData:O,onSaveToStoryblok:Hp,onStartOver:lo,isSaving:y,isGeneratingAltText:w,versions:h,onRestoreVersion:Wp}):null;case"error":const Q=U||V;return Q?u.jsx(mv,{error:Q,onStartOver:lo,onRetry:()=>{Y(null),hu()},showRetry:!!P&&!(U!=null&&U.includes("API key"))}):null}};return u.jsxs("div",{className:"blockart-container",children:[u.jsxs("div",{className:"blockart-content",children:[u.jsx("h1",{className:"blockart-title",children:"BlockArt"}),Vp()]}),ee&&u.jsx("div",{className:`notification-toast notification-${ee.type}`,children:u.jsxs("div",{className:"notification-content",children:[u.jsxs("div",{className:"notification-icon",children:[ee.type==="success"&&u.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14"}),u.jsx("polyline",{points:"22,4 12,14.01 9,11.01"})]}),ee.type==="error"&&u.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"15",y1:"9",x2:"9",y2:"15"}),u.jsx("line",{x1:"9",y1:"9",x2:"15",y2:"15"})]}),ee.type==="info"&&u.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("circle",{cx:"12",cy:"12",r:"10"}),u.jsx("line",{x1:"12",y1:"16",x2:"12",y2:"12"}),u.jsx("line",{x1:"12",y1:"8",x2:"12.01",y2:"8"})]})]}),u.jsx("span",{className:"notification-message",children:ee.message}),u.jsx("button",{className:"notification-close",onClick:()=>A(null),"aria-label":"Close notification",children:u.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[u.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),u.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})})]})},I0=()=>u.jsx(E0,{}),j0=e=>{const t=document.createElement("div");return t.id="app",t},Up=j0();document.body.appendChild(Up);mh(Up).render(u.jsx(I0,{}));throw new Error("This error can be safely ignored. It is caused by the legacy field plugin API. See issue https://github.com/storyblok/field-plugin/issues/107");