@widgetic/creator 0.4.42 → 0.4.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -49,6 +49,7 @@ declare const CreatorApp: $$__sveltets_2_IsomorphicComponent<{
49
49
  onLimitReached?: CreatorAppProps["onLimitReached"];
50
50
  onCanvasUnavailable?: CreatorAppProps["onCanvasUnavailable"];
51
51
  onCanvasChanged?: CreatorAppProps["onCanvasChanged"];
52
+ replaceAddressBarUrl?: CreatorAppProps["replaceAddressBarUrl"];
52
53
  onReady?: CreatorAppProps["onReady"];
53
54
  /** Partner library for chat/canvas uploads (see `CreatorAppProps.mediaLibrary`). */ mediaLibrary?: CreatorAppProps["mediaLibrary"];
54
55
  /** Optional override for PropsEditor file fields (`purpose: 'field'`). */ mediaLibraryForFields?: CreatorAppProps["mediaLibraryForFields"];
@@ -29,6 +29,6 @@ interface Props {
29
29
  language?: string;
30
30
  languageLocked?: boolean;
31
31
  }
32
- declare const BrandKitPanel: import("svelte").Component<Props, {}, "sub" | "title" | "brandKitEnabled" | "librariesEnabled" | "primary" | "secondary" | "fonts" | "libraries" | "libraryGitUrl" | "libraryFileName" | "libraryUploads" | "fontUploads" | "language">;
32
+ declare const BrandKitPanel: import("svelte").Component<Props, {}, "title" | "sub" | "brandKitEnabled" | "librariesEnabled" | "primary" | "secondary" | "fonts" | "libraries" | "libraryGitUrl" | "libraryFileName" | "libraryUploads" | "fontUploads" | "language">;
33
33
  type BrandKitPanel = ReturnType<typeof BrandKitPanel>;
34
34
  export default BrandKitPanel;
@@ -0,0 +1,49 @@
1
+ <script lang="ts">
2
+ // The design system exposes `Tabs` through its components barrel; a deep `…/components/ui/tabs`
3
+ // import does not resolve with the package `exports` map (`./components/*` → `dist/components/*.js`).
4
+ import { Tabs } from '@widgetic/design-system/components';
5
+ import type { Snippet } from 'svelte';
6
+ import type { EmbeddedSketchMobileTab } from '../embeddedSketchLayout.js';
7
+
8
+ let {
9
+ embedded = false,
10
+ sketchShell = false,
11
+ mobileTab = $bindable<EmbeddedSketchMobileTab>('canvas'),
12
+ tabCanvasLabel,
13
+ tabChatLabel,
14
+ children
15
+ }: {
16
+ embedded?: boolean;
17
+ sketchShell?: boolean;
18
+ mobileTab?: EmbeddedSketchMobileTab;
19
+ tabCanvasLabel: string;
20
+ tabChatLabel: string;
21
+ children: Snippet;
22
+ } = $props();
23
+ </script>
24
+
25
+ {#if embedded}
26
+ <Tabs.Root
27
+ bind:value={mobileTab}
28
+ class="flex min-h-0 flex-1 min-w-0 flex-col {sketchShell ? 'md:contents max-md:flex' : 'contents'}"
29
+ >
30
+ {#if sketchShell}
31
+ <Tabs.List
32
+ class="mx-3 mb-1 mt-2 w-[calc(100%-1.5rem)] shrink-0 md:hidden"
33
+ data-testid="embedded-sketch-mobile-tabs"
34
+ >
35
+ <Tabs.Trigger value="canvas" class="flex-1">{tabCanvasLabel}</Tabs.Trigger>
36
+ <Tabs.Trigger value="chat" class="flex-1">{tabChatLabel}</Tabs.Trigger>
37
+ </Tabs.List>
38
+ {/if}
39
+ <div
40
+ class="embedded-sketch-stage flex min-h-0 min-w-0 flex-1 flex-col max-lg:min-h-0 {sketchShell
41
+ ? 'md:contents max-md:relative max-md:min-h-0'
42
+ : ''}"
43
+ >
44
+ {@render children()}
45
+ </div>
46
+ </Tabs.Root>
47
+ {:else}
48
+ {@render children()}
49
+ {/if}
@@ -0,0 +1,13 @@
1
+ import type { Snippet } from 'svelte';
2
+ import type { EmbeddedSketchMobileTab } from '../embeddedSketchLayout.js';
3
+ type $$ComponentProps = {
4
+ embedded?: boolean;
5
+ sketchShell?: boolean;
6
+ mobileTab?: EmbeddedSketchMobileTab;
7
+ tabCanvasLabel: string;
8
+ tabChatLabel: string;
9
+ children: Snippet;
10
+ };
11
+ declare const EmbeddedSketchViewportShell: import("svelte").Component<$$ComponentProps, {}, "mobileTab">;
12
+ type EmbeddedSketchViewportShell = ReturnType<typeof EmbeddedSketchViewportShell>;
13
+ export default EmbeddedSketchViewportShell;
@@ -38,6 +38,7 @@
38
38
  import HoverTooltip from './HoverTooltip.svelte';
39
39
  import EditableName from './EditableName.svelte';
40
40
  import { errorLabel, useCreatorLanguage } from '../i18n/index.js';
41
+ import { CODEGEN_ERROR_DISPLAY } from '../errors/toUserFriendlyError.js';
41
42
  import { useTextDirection } from '@widgetic/design-system/components/textDirection';
42
43
  import { distanceTowardEnd, opensOnRightOfShape, roomBeforeNeighbour } from '../utils/directionPlacement.js';
43
44
 
@@ -98,6 +99,7 @@
98
99
  export const isCheckingActiveGeneration: boolean = false;
99
100
  export let lastCommitId: string | null = null;
100
101
  export let debugMode: boolean = false;
102
+ $: codegenErrorDisplay = { debugMode, ...CODEGEN_ERROR_DISPLAY };
101
103
  export let forceMockReady: boolean = false;
102
104
  // Passed by CreatorApp but never read here — export const keeps the
103
105
  // init-set contract without the unused-reactive warning.
@@ -1604,7 +1606,12 @@
1604
1606
  }
1605
1607
 
1606
1608
  const status = buildErr?.response?.status ?? buildErr?.status;
1607
- const isRetryable = status === 404 || status === 500 || !status;
1609
+ const isAuthFailure =
1610
+ status === 401 ||
1611
+ status === 403 ||
1612
+ /\bunauthorized\b/i.test(lastBuildErrorMsg);
1613
+ const isRetryable =
1614
+ !isAuthFailure && (status === 404 || status === 500 || !status);
1608
1615
  if (isRetryable && attempt < maxRetries) {
1609
1616
  // console.log(`[WidgetDetails] triggerBuildFromRepo attempt ${attempt}/${maxRetries} failed (${lastBuildErrorMsg}), retrying in ${retryDelayMs}ms...`);
1610
1617
  await new Promise(r => setTimeout(r, retryDelayMs));
@@ -3258,9 +3265,17 @@
3258
3265
  inlinePanelView = 'preview';
3259
3266
  }
3260
3267
  let showRuntimeConsole = false;
3268
+
3269
+ export function toggleRuntimeConsole() {
3270
+ showRuntimeConsole = !showRuntimeConsole;
3271
+ }
3272
+
3273
+ export function isRuntimeConsoleOpen() {
3274
+ return showRuntimeConsole;
3275
+ }
3261
3276
  $: if (!debugMode && showRuntimeConsole) showRuntimeConsole = false;
3262
3277
  /** Chat docked on the right. 30px narrower than the previous 480px column. */
3263
- const DOCKED_CHAT_COLUMN_WIDTH = 450;
3278
+ const DOCKED_CHAT_COLUMN_WIDTH = 440;
3264
3279
  /** Chat plus the console column. The chat-only panel clips the column when it stays at the docked width. */
3265
3280
  const CONSOLE_COLUMN_PANEL_WIDTH = 780;
3266
3281
  let widthBeforeConsole = 0;
@@ -3613,9 +3628,11 @@
3613
3628
  {#if selectedWidgetId}
3614
3629
  <!-- svelte-ignore a11y-no-static-element-interactions -->
3615
3630
  <div
3616
- class="widget-details-floating-shell pointer-events-none overflow-visible {showWidgetDetails ? '' : 'hidden'} {dockRight ? 'widget-details-dock-right absolute inset-y-0 end-0 h-full' : 'fixed'}"
3631
+ class="widget-details-floating-shell pointer-events-none overflow-visible {showWidgetDetails ? '' : 'hidden'} {dockRight
3632
+ ? 'widget-details-dock-right h-full max-lg:w-full max-lg:relative max-lg:inset-auto lg:absolute lg:inset-y-0 lg:end-0 lg:w-[var(--dock-panel-width)] lg:max-w-[var(--dock-panel-width)]'
3633
+ : 'fixed'}"
3617
3634
  style={dockRight
3618
- ? `width: ${consoleColumnOpen ? CONSOLE_COLUMN_PANEL_WIDTH : DOCKED_CHAT_COLUMN_WIDTH}px; z-index: ${panelZIndex};`
3635
+ ? `--dock-panel-width: ${consoleColumnOpen ? CONSOLE_COLUMN_PANEL_WIDTH : DOCKED_CHAT_COLUMN_WIDTH}px; z-index: ${panelZIndex};`
3619
3636
  : `left: ${detailsPanelX}px; /* rtl-ok: the panel is put in pixels from the left edge of the screen, beside its shape, and dragged there */ top: ${detailsPanelY}px; width: ${detailsPanelWidth}px; z-index: ${panelZIndex}; height: ${detailsPanelHeight ? detailsPanelHeight + 'px' : `calc(100vh - ${detailsPanelTopOffset + detailsPanelBottomMargin}px)`};`}
3620
3637
  >
3621
3638
  {#if !dockRight}
@@ -3814,14 +3831,17 @@
3814
3831
  <div class="widget-details-create-status-body min-w-0 flex-1">
3815
3832
  <slot name="code-generation-status" />
3816
3833
  </div>
3834
+ <!-- The docked chat opens the console from its own header icon; this text button is for the floating panel. It stays inside `{#if debugMode}`: the i18n source guard reads that test to leave debug words in English. -->
3817
3835
  {#if debugMode}
3818
- <button
3819
- type="button"
3820
- class="widget-details-console-toggle shrink-0 rounded border px-2 py-0.5 text-[10px] cursor-pointer {dockRight ? 'relative me-2' : 'absolute top-2.5 end-2 z-20'} {showRuntimeConsole ? 'border-green-400 bg-green-50 text-green-700' : 'border-gray-200 bg-white text-gray-600 hover:bg-gray-50'}"
3821
- aria-pressed={showRuntimeConsole}
3822
- title="Show the widget console"
3823
- onclick={() => { showRuntimeConsole = !showRuntimeConsole; }}
3824
- >Console</button>
3836
+ {#if !dockRight}
3837
+ <button
3838
+ type="button"
3839
+ class="widget-details-console-toggle shrink-0 rounded border px-2 py-0.5 text-[10px] cursor-pointer absolute top-2.5 end-2 z-20 {showRuntimeConsole ? 'border-green-400 bg-green-50 text-green-700' : 'border-gray-200 bg-white text-gray-600 hover:bg-gray-50'}"
3840
+ aria-pressed={showRuntimeConsole}
3841
+ title="Show the widget console"
3842
+ onclick={() => { showRuntimeConsole = !showRuntimeConsole; }}
3843
+ >Console</button>
3844
+ {/if}
3825
3845
  {/if}
3826
3846
  {#if dockRight}
3827
3847
  <div class="widget-details-status-version shrink-0 pe-2.5">
@@ -4030,7 +4050,7 @@
4030
4050
  <div class="widget-preview-error-indicator flex flex-col items-center justify-center text-center p-4">
4031
4051
  <div class="text-3xl mb-2">⚠️</div>
4032
4052
  <div class="font-medium text-sm text-red-600 mb-1">{$t('creator.details.previewUnavailable')}</div>
4033
- <div class="text-xs max-w-[200px] text-gray-600 mb-3">{errorLabel(previewError, $t)}</div>
4053
+ <div class="text-xs max-w-[200px] text-gray-600 mb-3">{errorLabel(previewError, $t, { debugMode })}</div>
4034
4054
  {#if !normalizeRepositoryId(selectedWidget)}
4035
4055
  <button type="button" onclick={() => { previewError = null; dispatch('retryRepository', { widgetId: selectedWidgetId }); }} class="px-3 py-1.5 text-xs rounded border border-blue-400 text-blue-600 bg-white hover:bg-blue-50 cursor-pointer font-medium">{$t('creator.details.createRepository')}</button>
4036
4056
  {:else}
@@ -4052,7 +4072,7 @@
4052
4072
  <div class="widget-preview-generation-error flex flex-col items-center justify-center text-center p-4">
4053
4073
  <div class="text-3xl mb-2">⚠️</div>
4054
4074
  <div class="font-medium text-sm text-red-600 mb-1">{$t('creator.status.failed')}</div>
4055
- <div class="text-xs max-w-[220px] text-gray-600 mb-3">{errorLabel(lastGenerationError, $t) || $t('creator.details.fixThePromptOrAttachments')}</div>
4075
+ <div class="text-xs max-w-[220px] text-gray-600 mb-3">{errorLabel(lastGenerationError, $t, codegenErrorDisplay) || $t('creator.details.fixThePromptOrAttachments')}</div>
4056
4076
  <button
4057
4077
  type="button"
4058
4078
  onclick={() => { dispatch('generateNow', { widgetId: selectedWidgetId }); }}
@@ -4180,6 +4200,13 @@
4180
4200
  outline: none;
4181
4201
  box-shadow: none;
4182
4202
  }
4203
+ /** Docked embed chat: column width on lg+ even if Tailwind misses arbitrary lg:w-[var(...)] in dev. */
4204
+ @media (min-width: 1024px) {
4205
+ .widget-details-dock-right.widget-details-floating-shell {
4206
+ width: var(--dock-panel-width);
4207
+ max-width: var(--dock-panel-width);
4208
+ }
4209
+ }
4183
4210
  .widget-details-dock-right :global(.action-bar) {
4184
4211
  flex-wrap: nowrap;
4185
4212
  gap: 0.35rem;
@@ -174,6 +174,8 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
174
174
  closeWidgetDetails?: (options?: {
175
175
  silent?: boolean;
176
176
  }) => void;
177
+ toggleRuntimeConsole?: () => void;
178
+ isRuntimeConsoleOpen?: () => boolean;
177
179
  }, {
178
180
  widgetRename: CustomEvent<any>;
179
181
  fixErrors: CustomEvent<any>;
@@ -276,6 +278,8 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
276
278
  closeWidgetDetails: (options?: {
277
279
  silent?: boolean;
278
280
  }) => void;
281
+ toggleRuntimeConsole: () => void;
282
+ isRuntimeConsoleOpen: () => boolean;
279
283
  }, string>;
280
284
  type WidgetDetails = InstanceType<typeof WidgetDetails>;
281
285
  export default WidgetDetails;
@@ -184,6 +184,11 @@ export interface CreatorAppProps {
184
184
  onPublishStateChanged?: (state: PublishState) => void;
185
185
  /** When true, hides auth screen + top bar; syncs session from site localStorage */
186
186
  embedded?: boolean;
187
+ /**
188
+ * When embedded in SvelteKit, syncs the address bar without tripping the router warning: the host passes
189
+ * `replaceState` from `$app/navigation`. Omitted: `history.replaceState` keeps the existing state object.
190
+ */
191
+ replaceAddressBarUrl?: (href: string) => void;
187
192
  /**
188
193
  * API gateway origin for embedded hosts (e.g. site `PUBLIC_API_URL`).
189
194
  * Without this, the creator falls back to the SDK default, `https://api.widgetic.com/v1` (the production API).
@@ -0,0 +1,9 @@
1
+ /** Breakpoints for embedded sketch creator (Figma Responsive 131:7). */
2
+ export declare const EMBEDDED_SKETCH_DESKTOP_MIN_PX = 1024;
3
+ export declare const EMBEDDED_SKETCH_TABLET_MIN_PX = 768;
4
+ export type EmbeddedSketchViewportLayout = 'beside' | 'stacked' | 'tabbed';
5
+ export type EmbeddedSketchMobileTab = 'canvas' | 'chat';
6
+ export declare function embeddedSketchLayoutForWidth(widthPx: number): EmbeddedSketchViewportLayout;
7
+ /** Chat tab stays active when user is composing (no auto-switch on generation). */
8
+ export declare function shouldKeepMobileChatTabOnGeneration(activeTab: EmbeddedSketchMobileTab): boolean;
9
+ export declare function mobileTabPaneHidden(activeTab: EmbeddedSketchMobileTab, pane: EmbeddedSketchMobileTab): boolean;
@@ -0,0 +1,17 @@
1
+ /** Breakpoints for embedded sketch creator (Figma Responsive 131:7). */
2
+ export const EMBEDDED_SKETCH_DESKTOP_MIN_PX = 1024;
3
+ export const EMBEDDED_SKETCH_TABLET_MIN_PX = 768;
4
+ export function embeddedSketchLayoutForWidth(widthPx) {
5
+ if (widthPx >= EMBEDDED_SKETCH_DESKTOP_MIN_PX)
6
+ return 'beside';
7
+ if (widthPx >= EMBEDDED_SKETCH_TABLET_MIN_PX)
8
+ return 'stacked';
9
+ return 'tabbed';
10
+ }
11
+ /** Chat tab stays active when user is composing (no auto-switch on generation). */
12
+ export function shouldKeepMobileChatTabOnGeneration(activeTab) {
13
+ return activeTab === 'chat';
14
+ }
15
+ export function mobileTabPaneHidden(activeTab, pane) {
16
+ return activeTab !== pane;
17
+ }
@@ -0,0 +1,44 @@
1
+ export type UserFriendlyErrorContext = 'codeGeneration' | 'canvasLoad' | 'generic';
2
+ /** Display options wired through chat and status UI (context literals live here for i18n audits). */
3
+ export declare const CODEGEN_ERROR_DISPLAY: {
4
+ readonly context: "codeGeneration";
5
+ };
6
+ export declare const CANVAS_LOAD_ERROR_DISPLAY: {
7
+ readonly context: "canvasLoad";
8
+ };
9
+ export type UserFriendlyErrorCategory = 'providerNotConfigured' | 'rateLimit' | 'usageLimit' | 'timeout' | 'network' | 'authExpired' | 'notFound' | 'permission' | 'validation' | 'server' | 'unknown';
10
+ export type UserFriendlyErrorOptions = {
11
+ debugMode: boolean;
12
+ context?: UserFriendlyErrorContext;
13
+ };
14
+ export type UserFriendlyErrorResult = {
15
+ userMessage: string;
16
+ technicalDetail: string | null;
17
+ category: UserFriendlyErrorCategory;
18
+ };
19
+ /** Canonical English shown to visitors; single source of truth is the catalog (statusText KNOWN_TEXTS mirrors these). */
20
+ export declare const USER_FRIENDLY_COPY: {
21
+ readonly providerNotConfigured: "Code generation is not available right now. Please try again later.";
22
+ readonly providerNotConfiguredGeneric: "This feature is not available right now. Please try again later.";
23
+ readonly rateLimit: "Too many requests, please try again later.";
24
+ readonly usageLimit: "Usage limit exceeded";
25
+ readonly timeout: "This took too long. Please try again.";
26
+ readonly network: "Could not reach the server. Try again.";
27
+ readonly authExpired: "Authentication expired. Please login again.";
28
+ readonly notFound: "We couldn't find that. It may have been deleted.";
29
+ readonly canvasNotFound: "We couldn't find this sketch. It may have been deleted.";
30
+ readonly permission: "You don't have permission to do that.";
31
+ readonly validation: "Something was wrong with the request. Please check your input and try again.";
32
+ readonly server: "Something went wrong on our side. Please try again in a moment.";
33
+ readonly generic: "Something went wrong. Please try again.";
34
+ readonly codeGenerationFailed: "Code generation failed.";
35
+ };
36
+ /** Strip marks and prefixes the creator adds before showing a stored failure. */
37
+ export declare function stripErrorDecorations(text: string): string;
38
+ /** Whether a stored line still looks like a raw server or runtime error. */
39
+ export declare function isLikelyTechnicalError(text: string): boolean;
40
+ export declare function toUserFriendlyError(error: unknown, options: UserFriendlyErrorOptions): UserFriendlyErrorResult;
41
+ /** What to store or show: friendly text, with technical detail only in debug mode. */
42
+ export declare function formatUserFacingErrorText(error: unknown, options: UserFriendlyErrorOptions): string;
43
+ /** Sanitize a string that is already stored in chat or UI state. */
44
+ export declare function friendlyTextFromStoredError(storedText: string, options: UserFriendlyErrorOptions): string;
@@ -0,0 +1,236 @@
1
+ import { ResponseError } from '@widgetic/api-sdk';
2
+ import { CREATOR_MESSAGES } from '../i18n/messages.js';
3
+ /** Display options wired through chat and status UI (context literals live here for i18n audits). */
4
+ export const CODEGEN_ERROR_DISPLAY = { context: 'codeGeneration' };
5
+ export const CANVAS_LOAD_ERROR_DISPLAY = { context: 'canvasLoad' };
6
+ /** Canonical English shown to visitors; single source of truth is the catalog (statusText KNOWN_TEXTS mirrors these). */
7
+ export const USER_FRIENDLY_COPY = {
8
+ providerNotConfigured: CREATOR_MESSAGES['creator.error.codeGenerationUnavailable'],
9
+ providerNotConfiguredGeneric: CREATOR_MESSAGES['creator.error.featureUnavailable'],
10
+ rateLimit: CREATOR_MESSAGES['creator.error.tooManyRequestsPleaseTry'],
11
+ usageLimit: CREATOR_MESSAGES['creator.error.usageLimitExceeded'],
12
+ timeout: CREATOR_MESSAGES['creator.error.requestTimedOut'],
13
+ network: CREATOR_MESSAGES['creator.error.couldNotReachTheServer'],
14
+ authExpired: CREATOR_MESSAGES['creator.status.authenticationExpired'],
15
+ notFound: CREATOR_MESSAGES['creator.error.resourceNotFound'],
16
+ canvasNotFound: CREATOR_MESSAGES['creator.error.canvasNotFound'],
17
+ permission: CREATOR_MESSAGES['creator.error.permissionDenied'],
18
+ validation: CREATOR_MESSAGES['creator.error.invalidRequest'],
19
+ server: CREATOR_MESSAGES['creator.error.serverError'],
20
+ generic: CREATOR_MESSAGES['creator.error.somethingWentWrong'],
21
+ codeGenerationFailed: CREATOR_MESSAGES['creator.error.codeGenerationFailed'],
22
+ };
23
+ const TECHNICAL_DETAIL_MAX = 300;
24
+ const ENV_KEY_RE = /\b(?:BASETEN|OPENAI|ANTHROPIC|GOOGLE|GEMINI|MISTRAL|COHERE|TOGETHER|FIREWORKS|DEEPSEEK|GROQ)[_\w]*_API_KEY\b/i;
25
+ const MISSING_KEY_RE = /missing api key|api key.*not configured|set \w+ in environment/i;
26
+ const PROVIDER_RE = /provider\s+["'`]|model not found|model unavailable|unavailable model/i;
27
+ const HTTP_STATUS_IN_TEXT_RE = /\b(?:HTTP\s*)?\b[45]\d{2}\b/;
28
+ const STACK_OR_CLASS_RE = /\bat\s+\S+\s*\(|ResponseError|TypeError|ZodError|SyntaxError/i;
29
+ function trimTechnicalDetail(raw) {
30
+ const oneLine = raw.replace(/\s+/g, ' ').trim();
31
+ if (oneLine.length <= TECHNICAL_DETAIL_MAX)
32
+ return oneLine;
33
+ return `${oneLine.slice(0, TECHNICAL_DETAIL_MAX)}…`;
34
+ }
35
+ /** Strip marks and prefixes the creator adds before showing a stored failure. */
36
+ export function stripErrorDecorations(text) {
37
+ let trimmed = text.trim();
38
+ trimmed = trimmed.replace(/^[^\p{L}\p{N}]+\s+/u, '');
39
+ trimmed = trimmed.replace(/^Code generation failed:\s*/i, '');
40
+ return trimmed.trim();
41
+ }
42
+ function readHttpStatus(error) {
43
+ if (error instanceof ResponseError && typeof error.response?.status === 'number') {
44
+ return error.response.status;
45
+ }
46
+ const response = error?.response;
47
+ if (response && typeof response.status === 'number')
48
+ return response.status;
49
+ const code = error?.code;
50
+ if (typeof code === 'number' && code >= 100 && code < 600)
51
+ return code;
52
+ if (typeof code === 'string' && /^\d{3}$/.test(code))
53
+ return Number(code);
54
+ return null;
55
+ }
56
+ function readErrorName(error) {
57
+ if (error instanceof Error && error.name)
58
+ return error.name;
59
+ if (typeof error === 'object' && error !== null && 'name' in error) {
60
+ const name = error.name;
61
+ if (typeof name === 'string')
62
+ return name;
63
+ }
64
+ return '';
65
+ }
66
+ function readRawMessage(error) {
67
+ if (error === undefined || error === null)
68
+ return '';
69
+ if (typeof error === 'string')
70
+ return stripErrorDecorations(error);
71
+ if (typeof error === 'number' || typeof error === 'boolean' || typeof error === 'bigint') {
72
+ return String(error);
73
+ }
74
+ if (error instanceof Error && typeof error.message === 'string') {
75
+ return stripErrorDecorations(error.message);
76
+ }
77
+ if (typeof error === 'object') {
78
+ const obj = error;
79
+ if (typeof obj.message === 'string' && obj.message.trim()) {
80
+ return stripErrorDecorations(obj.message);
81
+ }
82
+ if (typeof obj.error === 'string' && obj.error.trim()) {
83
+ return stripErrorDecorations(obj.error);
84
+ }
85
+ if (obj.error && typeof obj.error === 'object') {
86
+ const nested = readRawMessage(obj.error);
87
+ if (nested)
88
+ return nested;
89
+ }
90
+ try {
91
+ return trimTechnicalDetail(JSON.stringify(error));
92
+ }
93
+ catch {
94
+ return '';
95
+ }
96
+ }
97
+ return '';
98
+ }
99
+ function httpStatusFromText(raw) {
100
+ const match = raw.match(/\b(?:HTTP\s*)?([45]\d{2})\b/i);
101
+ return match ? Number(match[1]) : null;
102
+ }
103
+ function classify(raw, status, errorName, _context) {
104
+ const text = raw.toLowerCase();
105
+ const statusHit = status ?? httpStatusFromText(raw);
106
+ if (statusHit === 429 || /\brate\s*limit|too many requests/i.test(text))
107
+ return 'rateLimit';
108
+ if (statusHit === 402 ||
109
+ /usage limit|quota|credit|plan limit|budget exceeded/i.test(text) ||
110
+ text === 'usage limit exceeded') {
111
+ return 'usageLimit';
112
+ }
113
+ if (statusHit === 401 || /session expired|authentication expired|\bjwt\b/i.test(text))
114
+ return 'authExpired';
115
+ if (statusHit === 404 || /resource not found|not found/i.test(text))
116
+ return 'notFound';
117
+ if (statusHit === 403 || /forbidden|permission denied/i.test(text))
118
+ return 'permission';
119
+ if (statusHit === 400 || /validation|invalid request|bad request|zod/i.test(text))
120
+ return 'validation';
121
+ if ((statusHit !== null && statusHit >= 500) || /internal server error|service unavailable/i.test(text)) {
122
+ return 'server';
123
+ }
124
+ if (MISSING_KEY_RE.test(text) ||
125
+ ENV_KEY_RE.test(raw) ||
126
+ PROVIDER_RE.test(text) ||
127
+ /model not found|model unavailable/i.test(raw)) {
128
+ return 'providerNotConfigured';
129
+ }
130
+ if (/timed out|timeout|abort/i.test(text) || errorName === 'AbortError' || /\bETIMEDOUT\b/.test(raw)) {
131
+ return 'timeout';
132
+ }
133
+ if (/failed to fetch|networkerror|could not reach the server|econnrefused|enotfound|network request failed|widget builder is not reachable|not reachable/i.test(text)) {
134
+ return 'network';
135
+ }
136
+ if (HTTP_STATUS_IN_TEXT_RE.test(raw) || STACK_OR_CLASS_RE.test(raw) || ENV_KEY_RE.test(raw)) {
137
+ return 'unknown';
138
+ }
139
+ if (text.length === 0)
140
+ return 'unknown';
141
+ return 'unknown';
142
+ }
143
+ function messageForCategory(category, context) {
144
+ switch (category) {
145
+ case 'providerNotConfigured':
146
+ return context === 'codeGeneration'
147
+ ? USER_FRIENDLY_COPY.providerNotConfigured
148
+ : USER_FRIENDLY_COPY.providerNotConfiguredGeneric;
149
+ case 'rateLimit':
150
+ return USER_FRIENDLY_COPY.rateLimit;
151
+ case 'usageLimit':
152
+ return USER_FRIENDLY_COPY.usageLimit;
153
+ case 'timeout':
154
+ return USER_FRIENDLY_COPY.timeout;
155
+ case 'network':
156
+ return USER_FRIENDLY_COPY.network;
157
+ case 'authExpired':
158
+ return USER_FRIENDLY_COPY.authExpired;
159
+ case 'notFound':
160
+ return context === 'canvasLoad' ? USER_FRIENDLY_COPY.canvasNotFound : USER_FRIENDLY_COPY.notFound;
161
+ case 'permission':
162
+ return USER_FRIENDLY_COPY.permission;
163
+ case 'validation':
164
+ return USER_FRIENDLY_COPY.validation;
165
+ case 'server':
166
+ return USER_FRIENDLY_COPY.server;
167
+ case 'unknown':
168
+ default:
169
+ return USER_FRIENDLY_COPY.generic;
170
+ }
171
+ }
172
+ /** When the text is already one of our canonical user strings, keep it. */
173
+ function passthroughIfAlreadyFriendly(raw, category, context) {
174
+ const trimmed = raw.trim();
175
+ if (!trimmed)
176
+ return null;
177
+ if (category === 'notFound' && context === 'canvasLoad' && trimmed === USER_FRIENDLY_COPY.notFound) {
178
+ return null;
179
+ }
180
+ const friendlyValues = new Set(Object.values(USER_FRIENDLY_COPY));
181
+ if (friendlyValues.has(trimmed))
182
+ return trimmed;
183
+ if (category === 'unknown' && !isLikelyTechnicalError(trimmed)) {
184
+ return trimmed;
185
+ }
186
+ return null;
187
+ }
188
+ /** Whether a stored line still looks like a raw server or runtime error. */
189
+ export function isLikelyTechnicalError(text) {
190
+ const trimmed = text.trim();
191
+ if (!trimmed)
192
+ return false;
193
+ if (MISSING_KEY_RE.test(trimmed) || ENV_KEY_RE.test(trimmed) || PROVIDER_RE.test(trimmed))
194
+ return true;
195
+ if (HTTP_STATUS_IN_TEXT_RE.test(trimmed) || STACK_OR_CLASS_RE.test(trimmed))
196
+ return true;
197
+ if (/direct llm|widget builder is not reachable|econnrefused|failed to fetch/i.test(trimmed))
198
+ return true;
199
+ if (trimmed.length > 400 && /[{[\]}]|"\w+":/.test(trimmed))
200
+ return true;
201
+ return false;
202
+ }
203
+ export function toUserFriendlyError(error, options) {
204
+ const context = options.context ?? 'generic';
205
+ const raw = readRawMessage(error);
206
+ const status = readHttpStatus(error);
207
+ const errorName = readErrorName(error);
208
+ const category = classify(raw, status, errorName, context);
209
+ const allowPassthrough = typeof error === 'string' || error instanceof Error || (typeof error === 'object' && error !== null);
210
+ const passthrough = allowPassthrough && typeof error !== 'number' && typeof error !== 'boolean' && typeof error !== 'bigint'
211
+ ? passthroughIfAlreadyFriendly(raw, category, context)
212
+ : null;
213
+ const userMessage = passthrough ?? messageForCategory(category, context);
214
+ const technicalSource = raw || (typeof error === 'string' ? error : error instanceof Error ? error.message : '');
215
+ const technicalDetail = options.debugMode && technicalSource.trim() ? trimTechnicalDetail(technicalSource) : null;
216
+ return { userMessage, technicalDetail, category };
217
+ }
218
+ /** What to store or show: friendly text, with technical detail only in debug mode. */
219
+ export function formatUserFacingErrorText(error, options) {
220
+ const { userMessage, technicalDetail } = toUserFriendlyError(error, options);
221
+ if (!technicalDetail || technicalDetail === userMessage)
222
+ return userMessage;
223
+ return `${userMessage} (${technicalDetail})`;
224
+ }
225
+ /** Sanitize a string that is already stored in chat or UI state. */
226
+ export function friendlyTextFromStoredError(storedText, options) {
227
+ const stripped = stripErrorDecorations(storedText);
228
+ if (!stripped)
229
+ return storedText.trim();
230
+ const result = toUserFriendlyError(stripped, options);
231
+ if (!options.debugMode)
232
+ return result.userMessage;
233
+ if (!result.technicalDetail)
234
+ return result.userMessage;
235
+ return `${result.userMessage} (${result.technicalDetail})`;
236
+ }