@widgetic/creator 0.3.81 → 0.4.0

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.
Files changed (62) hide show
  1. package/README.md +157 -0
  2. package/dist/CreatorApp.svelte +1103 -612
  3. package/dist/CreatorApp.svelte.d.ts +22 -0
  4. package/dist/components/BrandKitPanel.svelte +48 -40
  5. package/dist/components/BrandKitPanel.svelte.d.ts +1 -1
  6. package/dist/components/DesignQuickEdit.svelte +13 -4
  7. package/dist/components/EditableName.svelte +13 -8
  8. package/dist/components/EditableName.svelte.d.ts +2 -2
  9. package/dist/components/FileUrlSourceControl.svelte +21 -8
  10. package/dist/components/HoverTooltip.svelte +1 -1
  11. package/dist/components/SelectorDropdown.svelte +19 -15
  12. package/dist/components/SelectorDropdown.svelte.d.ts +2 -2
  13. package/dist/components/VersionDropdownRow.svelte +14 -11
  14. package/dist/components/WidgetDetails.svelte +118 -92
  15. package/dist/components/WidgetShapeLivePreviews.svelte +105 -46
  16. package/dist/creator-types.d.ts +96 -0
  17. package/dist/host/creatorHost.d.ts +176 -0
  18. package/dist/host/creatorHost.js +242 -0
  19. package/dist/host/limitRefusal.d.ts +64 -0
  20. package/dist/host/limitRefusal.js +109 -0
  21. package/dist/i18n/index.d.ts +5 -0
  22. package/dist/i18n/index.js +5 -0
  23. package/dist/i18n/labels.d.ts +14 -0
  24. package/dist/i18n/labels.js +39 -0
  25. package/dist/i18n/language.d.ts +559 -0
  26. package/dist/i18n/language.js +47 -0
  27. package/dist/i18n/languageKit.d.ts +52 -0
  28. package/dist/i18n/languageKit.js +45 -0
  29. package/dist/i18n/messages.d.ts +526 -0
  30. package/dist/i18n/messages.js +548 -0
  31. package/dist/i18n/slots.d.ts +22 -0
  32. package/dist/i18n/slots.js +42 -0
  33. package/dist/i18n/statusText.d.ts +22 -0
  34. package/dist/i18n/statusText.js +223 -0
  35. package/dist/index.d.ts +1 -0
  36. package/dist/index.js +2 -0
  37. package/dist/stores/userSession.d.ts +8 -1
  38. package/dist/stores/userSession.js +18 -25
  39. package/dist/stores/websocketStore.d.ts +6 -0
  40. package/dist/stores/websocketStore.js +39 -4
  41. package/dist/utils/designIntentTelemetry.d.ts +8 -0
  42. package/dist/utils/designIntentTelemetry.js +52 -34
  43. package/dist/utils/directionPlacement.d.ts +51 -0
  44. package/dist/utils/directionPlacement.js +55 -0
  45. package/dist/utils/embedCode.d.ts +0 -1
  46. package/dist/utils/embedCode.js +0 -4
  47. package/dist/utils/nativeScrollbarPadding.js +1 -1
  48. package/dist/utils/pickedFile.d.ts +15 -0
  49. package/dist/utils/pickedFile.js +21 -0
  50. package/dist/utils/widgeticChatUpload.d.ts +9 -0
  51. package/dist/utils/widgeticChatUpload.js +24 -2
  52. package/package.json +5 -3
  53. package/dist/retiredSurface.test.d.ts +0 -1
  54. package/dist/retiredSurface.test.js +0 -113
  55. package/dist/utils/designIntentResolver.test.d.ts +0 -1
  56. package/dist/utils/designIntentResolver.test.js +0 -246
  57. package/dist/utils/designIntentTelemetry.test.d.ts +0 -1
  58. package/dist/utils/designIntentTelemetry.test.js +0 -385
  59. package/dist/utils/designQuickEditValues.test.d.ts +0 -1
  60. package/dist/utils/designQuickEditValues.test.js +0 -100
  61. package/dist/utils/widgeticChatUpload.test.d.ts +0 -1
  62. package/dist/utils/widgeticChatUpload.test.js +0 -257
@@ -62,6 +62,88 @@
62
62
  }
63
63
  };
64
64
 
65
+ /** The bearer token a request carries, or null. */
66
+ function bearerTokenOf(headersInit: HeadersInit | undefined): string | null {
67
+ const value = new Headers(headersInit).get('Authorization');
68
+ return value ? value.replace(/^Bearer\s+/i, '') : null;
69
+ }
70
+
71
+ /** The API's code for a refusal (`EDITOR_SESSION_REVOKED`, `EDITOR_SESSION_EXPIRED` ...), when its answer has one. */
72
+ async function refusalCodeOf(response: Response): Promise<string | undefined> {
73
+ try {
74
+ const body = await response.clone().json();
75
+ const code = body?.error?.code ?? body?.code;
76
+ return typeof code === 'string' && code ? code : undefined;
77
+ } catch {
78
+ return undefined;
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Partner mode: when the API turns a token down (401), ask the page for a replacement and send the request once
84
+ * more. The page is asked once per burst of refusals (it is told which token was refused). When the page can only
85
+ * give back the very token the API refused (a session that was revoked), the session is over: the page is told, and
86
+ * neither the page nor the API is asked anything more with that token.
87
+ */
88
+ const retriedAfterTokenRefresh = new WeakSet<object>();
89
+ /** The token the API refused and the page had no other to give instead. */
90
+ let tokenWithoutReplacement: string | null = null;
91
+ const hostTokenRefreshMiddleware: Middleware = {
92
+ pre: async (context) => {
93
+ // Sent again, it would only be refused again.
94
+ if (tokenWithoutReplacement && bearerTokenOf(context.init.headers) === tokenWithoutReplacement) {
95
+ throw new Error(partnerSessionEndedText());
96
+ }
97
+ },
98
+ post: async (context) => {
99
+ if (context.response.status !== 401 || retriedAfterTokenRefresh.has(context.init)) return;
100
+ const refusedToken = bearerTokenOf(context.init.headers);
101
+ // The page was already asked about this very token and had nothing else to give.
102
+ if (refusedToken && refusedToken === tokenWithoutReplacement) return;
103
+ const replacement = await adoptHostToken('expired', refusedToken ?? undefined);
104
+ if (!replacement) return;
105
+ if (replacement === refusedToken) {
106
+ tokenWithoutReplacement = refusedToken;
107
+ endHostSession('The API refused the session token and the page has no other to give.', await refusalCodeOf(context.response));
108
+ return;
109
+ }
110
+ const headers = new Headers(context.init.headers);
111
+ headers.set('Authorization', `Bearer ${replacement}`);
112
+ const retryInit: RequestInit = { ...context.init, headers };
113
+ retriedAfterTokenRefresh.add(retryInit);
114
+ return context.fetch(context.url, retryInit);
115
+ }
116
+ };
117
+
118
+ /**
119
+ * Partner mode: the page is told when the API refuses something because the visitor reached a limit (the wallet is
120
+ * empty, the plan does not include it, the storage is full, the customer's budget is used up), once per limit and not
121
+ * once per refused request. What counts as a limit is decided in `host/limitRefusal.ts`. The creator keeps showing the
122
+ * visitor its own neutral message; this is for the partner's page to show whatever it has for it.
123
+ */
124
+ const limitReporter = createLimitReporter({ report: reportLimitReached });
125
+ const limitReachedMiddleware: Middleware = {
126
+ post: async (context) => {
127
+ const status = context.response.status;
128
+ // Only the few statuses a limit comes with are read: every other answer is left alone.
129
+ if (!answerMayBeALimit(status)) return;
130
+ let body: unknown;
131
+ try {
132
+ body = await context.response.clone().json();
133
+ } catch {
134
+ // An answer that is not JSON did not come from the gateway's error handler, so it is no limit of ours.
135
+ return;
136
+ }
137
+ let where: string | undefined;
138
+ try {
139
+ where = `${context.init.method ?? 'GET'} ${new URL(context.url, 'http://localhost').pathname}`;
140
+ } catch {
141
+ where = undefined;
142
+ }
143
+ limitReporter.noteAnswer(status, body, where);
144
+ }
145
+ };
146
+
65
147
  import {
66
148
  normalizeErrorMessage,
67
149
  toErrorMessage,
@@ -74,13 +156,17 @@
74
156
  sanitizePreviewBuildError,
75
157
  isInfrastructurePreviewError
76
158
  } from './pageHelpers.js';
77
- import { uploadChatFileToWidgeticApi } from './utils/widgeticChatUpload.js';
159
+ import {
160
+ ChatUploadRefusedError,
161
+ shouldUseTusForChatUpload,
162
+ uploadChatFileToWidgeticApi
163
+ } from './utils/widgeticChatUpload.js';
78
164
  import { persistWidgetThumbnail } from './utils/persistWidgetThumbnail.js';
79
165
  import { nativeScrollbarPadding } from './utils/nativeScrollbarPadding.js';
80
166
  import { pinScrollToBottom } from './utils/pinScrollToBottom.js';
81
167
  import { installFreezeWatchdog, measureSync } from './utils/freezeWatchdog.js';
82
168
  import { streamOperationUpdates } from './utils/operationStream.js';
83
- import { generateEmbedCode, EMBED_FORMATS, EMBED_FORMAT_LABELS, type EmbedFormat } from './utils/embedCode.js';
169
+ import { generateEmbedCode, EMBED_FORMATS, type EmbedFormat } from './utils/embedCode.js';
84
170
 
85
171
  function openEmbedTestPage(href: string) {
86
172
  if (typeof window === 'undefined') return;
@@ -91,6 +177,32 @@
91
177
  import { syncSessionFromSiteAuth } from './syncSiteAuth.js';
92
178
  import { setEnableLocalCache, isLocalCacheEnabled } from './localCacheGate.js';
93
179
  import type { CreatorAppProps } from './creator-types.js';
180
+ import { shareTextDirection, type TextDirection } from '@widgetic/design-system/components/textDirection';
181
+ import { listAlignedToEnd } from './utils/directionPlacement.js';
182
+ import { conversationLineLabel, embedFormatLabel, errorLabel, provideCreatorLanguage, sentenceParts, splitCreatorMessages, statusLabel, versionDateText } from './i18n/index.js';
183
+ import {
184
+ creatorStorage,
185
+ creatorSessionStorage,
186
+ HOST_VISITOR,
187
+ enterPartnerMode,
188
+ leavePartnerMode,
189
+ isPartnerMode,
190
+ setHostHandlers,
191
+ mayUseAddressBar,
192
+ mayShowAccountBilling,
193
+ mayListenToSiteEvents,
194
+ announceToSite,
195
+ eventIsFromCreator,
196
+ eventPathMatches,
197
+ createDragFeedback,
198
+ getCreatorShadowRoot,
199
+ messageIsFromCreatorFrame,
200
+ reloadThePage,
201
+ reportSessionEnded,
202
+ reportLimitReached,
203
+ reportCanvasUnavailable
204
+ } from './host/creatorHost.js';
205
+ import { answerMayBeALimit, createLimitReporter, responseIsALimit } from './host/limitRefusal.js';
94
206
 
95
207
  function resolveCreatorWorkflowStep(
96
208
  step?: CreatorAppProps['initialStep'] | 'create' | 'edit' | 'embed' | null
@@ -125,6 +237,90 @@
125
237
  export const onBack: CreatorAppProps['onBack'] = undefined;
126
238
  export let onWidgetRenamed: CreatorAppProps['onWidgetRenamed'] = undefined;
127
239
 
240
+ /**
241
+ * Partner mode (see `CreatorAppProps.getAccessToken`): the page hands over the token and keeps the storage, the
242
+ * address bar and the navigation for itself. Decided once, when the creator starts.
243
+ */
244
+ export let getAccessToken: CreatorAppProps['getAccessToken'] = undefined;
245
+ export let onSessionEnded: CreatorAppProps['onSessionEnded'] = undefined;
246
+ export let onReloadRequested: CreatorAppProps['onReloadRequested'] = undefined;
247
+ export let onLimitReached: CreatorAppProps['onLimitReached'] = undefined;
248
+ export let onCanvasUnavailable: CreatorAppProps['onCanvasUnavailable'] = undefined;
249
+ export let onCanvasChanged: CreatorAppProps['onCanvasChanged'] = undefined;
250
+ export let onReady: CreatorAppProps['onReady'] = undefined;
251
+ /** The page's own media library for the editor's file pickers (see `CreatorAppProps.mediaLibrary`). */
252
+ export let mediaLibrary: CreatorAppProps['mediaLibrary'] = undefined;
253
+ /**
254
+ * The language of everything the creator shows (see `CreatorAppProps.locale` and `CreatorAppProps.messages`). The one flat
255
+ * `messages` object is split between the creator's own words and the parts it draws: the editor (with its file
256
+ * browser), the chat and the canvas each have a catalog of their own.
257
+ */
258
+ export let locale: CreatorAppProps['locale'] = null;
259
+ export let messages: CreatorAppProps['messages'] = null;
260
+ const firstLanguageSlices = splitCreatorMessages(messages);
261
+ const language = provideCreatorLanguage({ locale, messages: firstLanguageSlices.creator });
262
+ const editorLanguage = provideEditorLanguage({ locale, messages: firstLanguageSlices.editor });
263
+ // `languageTag` is the language the words are in ('en' unless the page asked for another one); dates are written in it.
264
+ const { t, locale: languageTag } = language;
265
+ /**
266
+ * The direction of the creator's screen (see `CreatorAppProps.dir`). Every part below (the chat, the canvas, the editor with
267
+ * its File Browser and rich text editor) reads it from Svelte's context and follows when the page changes `dir`;
268
+ * `textDirection` is the answer, for the creator's own decisions (where a pop-up opens from, which way a divider drags).
269
+ */
270
+ export let dir: CreatorAppProps['dir'] = undefined;
271
+ const givenDirection = writable<TextDirection | undefined>(dir);
272
+ const textDirection = shareTextDirection(givenDirection);
273
+ $: givenDirection.set(dir);
274
+ // The page may change the language while the creator is open.
275
+ $: languageSlices = splitCreatorMessages(messages);
276
+ $: language.update({ locale, messages: languageSlices.creator });
277
+ $: editorLanguage.update({ locale, messages: languageSlices.editor });
278
+ $: chatMessages = languageSlices.chat;
279
+ $: canvasMessages = languageSlices.canvas;
280
+ /** The creator's own area of the page (see `eventIsFromCreator`). */
281
+ let creatorRootEl: HTMLElement | null = null;
282
+ const partnerMode = typeof getAccessToken === 'function';
283
+ if (partnerMode) {
284
+ // A creator in a partner's page is always the embedded kind: no sign-in screen, no top bar.
285
+ embedded = true;
286
+ // Before anything below can ask the storage for a sign-in: in partner mode the storage is memory.
287
+ enterPartnerMode({ onSessionEnded, onReloadRequested, onLimitReached, onCanvasUnavailable });
288
+ }
289
+ // The page may hand over new functions while the creator runs.
290
+ $: if (partnerMode) setHostHandlers({ onSessionEnded, onReloadRequested, onLimitReached, onCanvasUnavailable });
291
+ // The page is told which canvas is open whenever that changes (the creator opens one, or makes a new one), so a
292
+ // partner's page can keep the id: the creator leaves the address bar and the storage alone.
293
+ let lastReportedCanvasId: string | null = null;
294
+ $: if (canvasId && canvasId !== lastReportedCanvasId) {
295
+ lastReportedCanvasId = canvasId;
296
+ try {
297
+ onCanvasChanged?.({ canvasId });
298
+ } catch (error) {
299
+ console.error(`[CreatorApp] The page's onCanvasChanged handler threw:`, error);
300
+ }
301
+ }
302
+ // The page is told once, when the first canvas has loaded (see `markCanvasStateLoaded`), that the creator is ready.
303
+ let readyAnnounced = false;
304
+ function announceReadyOnce(): void {
305
+ if (readyAnnounced) return;
306
+ // A creator that has no canvas to show (the page named one the visitor cannot open) or no session is not ready:
307
+ // the page was told what is wrong instead.
308
+ if (canvasUnavailable || hostSessionEnded) return;
309
+ readyAnnounced = true;
310
+ try {
311
+ onReady?.({ canvasId: canvasId || null });
312
+ } catch (error) {
313
+ console.error(`[CreatorApp] The page's onReady handler threw:`, error);
314
+ }
315
+ }
316
+ /**
317
+ * What every API client of the creator runs its requests through. In a partner's page the limit middleware comes
318
+ * last, so it reads the answer to the request that was sent again with a fresh token, not the refusal before it.
319
+ */
320
+ const clientMiddleware: Middleware[] = partnerMode
321
+ ? [idempotencyKeyMiddleware, hostTokenRefreshMiddleware, limitReachedMiddleware]
322
+ : [idempotencyKeyMiddleware];
323
+
128
324
  // Opt-in Dexie owner — reactive to prop changes without $effect (would force runes mode).
129
325
  $: setEnableLocalCache(!!enableLocalCache);
130
326
 
@@ -161,13 +357,7 @@
161
357
  // console.log('[CreatorApp] Notify host widget name:', widget.id, name);
162
358
  onWidgetRenamed?.({ widgetId: widget.id, name });
163
359
  // Also broadcast — mount props can be stale across embed remounts.
164
- if (typeof window !== 'undefined') {
165
- window.dispatchEvent(
166
- new CustomEvent('widgetic:creator-primary-renamed', {
167
- detail: { widgetId: widget.id, name },
168
- }),
169
- );
170
- }
360
+ announceToSite('widgetic:creator-primary-renamed', { widgetId: widget.id, name });
171
361
  }
172
362
 
173
363
  /**
@@ -179,6 +369,8 @@
179
369
  */
180
370
  function syncEmbeddedCanvasUrl(canvasIdToSync: string): void {
181
371
  if (!embedded || !canvasIdToSync) return;
372
+ // A partner's address bar is the partner's: the page learns which canvas is open from the module instead.
373
+ if (!mayUseAddressBar()) return;
182
374
  try {
183
375
  const url = new URL(window.location.href);
184
376
  url.pathname = `/canvas/${encodeURIComponent(canvasIdToSync)}`;
@@ -253,7 +445,7 @@
253
445
  function handleHostRequestPublishEvent(): void {
254
446
  const targetId = focusedPanelWidgetId || selectedWidgetId;
255
447
  if (!targetId) {
256
- showToast('error', 'Cannot publish', { description: 'No widget selected.' });
448
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.widget.noWidgetSelected') });
257
449
  return;
258
450
  }
259
451
  // console.log('[CreatorApp] Host requested publish for', targetId.substring(0, 8));
@@ -266,7 +458,9 @@
266
458
 
267
459
  // Sync JWT before reactive blocks run (avoids false "No JWT" on first paint in embedded or standalone)
268
460
  if (typeof window !== 'undefined') {
269
- if (embedded) {
461
+ if (partnerMode) {
462
+ // The sign-in comes from the page (adoptHostToken, below), never from the browser's storage.
463
+ } else if (embedded) {
270
464
  syncSessionFromSiteAuth();
271
465
  } else {
272
466
  restoreSession();
@@ -304,6 +498,8 @@
304
498
  }
305
499
 
306
500
  function buildCompositionProjectFields(widgetId?: string | null): { projectId?: string } {
501
+ // A visitor in a partner's page has no project of the Widgetic site, and the gateway refuses the field for a session.
502
+ if (partnerMode) return {};
307
503
  const resolvedProjectId = resolveCompositionProjectId(widgetId);
308
504
  return resolvedProjectId ? { projectId: resolvedProjectId } : {};
309
505
  }
@@ -317,7 +513,7 @@
317
513
  /**
318
514
  * WIDGETIC EDITOR — PropsEditor for design/content property editing
319
515
  */
320
- import { PropsEditor, setFileBrowserUploadConfig, setGoogleFontsApiKey } from '@widgetic/editor';
516
+ import { PropsEditor, provideEditorLanguage, setFileBrowserUploadConfig, setGoogleFontsApiKey } from '@widgetic/editor';
321
517
 
322
518
  // API root: embedded hosts pass apiUrl; standalone uses VITE_API_URL / PUBLIC_API_URL.
323
519
  // If unset, @widgetic/api-sdk falls back to BASE_PATH = dev-api.widgetic.com (OpenAPI default).
@@ -348,7 +544,7 @@
348
544
  let messagesClient: MessagesApi;
349
545
  let compositionsClient: CompositionsApi;
350
546
  let uploadsClient: UploadsApi;
351
- let usersClient: UsersApi;
547
+ let usersClient: UsersApi | null = null;
352
548
  /** Credits, and days left while the account is still on the free trial. */
353
549
  let trialCounter: { credits: number; days: number | null; trialEnded: boolean } | null = null;
354
550
 
@@ -370,35 +566,39 @@
370
566
  setWebsocketApiUrl(apiRoot ?? null);
371
567
 
372
568
  canvasesClient = apiBasePath
373
- ? new CanvasesApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
374
- : new CanvasesApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
569
+ ? new CanvasesApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
570
+ : new CanvasesApi({ accessToken: token, middleware: clientMiddleware });
375
571
  widgetsClient = apiBasePath
376
- ? new WidgetsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
377
- : new WidgetsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
572
+ ? new WidgetsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
573
+ : new WidgetsApi({ accessToken: token, middleware: clientMiddleware });
378
574
  componentsClient = apiBasePath
379
- ? new ComponentsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
380
- : new ComponentsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
575
+ ? new ComponentsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
576
+ : new ComponentsApi({ accessToken: token, middleware: clientMiddleware });
381
577
  agentClient = apiBasePath
382
- ? new AgentApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
383
- : new AgentApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
578
+ ? new AgentApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
579
+ : new AgentApi({ accessToken: token, middleware: clientMiddleware });
384
580
  operationsClient = apiBasePath
385
- ? new OperationsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
386
- : new OperationsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
581
+ ? new OperationsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
582
+ : new OperationsApi({ accessToken: token, middleware: clientMiddleware });
387
583
  conversationsClient = apiBasePath
388
- ? new ConversationsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
389
- : new ConversationsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
584
+ ? new ConversationsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
585
+ : new ConversationsApi({ accessToken: token, middleware: clientMiddleware });
390
586
  messagesClient = apiBasePath
391
- ? new MessagesApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
392
- : new MessagesApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
587
+ ? new MessagesApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
588
+ : new MessagesApi({ accessToken: token, middleware: clientMiddleware });
393
589
  compositionsClient = apiBasePath
394
- ? new CompositionsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
395
- : new CompositionsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
590
+ ? new CompositionsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
591
+ : new CompositionsApi({ accessToken: token, middleware: clientMiddleware });
396
592
  uploadsClient = apiBasePath
397
- ? new UploadsApi({ basePath: apiBasePath, accessToken: token, middleware: [idempotencyKeyMiddleware] })
398
- : new UploadsApi({ accessToken: token, middleware: [idempotencyKeyMiddleware] });
399
- usersClient = apiBasePath
400
- ? new UsersApi({ basePath: apiBasePath, accessToken: token })
401
- : new UsersApi({ accessToken: token });
593
+ ? new UploadsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
594
+ : new UploadsApi({ accessToken: token, middleware: clientMiddleware });
595
+ // The trial and credit counter is an account matter: a visitor of a partner has none, and a session may not ask for it
596
+ // (so there is no client for it at all, and nothing can ask by mistake).
597
+ usersClient = partnerMode
598
+ ? null
599
+ : apiBasePath
600
+ ? new UsersApi({ basePath: apiBasePath, accessToken: token })
601
+ : new UsersApi({ accessToken: token });
402
602
 
403
603
  authenticatedClientsToken = token;
404
604
  try {
@@ -410,9 +610,96 @@
410
610
  void refreshTrialCounter();
411
611
  }
412
612
 
613
+ /** Partner mode: the page could not give the creator a token the API accepts, so nothing it asks can go through. */
614
+ let hostSessionEnded = false;
615
+ /** Partner mode: how often the creator takes the token the page holds, so a renewed one reaches the API clients. */
616
+ const HOST_TOKEN_PUMP_MS = 20_000;
617
+ let hostTokenPump: ReturnType<typeof setInterval> | null = null;
618
+
619
+ /**
620
+ * Partner mode: takes the token the page holds (`'initial'`) or, when the API has just refused one, a replacement
621
+ * for it (`'expired'`), and makes it the one the creator calls the API with. Resolves with the token, or null when
622
+ * the page could not give one. A failed replacement ends the session; a later successful call revives it.
623
+ */
624
+ async function adoptHostToken(reason: 'initial' | 'expired', refusedToken?: string): Promise<string | null> {
625
+ if (!partnerMode || typeof getAccessToken !== 'function') return null;
626
+ try {
627
+ const token = await getAccessToken(reason, refusedToken);
628
+ if (typeof token !== 'string' || token.trim() === '') {
629
+ throw new Error('The page did not give the creator a token');
630
+ }
631
+ // Only another token revives a session: the very token the API refused would end it again at once.
632
+ if (hostSessionEnded && token !== tokenWithoutReplacement) {
633
+ hostSessionEnded = false;
634
+ }
635
+ if (token !== $userSession.jwt || !$userSession.user) {
636
+ // The reactive statement on $userSession binds the API clients to the new token.
637
+ setSession(HOST_VISITOR, token);
638
+ }
639
+ return token;
640
+ } catch (error) {
641
+ console.warn('[CreatorApp] The page could not give the creator a token', error);
642
+ if (reason === 'expired') {
643
+ // Asked about this token and had nothing to give: it is not asked again for the same one.
644
+ if (refusedToken) tokenWithoutReplacement = refusedToken;
645
+ endHostSession(
646
+ error instanceof Error && error.message ? error.message : 'The session could not be renewed.',
647
+ 'TOKEN_REFRESH_FAILED'
648
+ );
649
+ }
650
+ return null;
651
+ }
652
+ }
653
+
654
+ /** Partner mode: nothing more can be asked of the API. Tells the page (once per ending) and shows the visitor. */
655
+ function endHostSession(message: string, code?: string): void {
656
+ const alreadyEnded = hostSessionEnded;
657
+ hostSessionEnded = true;
658
+ updateTokenStatus();
659
+ if (alreadyEnded) return;
660
+ // The visitor is told in plain words whatever the cause was; the reason goes to the page, not to the visitor.
661
+ showToast('warning', $t('creator.session.sessionEnded'), { description: partnerSessionEndedText(), duration: 8000 });
662
+ reportSessionEnded({ message, code });
663
+ }
664
+
665
+ /** In a partner's page there is no sign-in to offer a visitor whose session is gone, only a new one the page starts. */
666
+ function partnerSessionEndedText(): string {
667
+ return $t('creator.session.endedStartAgain');
668
+ }
669
+
670
+ /** What to tell the visitor when their sign-in is gone: the site's wording, or the neutral one in a partner's page. */
671
+ function signInAgainText(siteText: string): string {
672
+ return partnerMode ? partnerSessionEndedText() : siteText;
673
+ }
674
+
675
+ /**
676
+ * Partner mode: the canvas the page named is not one this visitor can open (the API answers as if it did not exist for
677
+ * them). There is nothing to show or to save then, and asking again would not change the answer.
678
+ */
679
+ let canvasUnavailable = false;
680
+ function partnerCanvasUnavailableText(): string {
681
+ return $t('creator.session.canvasCannotOpen');
682
+ }
683
+
684
+ /** Says so once: on the creator's own screen and to the page, and stops everything that would ask for the canvas again. */
685
+ function declareCanvasUnavailable(unavailableCanvasId: string | null, message: string, code = 'NOT_FOUND'): void {
686
+ if (canvasUnavailable) return;
687
+ canvasUnavailable = true;
688
+ clearCanvasLoadFailsafe();
689
+ clearCanvasHydrateRetry();
690
+ canvasApiLoadError = partnerCanvasUnavailableText();
691
+ reportCanvasUnavailable({ canvasId: unavailableCanvasId, message, code });
692
+ }
693
+
694
+ /** Partner mode: does this error from the API say that there is no such canvas (for this visitor)? */
695
+ function saysCanvasIsMissing(err: unknown): boolean {
696
+ return partnerMode && err instanceof ResponseError && err.response?.status === 404;
697
+ }
698
+
413
699
  /** Credits left and days left, from the same billing status the publish gate uses. */
414
700
  async function refreshTrialCounter() {
415
- if (!usersClient) return;
701
+ // An account matter: a visitor of a partner has no trial and no balance of their own to show.
702
+ if (!usersClient || !mayShowAccountBilling()) return;
416
703
  try {
417
704
  const accepted = await usersClient.usersMeBillingGetRaw();
418
705
  const body = await accepted.raw.json();
@@ -436,27 +723,27 @@
436
723
  days: paidPlan || days == null || !Number.isFinite(days) ? null : Math.max(0, Math.round(days)),
437
724
  trialEnded: !paidPlan && days === 0,
438
725
  };
439
- if (typeof window !== 'undefined') {
440
- window.dispatchEvent(new CustomEvent('widgetic:trial-counter'));
441
- }
726
+ announceToSite('widgetic:trial-counter');
442
727
  } catch (error) {
443
728
  console.warn('[Trial] Could not load the credit counter', error);
444
729
  }
445
730
  }
446
731
 
447
732
  function applySiteSessionToCreator(): boolean {
733
+ // Partner mode has no site session. A refused token is replaced by the middleware that sees the refusal.
734
+ if (partnerMode) return hasValidToken;
448
735
  const synced = syncSessionFromSiteAuth();
449
736
  if (!synced) return false;
450
737
  try {
451
- const sessionStr = localStorage.getItem('session');
738
+ const sessionStr = creatorStorage.getItem('session');
452
739
  const session = sessionStr ? JSON.parse(sessionStr) : null;
453
740
  currentUserToken =
454
741
  session?.accessToken ||
455
742
  session?.access_token ||
456
- localStorage.getItem('jwt') ||
743
+ creatorStorage.getItem('jwt') ||
457
744
  currentUserToken;
458
745
  } catch {
459
- currentUserToken = localStorage.getItem('jwt') || currentUserToken;
746
+ currentUserToken = creatorStorage.getItem('jwt') || currentUserToken;
460
747
  }
461
748
  if (currentUserToken) {
462
749
  authenticatedClientsToken = null;
@@ -582,6 +869,7 @@
582
869
  import {
583
870
  recordDesignIntentTelemetry,
584
871
  recordDesignIntentJevOutcome,
872
+ installDesignIntentTelemetryConsoleHandle,
585
873
  isJevCandidateBucket,
586
874
  type DesignIntentClassification
587
875
  } from './utils/designIntentTelemetry';
@@ -650,11 +938,19 @@
650
938
  const canvasModule = await canvasModulePromise;
651
939
  // Installed before the canvas mounts so the first save already externalizes
652
940
  installCanvasThumbnailStore(canvasModule);
941
+ // The canvas keeps the visitor's saved colors where the creator keeps its own memory: the browser's
942
+ // storage, except in a partner's page, where it is memory (a partner's page is not written to).
943
+ canvasModule.setCanvasPreferenceStorage?.(creatorStorage);
653
944
  WidgeticCanvas = canvasModule.Canvas;
654
945
  }
655
- installLongTaskFreezeReporter();
656
- installFreezeWatchdog();
657
- console.info('[FreezeWatchdog] Freeze reports log on this page. In DevTools, pick the top frame — not a widget iframe.');
946
+ // Widgetic's own diagnostics (a watchdog worker, long-task observers and console handles on `window`) belong
947
+ // to the pages Widgetic owns; a partner's page gets none of them.
948
+ if (!isPartnerMode()) {
949
+ installLongTaskFreezeReporter();
950
+ installFreezeWatchdog();
951
+ installDesignIntentTelemetryConsoleHandle();
952
+ console.info('[FreezeWatchdog] Freeze reports log on this page. In DevTools, pick the top frame — not a widget iframe.');
953
+ }
658
954
  });
659
955
 
660
956
  /**
@@ -701,7 +997,6 @@
701
997
  /**
702
998
  * CONSTANTS
703
999
  */
704
- import { page as pageStore } from '$app/stores';
705
1000
  import { maxCharsFromId } from './constants.js';
706
1001
  import {
707
1002
  saveCanvasState,
@@ -826,7 +1121,7 @@
826
1121
  let canvasApiLoadError: string | null = null;
827
1122
  let canvasShapesMissingWarning = false;
828
1123
  let lastSavedCanvasObjectCount = (() => {
829
- try { return parseInt(sessionStorage.getItem(CANVAS_OBJ_COUNT_KEY) || '0', 10) || 0; }
1124
+ try { return parseInt(creatorSessionStorage.getItem(CANVAS_OBJ_COUNT_KEY) || '0', 10) || 0; }
830
1125
  catch { return 0; }
831
1126
  })();
832
1127
 
@@ -878,7 +1173,7 @@
878
1173
  break;
879
1174
  case 'keep-in-db':
880
1175
  deleteDialogOpen = false;
881
- showToast('info', 'Shape removed', { description: 'Widget kept in database' });
1176
+ showToast('info', $t('creator.widget.shapeRemoved'), { description: $t('creator.widget.widgetKeptInDatabase') });
882
1177
  break;
883
1178
  case 'delete-from-db':
884
1179
  deleteDialogOpen = false;
@@ -902,7 +1197,7 @@
902
1197
  if (selectedWidgetId === widgetId) {
903
1198
  selectedWidgetId = null;
904
1199
  }
905
- showToast('success', 'Widget deleted from database');
1200
+ showToast('success', $t('creator.widget.widgetDeletedFromDatabase'));
906
1201
  } catch (err) {
907
1202
  // A shape can outlive its widget row (deleted from the Projects page or
908
1203
  // another session). The canvas only needs the shape and local entry gone,
@@ -914,13 +1209,13 @@
914
1209
  if (selectedWidgetId === widgetId) {
915
1210
  selectedWidgetId = null;
916
1211
  }
917
- showToast('info', 'Widget was already deleted', {
918
- description: 'Removed the leftover shape from this canvas.',
1212
+ showToast('info', $t('creator.widget.widgetWasAlreadyDeleted'), {
1213
+ description: $t('creator.canvas.removedTheLeftoverShapeFrom'),
919
1214
  });
920
1215
  return;
921
1216
  }
922
1217
  console.error('[WidgetCreator] Failed to delete widget from DB:', err);
923
- showToast('error', 'Failed to delete widget from database');
1218
+ showToast('error', $t('creator.widget.failedToDeleteWidgetFrom'));
924
1219
  }
925
1220
  }
926
1221
 
@@ -928,10 +1223,10 @@
928
1223
  function saveSelectedWidgetId(widgetId: string | null) {
929
1224
  try {
930
1225
  if (widgetId) {
931
- localStorage.setItem(SELECTED_WIDGET_STORAGE_KEY, widgetId);
1226
+ creatorStorage.setItem(SELECTED_WIDGET_STORAGE_KEY, widgetId);
932
1227
  // console.log('[WidgetCreator] Saved selected widget ID to localStorage:', widgetId);
933
1228
  } else {
934
- localStorage.removeItem(SELECTED_WIDGET_STORAGE_KEY);
1229
+ creatorStorage.removeItem(SELECTED_WIDGET_STORAGE_KEY);
935
1230
  // console.log('[WidgetCreator] Cleared selected widget ID from localStorage');
936
1231
  }
937
1232
  } catch (e) {
@@ -942,7 +1237,7 @@
942
1237
  // Helper function to get saved widget ID from localStorage
943
1238
  function getSavedSelectedWidgetId(): string | null {
944
1239
  try {
945
- return localStorage.getItem(SELECTED_WIDGET_STORAGE_KEY);
1240
+ return creatorStorage.getItem(SELECTED_WIDGET_STORAGE_KEY);
946
1241
  } catch (e) {
947
1242
  console.warn('[WidgetCreator] Failed to get selected widget ID from localStorage:', e);
948
1243
  return null;
@@ -952,9 +1247,9 @@
952
1247
  function saveSelectedCanvasId(id: string | null) {
953
1248
  try {
954
1249
  if (id) {
955
- localStorage.setItem(SELECTED_CANVAS_STORAGE_KEY, id);
1250
+ creatorStorage.setItem(SELECTED_CANVAS_STORAGE_KEY, id);
956
1251
  } else {
957
- localStorage.removeItem(SELECTED_CANVAS_STORAGE_KEY);
1252
+ creatorStorage.removeItem(SELECTED_CANVAS_STORAGE_KEY);
958
1253
  }
959
1254
  } catch (e) {
960
1255
  console.warn('[WidgetCreator] Failed to save canvas ID to localStorage:', e);
@@ -970,7 +1265,7 @@
970
1265
 
971
1266
  function getSavedSelectedCanvasId(): string | null {
972
1267
  try {
973
- return localStorage.getItem(SELECTED_CANVAS_STORAGE_KEY);
1268
+ return creatorStorage.getItem(SELECTED_CANVAS_STORAGE_KEY);
974
1269
  } catch (e) {
975
1270
  return null;
976
1271
  }
@@ -992,15 +1287,17 @@
992
1287
  return isGeneratingCode || Object.keys(generatingWidgetIds).some((id) => generatingWidgetIds[id]);
993
1288
  }
994
1289
 
995
- /** Synchronous hold so a screenshot cannot postMessage after codegen has started. */
1290
+ /**
1291
+ * Synchronous hold so a screenshot cannot postMessage after codegen has started. Kept in the component, not on
1292
+ * `window`: nothing else reads it, and a partner's page is not a place to leave globals.
1293
+ */
1294
+ let codegenActiveCount = 0;
996
1295
  function noteCodegenActive(active: boolean): void {
997
- if (typeof window === 'undefined') return;
998
- const holder = window as Window & { __widgeticCodegenCount?: number };
999
- holder.__widgeticCodegenCount = Math.max(0, (holder.__widgeticCodegenCount || 0) + (active ? 1 : -1));
1296
+ codegenActiveCount = Math.max(0, codegenActiveCount + (active ? 1 : -1));
1000
1297
  }
1001
1298
 
1002
1299
  function codegenCaptureBlocked(): boolean {
1003
- if (typeof window !== 'undefined' && ((window as Window & { __widgeticCodegenCount?: number }).__widgeticCodegenCount || 0) > 0) {
1300
+ if (codegenActiveCount > 0) {
1004
1301
  return true;
1005
1302
  }
1006
1303
  if (isAnyWidgetGenerating()) return true;
@@ -1018,6 +1315,11 @@
1018
1315
  }
1019
1316
 
1020
1317
  function openUpgradePlans() {
1318
+ if (partnerMode) {
1319
+ // A visitor of a partner has no plan of their own to upgrade: the page decides what a limit means for them.
1320
+ reportLimitReached({ message: 'The visitor reached a limit.', code: 'LIMIT_REACHED' });
1321
+ return;
1322
+ }
1021
1323
  window.location.assign('/workspaces/personal/settings/billing');
1022
1324
  }
1023
1325
  let lastGenerationError: string | null = null; // Store the error message for display
@@ -1156,8 +1458,8 @@
1156
1458
  return await processImageFile(imageFile);
1157
1459
  } catch (error) {
1158
1460
  console.error('[Chat→CodeGen] Failed to load uploaded image URL:', uploadedUrl, error);
1159
- showToast('error', 'Could not load uploaded image', {
1160
- description: 'Try uploading the image again.',
1461
+ showToast('error', $t('creator.general.couldNotLoadUploadedImage'), {
1462
+ description: $t('creator.general.tryUploadingTheImageAgain'),
1161
1463
  duration: 6000,
1162
1464
  });
1163
1465
  return null;
@@ -1190,21 +1492,36 @@
1190
1492
  console.warn('[Chat→Upload] WebP convert skipped, using original file', error);
1191
1493
  }
1192
1494
  }
1193
- const result = await uploadChatFileToWidgeticApi(
1194
- uploadFile,
1195
- {
1196
- apiBasePath: uploadBasePath,
1197
- accessToken: authenticatedClientsToken,
1198
- contextType: options?.source === 'preview-screenshot' ? 'browser-ic' : 'widget-codegen',
1199
- source: options?.source || 'chat-upload',
1200
- widgetId: persistWidgetId && !isDraftConvertId(persistWidgetId) ? persistWidgetId : undefined,
1201
- conversationId:
1202
- currentChatConversationId && !isLocalOnlyConversationId(currentChatConversationId)
1203
- ? currentChatConversationId
1204
- : undefined,
1205
- },
1206
- { onProgress: options?.onProgress },
1207
- );
1495
+ // A visitor's session cannot use the resumable (TUS) upload the gateway keeps for bigger files,
1496
+ // so say so up front instead of failing halfway (the File Browser module does the same).
1497
+ if (partnerMode && shouldUseTusForChatUpload(uploadFile)) {
1498
+ throw new Error('This file is too large to attach here (the limit is 10 MB).');
1499
+ }
1500
+ let result: Awaited<ReturnType<typeof uploadChatFileToWidgeticApi>>;
1501
+ try {
1502
+ result = await uploadChatFileToWidgeticApi(
1503
+ uploadFile,
1504
+ {
1505
+ apiBasePath: uploadBasePath,
1506
+ accessToken: authenticatedClientsToken,
1507
+ contextType: options?.source === 'preview-screenshot' ? 'browser-ic' : 'widget-codegen',
1508
+ source: options?.source || 'chat-upload',
1509
+ widgetId: persistWidgetId && !isDraftConvertId(persistWidgetId) ? persistWidgetId : undefined,
1510
+ conversationId:
1511
+ currentChatConversationId && !isLocalOnlyConversationId(currentChatConversationId)
1512
+ ? currentChatConversationId
1513
+ : undefined,
1514
+ },
1515
+ { onProgress: options?.onProgress },
1516
+ );
1517
+ } catch (error) {
1518
+ // This upload does not go through the API clients, so their middleware did not see the refusal: a full storage
1519
+ // allowance is a limit the page is told about, like the others (the chat still shows its own message).
1520
+ if (partnerMode && error instanceof ChatUploadRefusedError) {
1521
+ limitReporter.noteAnswer(error.status, error.body, 'POST /v1/uploads');
1522
+ }
1523
+ throw error;
1524
+ }
1208
1525
  // console.log('[Chat→Upload] Stored attachment:', {
1209
1526
  // id: result.id,
1210
1527
  // url: result.url.slice(0, 80),
@@ -1293,10 +1610,10 @@
1293
1610
  void deleteWidgetDraft(codegenWidgetId).catch(() => {
1294
1611
  // Also drop the legacy localStorage copies if the durable clear fails.
1295
1612
  try {
1296
- localStorage.removeItem(PROMPT_IMAGES_STORAGE_PREFIX + codegenWidgetId);
1297
- localStorage.removeItem(CHAT_DRAFT_STORAGE_PREFIX + codegenWidgetId);
1298
- localStorage.removeItem(PROMPT_TEXT_STORAGE_PREFIX + codegenWidgetId);
1299
- localStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
1613
+ creatorStorage.removeItem(PROMPT_IMAGES_STORAGE_PREFIX + codegenWidgetId);
1614
+ creatorStorage.removeItem(CHAT_DRAFT_STORAGE_PREFIX + codegenWidgetId);
1615
+ creatorStorage.removeItem(PROMPT_TEXT_STORAGE_PREFIX + codegenWidgetId);
1616
+ creatorStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
1300
1617
  } catch {
1301
1618
  /* ignore */
1302
1619
  }
@@ -1348,8 +1665,8 @@
1348
1665
  );
1349
1666
  if (!hasImages && !hasNonImageFiles && promptImpliesVisionReference(content)) {
1350
1667
  const missingImageError =
1351
- 'Promptul menționează o imagine atașată, dar în chat nu e niciun attachment. Folosește butonul Upload.';
1352
- showToast('warning', 'Lipsește imaginea de referință', {
1668
+ $t('creator.codegen.missingImageError');
1669
+ showToast('warning', $t('creator.codegen.missingReferenceImage'), {
1353
1670
  description: missingImageError,
1354
1671
  duration: 10000,
1355
1672
  });
@@ -1565,7 +1882,7 @@
1565
1882
  // console.log('[Chat] Conversation marked', next ? 'completed' : 'active', conversationId);
1566
1883
  } catch (error) {
1567
1884
  console.error('[Chat] Failed to persist conversation completed:', error);
1568
- showToast('error', 'Could not update conversation status');
1885
+ showToast('error', $t('creator.general.couldNotUpdateConversationStatus'));
1569
1886
  conversationCompletedByWidgetId = { ...conversationCompletedByWidgetId, [widgetId]: !next };
1570
1887
  }
1571
1888
  }
@@ -1724,6 +2041,13 @@
1724
2041
  if (Array.isArray(body)) return body;
1725
2042
  if (Array.isArray(nested)) return nested;
1726
2043
  if (Array.isArray(envelopeData)) return envelopeData;
2044
+ // An answer that carries error or message (the apiRequest envelope) is not an empty list:
2045
+ // throw it, as the loader did before the raw read, so the caller shows the message instead
2046
+ // of a blank list. A refused request (a 404 for a canvas that is not there) is thrown as a
2047
+ // ResponseError by the client itself, before this point.
2048
+ if (body && (body.error || body.message)) {
2049
+ throw new Error(String(body.message || body.error));
2050
+ }
1727
2051
  return [];
1728
2052
  }
1729
2053
 
@@ -1963,15 +2287,17 @@
1963
2287
  */
1964
2288
  function resolveLiveWidgetShapeIframe(widgetId: string | null | undefined): HTMLIFrameElement | null {
1965
2289
  const targetId = widgetId || focusedPanelWidgetId || selectedWidgetId;
2290
+ // The tree the creator is in: in a partner's page `document.querySelector` cannot see into its shadow root.
2291
+ const searchRoot = getCreatorShadowRoot(creatorRootEl) ?? document;
1966
2292
  if (targetId) {
1967
- const liveById = document.querySelector(
2293
+ const liveById = searchRoot.querySelector(
1968
2294
  `iframe.widget-shape-live-preview-iframe[data-widget-id="${CSS.escape(targetId)}"]`,
1969
2295
  ) as HTMLIFrameElement | null;
1970
2296
  return liveById?.contentWindow ? liveById : null;
1971
2297
  }
1972
2298
  // No id known: only unambiguous when exactly one shape is mounted.
1973
2299
  const all = Array.from(
1974
- document.querySelectorAll('iframe.widget-shape-live-preview-iframe'),
2300
+ searchRoot.querySelectorAll('iframe.widget-shape-live-preview-iframe'),
1975
2301
  ) as HTMLIFrameElement[];
1976
2302
  const withWindow = all.filter((frame) => !!frame.contentWindow);
1977
2303
  return withWindow.length === 1 ? withWindow[0] : null;
@@ -2057,14 +2383,15 @@
2057
2383
  host.className = 'wc-hidden-screenshot-host';
2058
2384
  host.setAttribute(
2059
2385
  'style',
2060
- 'position:fixed;left:-10000px;top:0;width:800px;height:600px;opacity:0;pointer-events:none;z-index:-1;',
2386
+ 'position:fixed;left:-10000px;top:0;width:800px;height:600px;opacity:0;pointer-events:none;z-index:-1;', // rtl-ok: parked far outside the screen where nobody sees it, whatever the direction
2061
2387
  );
2062
2388
  const iframe = document.createElement('iframe');
2063
2389
  iframe.title = 'Hidden widget screenshot';
2064
2390
  iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-forms');
2065
2391
  iframe.style.cssText = 'width:800px;height:600px;border:0;';
2066
2392
  host.appendChild(iframe);
2067
- document.body.appendChild(host);
2393
+ // In the creator's own tree: in a partner's page the creator must not put a frame in the page's <body>.
2394
+ (getCreatorShadowRoot(creatorRootEl) ?? document.body).appendChild(host);
2068
2395
 
2069
2396
  try {
2070
2397
  await new Promise<void>((resolve, reject) => {
@@ -2672,10 +2999,10 @@
2672
2999
  syncWidgetShapeLivePreviews();
2673
3000
  panelDisplayRevision += 1;
2674
3001
  }
2675
- showToast('success', undoMode ? 'Change undone' : 'Checkpoint restored', {
3002
+ showToast('success', undoMode ? $t('creator.general.changeUndone') : $t('creator.version.checkpointRestored'), {
2676
3003
  description: undoMode
2677
- ? `Code reverted to commit ${formatCommitShaShort(historicalSha)}. Refreshing preview…`
2678
- : `Widget code at commit ${formatCommitShaShort(historicalSha)}. Refreshing preview…`,
3004
+ ? $t('creator.codegen.codeRevertedToCommitRefreshing', { commit: formatCommitShaShort(historicalSha) })
3005
+ : $t('creator.codegen.widgetCodeAtCommitRefreshing', { commit: formatCommitShaShort(historicalSha) }),
2679
3006
  duration: 6000,
2680
3007
  });
2681
3008
  liveDesignValues = {};
@@ -2719,8 +3046,8 @@
2719
3046
  void scheduleBuildRetry();
2720
3047
  } else {
2721
3048
  console.warn('[Chat→Backend] Git rollback not detected in response, refreshing preview anyway...');
2722
- showToast('warning', 'Restore completed with warnings', {
2723
- description: 'Git rollback may not have applied. Try Rebuild from the preview panel.',
3049
+ showToast('warning', $t('creator.version.restoreCompletedWithWarnings'), {
3050
+ description: $t('creator.codegen.gitRollbackMayNotHave'),
2724
3051
  duration: 8000,
2725
3052
  });
2726
3053
  liveDesignValues = {};
@@ -2736,8 +3063,8 @@
2736
3063
  return data;
2737
3064
  } catch (error) {
2738
3065
  console.error('[Chat→Backend] Failed to restore checkpoint:', error);
2739
- showToast('error', 'Failed to restore checkpoint', {
2740
- description: error instanceof Error ? error.message : 'Unknown error',
3066
+ showToast('error', $t('creator.version.failedToRestoreCheckpoint'), {
3067
+ description: error instanceof Error ? error.message : $t('creator.general.unknownError'),
2741
3068
  });
2742
3069
  return null;
2743
3070
  }
@@ -2813,7 +3140,8 @@
2813
3140
  /** The version whose title rename is in flight, as `widgetId:version`. */
2814
3141
  let renamingTitleFor: string | null = null;
2815
3142
  let liveHistoryPanelTop = 0;
2816
- let liveHistoryPanelRight = 0;
3143
+ /** The edge of the publish history list that lines up with the header cluster, as style text: it is the end edge of the cluster. */
3144
+ let liveHistoryPanelPlacement = '';
2817
3145
  /** True once publish history fetch completed for the current widget (or widget was never published). */
2818
3146
  let publishHistoryResolved = false;
2819
3147
  let publishHistoryResolvedForWidgetId: string | null = null;
@@ -3393,7 +3721,7 @@
3393
3721
  contentSchema = normalizeContentSchemaFromApiResponse(contentRes);
3394
3722
 
3395
3723
  if (!designSchema && !contentSchema) {
3396
- schemaError = 'No editable settings found. Generate and publish the widget first.';
3724
+ schemaError = $t('creator.publish.noEditableSettingsFoundGenerate');
3397
3725
  }
3398
3726
 
3399
3727
  // console.log('[CompositionEditor] Schemas loaded for', widgetId.substring(0, 8), {
@@ -3402,7 +3730,7 @@
3402
3730
  // });
3403
3731
  } catch (err: any) {
3404
3732
  console.error('[CompositionEditor] Failed to load schemas:', err);
3405
- schemaError = err?.message || 'Failed to load editor settings';
3733
+ schemaError = err?.message || $t('creator.general.failedToLoadEditorSettings');
3406
3734
  }
3407
3735
 
3408
3736
  widgetSchemaCache.set(widgetId, {
@@ -3928,7 +4256,7 @@
3928
4256
  const label = property?.label ?? result.property;
3929
4257
  applyDesignValuesToPreview(widgetId, { [result.property]: result.value });
3930
4258
  const card: DesignControlRequest = {
3931
- summary: `Set ${label} to ${String(result.value)}.`,
4259
+ summary: $t('creator.general.setTo', { label, value: String(result.value) }),
3932
4260
  properties: [
3933
4261
  {
3934
4262
  id: result.property,
@@ -4382,7 +4710,7 @@
4382
4710
  // Ensure the created object carries the name we used locally
4383
4711
  if (!created.name) created.name = nameToUse;
4384
4712
  // console.log('[Compositions] Created:', created);
4385
- showToast('success', `Composition "${nameToUse}" created`);
4713
+ showToast('success', $t('creator.composition.compositionCreated', { name: nameToUse }));
4386
4714
 
4387
4715
  // Select immediately so loadCompositions doesn't auto-select a different one
4388
4716
  selectComposition(created);
@@ -4391,7 +4719,7 @@
4391
4719
  await loadCompositions();
4392
4720
  } catch (err: any) {
4393
4721
  console.error('[Compositions] Create failed:', err);
4394
- showToast('error', `Failed to create composition: ${err.message || 'Unknown error'}`);
4722
+ showToast('error', $t('creator.composition.failedToCreateComposition', { message: err.message || $t('creator.general.unknownError') }));
4395
4723
  } finally {
4396
4724
  compositionSaving = false;
4397
4725
  }
@@ -4415,7 +4743,7 @@
4415
4743
  });
4416
4744
  const updated = (res as any)?.data ?? res;
4417
4745
  // console.log('[Compositions] Updated:', updated);
4418
- showToast('success', 'Composition saved');
4746
+ showToast('success', $t('creator.composition.compositionSaved'));
4419
4747
  compositionDirty = false;
4420
4748
  // Preserve local name if the API response doesn't include it
4421
4749
  const currentName = selectedComposition!.name;
@@ -4424,7 +4752,7 @@
4424
4752
  return true;
4425
4753
  } catch (err: any) {
4426
4754
  console.error('[Compositions] Update failed:', err);
4427
- showToast('error', `Failed to update: ${err.message || 'Unknown error'}`);
4755
+ showToast('error', $t('creator.general.failedToUpdate', { message: err.message || $t('creator.general.unknownError') }));
4428
4756
  return false;
4429
4757
  } finally {
4430
4758
  compositionSaving = false;
@@ -4502,11 +4830,11 @@
4502
4830
  id: compositionId,
4503
4831
  updateComposition: { name: trimmed }
4504
4832
  });
4505
- showToast('success', 'Composition renamed');
4833
+ showToast('success', $t('creator.composition.compositionRenamed'));
4506
4834
  await loadCompositions();
4507
4835
  } catch (err: any) {
4508
4836
  console.error('[Compositions] Rename failed:', err);
4509
- showToast('error', 'Failed to rename composition');
4837
+ showToast('error', $t('creator.composition.failedToRenameComposition'));
4510
4838
  } finally {
4511
4839
  editingCompositionId = null;
4512
4840
  }
@@ -4524,7 +4852,7 @@
4524
4852
  deletingCompositionId = null;
4525
4853
  try {
4526
4854
  await compositionsClient.deleteComposition({ id: compositionId });
4527
- showToast('success', 'Composition deleted');
4855
+ showToast('success', $t('creator.composition.compositionDeleted'));
4528
4856
  if (selectedComposition?.id === compositionId) {
4529
4857
  selectedComposition = null;
4530
4858
  liveDesignValues = {};
@@ -4535,7 +4863,7 @@
4535
4863
  await loadCompositions();
4536
4864
  } catch (err: any) {
4537
4865
  console.error('[Compositions] Delete failed:', err);
4538
- showToast('error', 'Failed to delete composition');
4866
+ showToast('error', $t('creator.composition.failedToDeleteComposition'));
4539
4867
  }
4540
4868
  }
4541
4869
 
@@ -4573,7 +4901,7 @@
4573
4901
  // console.log('[Embed] Saved dimensions:', embedWidth, '×', embedHeight);
4574
4902
  } catch (err) {
4575
4903
  console.error('[Embed] Failed to save dimensions:', err);
4576
- showToast('error', 'Failed to save dimensions');
4904
+ showToast('error', $t('creator.general.failedToSaveDimensions'));
4577
4905
  } finally {
4578
4906
  isSavingEmbedDims = false;
4579
4907
  }
@@ -4700,10 +5028,14 @@
4700
5028
 
4701
5029
  // debugMode — current ON/OFF state. User can still toggle when the UI is available.
4702
5030
  let debugMode = debugModeAvailable;
4703
- if (typeof localStorage !== 'undefined' && debugModeAvailable) {
4704
- const storedDebugMode = localStorage.getItem('widgetic:site-debug-on');
4705
- if (storedDebugMode === '1' || storedDebugMode === 'true') debugMode = true;
4706
- if (storedDebugMode === '0' || storedDebugMode === 'false') debugMode = false;
5031
+ if (debugModeAvailable && typeof window !== 'undefined') {
5032
+ try {
5033
+ const storedDebugMode = creatorStorage.getItem('widgetic:site-debug-on');
5034
+ if (storedDebugMode === '1' || storedDebugMode === 'true') debugMode = true;
5035
+ if (storedDebugMode === '0' || storedDebugMode === 'false') debugMode = false;
5036
+ } catch {
5037
+ /* storage unavailable (a sandboxed frame): keep the default */
5038
+ }
4707
5039
  }
4708
5040
  // console.log('[WidgetCreator] Debug from host/env', {
4709
5041
  // hostProvidedDebug,
@@ -4878,19 +5210,14 @@
4878
5210
 
4879
5211
  // Toggle debug mode
4880
5212
  function emitCreatorDebugChanged() {
4881
- if (typeof window === 'undefined') return;
4882
- window.dispatchEvent(
4883
- new CustomEvent(CREATOR_DEBUG_CHANGED_EVENT, {
4884
- detail: { debugMode, debugModeAvailable }
4885
- })
4886
- );
5213
+ announceToSite(CREATOR_DEBUG_CHANGED_EVENT, { debugMode, debugModeAvailable });
4887
5214
  }
4888
5215
 
4889
5216
  function toggleDebugMode() {
4890
5217
  if (!debugModeAvailable) return;
4891
5218
  debugMode = !debugMode;
4892
5219
  try {
4893
- localStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
5220
+ creatorStorage.setItem('widgetic:site-debug-on', debugMode ? '1' : '0');
4894
5221
  } catch (err) {
4895
5222
  console.warn('[WidgetCreator] Could not persist debug mode', err);
4896
5223
  }
@@ -4912,12 +5239,7 @@
4912
5239
  let canvasPrimaryWidgetId: string | null = null;
4913
5240
 
4914
5241
  function emitCreatorWireframeChanged() {
4915
- if (typeof window === 'undefined') return;
4916
- window.dispatchEvent(
4917
- new CustomEvent(CREATOR_WIREFRAME_CHANGED_EVENT, {
4918
- detail: { wireframeMode: canvasWireframeMode }
4919
- })
4920
- );
5242
+ announceToSite(CREATOR_WIREFRAME_CHANGED_EVENT, { wireframeMode: canvasWireframeMode });
4921
5243
  }
4922
5244
 
4923
5245
  function handleHostToggleWireframeEvent() {
@@ -4927,12 +5249,7 @@
4927
5249
  }
4928
5250
 
4929
5251
  function emitCreatorAdvancedChanged() {
4930
- if (typeof window === 'undefined') return;
4931
- window.dispatchEvent(
4932
- new CustomEvent(CREATOR_ADVANCED_CHANGED_EVENT, {
4933
- detail: { advancedFeatures: canvasAdvancedFeatures }
4934
- })
4935
- );
5252
+ announceToSite(CREATOR_ADVANCED_CHANGED_EVENT, { advancedFeatures: canvasAdvancedFeatures });
4936
5253
  }
4937
5254
 
4938
5255
  function handleHostToggleAdvancedEvent() {
@@ -4959,8 +5276,8 @@
4959
5276
  function handleHostOpenWidgetDetailsEvent(): void {
4960
5277
  const widgetId = resolveHostTargetWidgetId();
4961
5278
  if (!widgetId) {
4962
- showToast('warning', 'Select a widget first', {
4963
- description: 'Click a widget on the canvas, then use Edit to open Widget Details.',
5279
+ showToast('warning', $t('creator.widget.selectAWidgetFirst'), {
5280
+ description: $t('creator.canvas.clickAWidgetOnThe'),
4964
5281
  });
4965
5282
  return;
4966
5283
  }
@@ -4971,8 +5288,8 @@
4971
5288
  async function handleHostDuplicateWidgetEvent(): Promise<void> {
4972
5289
  const widgetId = canvasPrimaryWidgetId || resolveHostTargetWidgetId();
4973
5290
  if (!widgetId || isDraftConvertId(widgetId)) {
4974
- showToast('warning', 'Select a widget first', {
4975
- description: 'Duplicate from the header copies the widget in the title.',
5291
+ showToast('warning', $t('creator.widget.selectAWidgetFirst'), {
5292
+ description: $t('creator.widget.duplicateFromTheHeaderCopies'),
4976
5293
  });
4977
5294
  return;
4978
5295
  }
@@ -4989,7 +5306,7 @@
4989
5306
  async function handleHostDeleteWidgetEvent(): Promise<void> {
4990
5307
  const widgetId = resolveHostTargetWidgetId();
4991
5308
  if (!widgetId) {
4992
- showToast('warning', 'Select a widget first');
5309
+ showToast('warning', $t('creator.widget.selectAWidgetFirst'));
4993
5310
  return;
4994
5311
  }
4995
5312
  if (canvasRef?.selectWidgetShape?.(widgetId) && typeof canvasRef.deleteSelectedObjects === 'function') {
@@ -5004,8 +5321,8 @@
5004
5321
  }
5005
5322
 
5006
5323
  function emitCreatorSaveState(dirty: boolean): void {
5007
- if (typeof window === 'undefined' || !embedded) return;
5008
- window.dispatchEvent(new CustomEvent('widgetic:creator-save-state', { detail: { dirty } }));
5324
+ if (!embedded) return;
5325
+ announceToSite('widgetic:creator-save-state', { dirty });
5009
5326
  }
5010
5327
 
5011
5328
  function handleHostSaveCanvasEvent(): void {
@@ -5013,7 +5330,7 @@
5013
5330
  const json = canvasRef?.saveCanvas?.() ?? null;
5014
5331
  if (!json) {
5015
5332
  console.warn('[CreatorApp] Host Save ignored — saveCanvas returned null');
5016
- showToast('error', 'Nothing to save', { description: 'Canvas is not ready yet.' });
5333
+ showToast('error', $t('creator.general.nothingToSave'), { description: $t('creator.canvas.canvasIsNotReadyYet') });
5017
5334
  return;
5018
5335
  }
5019
5336
  void handleCanvasAutoSave(json, false, { force: true });
@@ -5162,9 +5479,7 @@
5162
5479
  primaryWidgetId = items[0].id;
5163
5480
  }
5164
5481
  // console.log('[CreatorApp] Emit canvas widgets for header', reason, items.length, primaryWidgetId);
5165
- window.dispatchEvent(new CustomEvent(CREATOR_CANVAS_WIDGETS_EVENT, {
5166
- detail: { widgets: items, primaryWidgetId: primaryWidgetId || '' }
5167
- }));
5482
+ announceToSite(CREATOR_CANVAS_WIDGETS_EVENT, { widgets: items, primaryWidgetId: primaryWidgetId || '' });
5168
5483
  }
5169
5484
 
5170
5485
  function handleHostRequestCanvasWidgetsEvent() {
@@ -5368,10 +5683,10 @@
5368
5683
  if (!widgetId) return;
5369
5684
  try {
5370
5685
  if (active) {
5371
- localStorage.setItem(`crossTab_generating_${widgetId}`, String(Date.now()));
5686
+ creatorStorage.setItem(`crossTab_generating_${widgetId}`, String(Date.now()));
5372
5687
  // console.log('[CrossTab] Set generating flag for widget:', widgetId);
5373
5688
  } else {
5374
- localStorage.removeItem(`crossTab_generating_${widgetId}`);
5689
+ creatorStorage.removeItem(`crossTab_generating_${widgetId}`);
5375
5690
  // console.log('[CrossTab] Cleared generating flag for widget:', widgetId);
5376
5691
  }
5377
5692
  } catch (e) { /* localStorage unavailable */ }
@@ -5382,10 +5697,10 @@
5382
5697
  if (!widgetId) return;
5383
5698
  try {
5384
5699
  if (active) {
5385
- localStorage.setItem(`crossTab_publishing_${widgetId}`, String(Date.now()));
5700
+ creatorStorage.setItem(`crossTab_publishing_${widgetId}`, String(Date.now()));
5386
5701
  // console.log('[CrossTab] Set publishing flag for widget:', widgetId);
5387
5702
  } else {
5388
- localStorage.removeItem(`crossTab_publishing_${widgetId}`);
5703
+ creatorStorage.removeItem(`crossTab_publishing_${widgetId}`);
5389
5704
  // console.log('[CrossTab] Cleared publishing flag for widget:', widgetId);
5390
5705
  }
5391
5706
  } catch (e) { /* localStorage unavailable */ }
@@ -5395,11 +5710,11 @@
5395
5710
  function checkCrossTabGenerating(widgetId = selectedWidgetId): boolean {
5396
5711
  if (!widgetId || isGeneratingCode) return false;
5397
5712
  try {
5398
- const ts = localStorage.getItem(`crossTab_generating_${widgetId}`);
5713
+ const ts = creatorStorage.getItem(`crossTab_generating_${widgetId}`);
5399
5714
  if (!ts) return false;
5400
5715
  const elapsed = Date.now() - Number(ts);
5401
5716
  if (elapsed > CROSS_TAB_STALE_TIMEOUT_MS) {
5402
- localStorage.removeItem(`crossTab_generating_${widgetId}`);
5717
+ creatorStorage.removeItem(`crossTab_generating_${widgetId}`);
5403
5718
  return false;
5404
5719
  }
5405
5720
  return true;
@@ -5410,11 +5725,11 @@
5410
5725
  function checkCrossTabPublishing(widgetId = selectedWidgetId): boolean {
5411
5726
  if (!widgetId || isPublishing) return false; // If WE are publishing, ignore cross-tab flag
5412
5727
  try {
5413
- const ts = localStorage.getItem(`crossTab_publishing_${widgetId}`);
5728
+ const ts = creatorStorage.getItem(`crossTab_publishing_${widgetId}`);
5414
5729
  if (!ts) return false;
5415
5730
  const elapsed = Date.now() - Number(ts);
5416
5731
  if (elapsed > CROSS_TAB_STALE_TIMEOUT_MS) {
5417
- localStorage.removeItem(`crossTab_publishing_${widgetId}`);
5732
+ creatorStorage.removeItem(`crossTab_publishing_${widgetId}`);
5418
5733
  return false;
5419
5734
  }
5420
5735
  return true;
@@ -5472,7 +5787,7 @@
5472
5787
  const persisted = await readActiveGeneration(widgetId);
5473
5788
  if (persisted) return persisted;
5474
5789
  try {
5475
- return localStorage.getItem(`activeGeneration_${widgetId}`);
5790
+ return creatorStorage.getItem(`activeGeneration_${widgetId}`);
5476
5791
  } catch (e) { return null; }
5477
5792
  }
5478
5793
 
@@ -5529,8 +5844,8 @@
5529
5844
  // console.log(`[Version] Commit restored from completed operation: ${resumeCommitSha.substring(0, 7)}`);
5530
5845
  }
5531
5846
  generateCodeStatus = 'Code generation completed! Auto-saving...';
5532
- showToast('success', 'Code generation completed', {
5533
- description: 'Generation finished while you were away. Auto-saving to repo...',
5847
+ showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5848
+ description: $t('creator.codegen.generationFinishedWhileYouWere'),
5534
5849
  duration: 5000
5535
5850
  });
5536
5851
  generateCodeStatus = 'Code generation completed! Changes saved to GitLab.';
@@ -5553,7 +5868,7 @@
5553
5868
  lastGenerationFailed = true;
5554
5869
  lastGenerationError = failedMsg;
5555
5870
  generateCodeStatus = `❌ Code generation failed`;
5556
- showToast('error', isServiceErr ? 'Service temporarily unavailable' : 'Code generation failed', {
5871
+ showToast('error', isServiceErr ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
5557
5872
  description: failedMsg,
5558
5873
  duration: isServiceErr ? 10000 : 6000
5559
5874
  });
@@ -5578,8 +5893,8 @@
5578
5893
  // Keep preview tab so user sees the "Generating..." overlay
5579
5894
  widgetDetails?.setInlinePanelView('preview');
5580
5895
 
5581
- showToast('info', 'Generation in progress', {
5582
- description: 'Reconnected to an active code generation. Please wait...',
5896
+ showToast('info', $t('creator.codegen.generationInProgress'), {
5897
+ description: $t('creator.codegen.reconnectedToAnActiveCode'),
5583
5898
  duration: 4000
5584
5899
  });
5585
5900
 
@@ -5600,7 +5915,7 @@
5600
5915
  lastGenerationFailed = true;
5601
5916
  lastGenerationError = resumeError;
5602
5917
  clearActiveOperationId();
5603
- showToast('error', isResumeServiceErr ? 'Service temporarily unavailable' : 'Code generation failed', {
5918
+ showToast('error', isResumeServiceErr ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
5604
5919
  description: resumeError,
5605
5920
  duration: isResumeServiceErr ? 10000 : 8000
5606
5921
  });
@@ -5612,8 +5927,8 @@
5612
5927
 
5613
5928
  if (selectedWidgetId !== resumeWidgetId) {
5614
5929
  // console.log('[GenerationResilience] Completed for widget', resumeWidgetId, 'but user switched to', selectedWidgetId);
5615
- showToast('success', 'Code generation completed', {
5616
- description: 'Generation finished for a different widget.',
5930
+ showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5931
+ description: $t('creator.codegen.generationFinishedForADifferent'),
5617
5932
  duration: 5000
5618
5933
  });
5619
5934
  return;
@@ -5621,8 +5936,8 @@
5621
5936
 
5622
5937
  hasChangesToSave = false;
5623
5938
  generateCodeStatus = 'Code generation completed! Saved to GitLab.';
5624
- showToast('success', 'Code generation completed', {
5625
- description: 'Code saved to GitLab and preview ready.',
5939
+ showToast('success', $t('creator.codegen.codeGenerationCompleted'), {
5940
+ description: $t('creator.codegen.codeSavedToGitlabAnd'),
5626
5941
  duration: 5000
5627
5942
  });
5628
5943
  setTimeout(async () => {
@@ -5677,6 +5992,8 @@
5677
5992
  let isLoadingCanvasOnce = false;
5678
5993
  let canvasHydrateRetryTimer: ReturnType<typeof setTimeout> | null = null;
5679
5994
  let canvasHydrateRetryCount = 0;
5995
+ /** How many reads of the canvas from the API are running (see `tryLoadCanvasState`). */
5996
+ let canvasRemoteReadsInFlight = 0;
5680
5997
  const CANVAS_HYDRATE_MAX_RETRIES = 10;
5681
5998
  const CANVAS_API_TIMEOUT_MS = 8000;
5682
5999
 
@@ -5697,7 +6014,7 @@
5697
6014
  }
5698
6015
 
5699
6016
  function scheduleCanvasHydrateRetry(reason: string) {
5700
- if (isCanvasStateLoaded) return;
6017
+ if (isCanvasStateLoaded || canvasUnavailable) return;
5701
6018
  if (canvasHydrateRetryCount >= CANVAS_HYDRATE_MAX_RETRIES) {
5702
6019
  console.warn('[CanvasDebug] Exhausted canvas hydrate retries:', reason);
5703
6020
  armCanvasLoadFailsafe(reason, canvasId || '__pending__');
@@ -5709,6 +6026,9 @@
5709
6026
  clearCanvasHydrateRetry();
5710
6027
  canvasHydrateRetryTimer = setTimeout(() => {
5711
6028
  canvasHydrateRetryTimer = null;
6029
+ // Partner mode: a read that is still running will finish the load, or schedule the next try itself; a second
6030
+ // load beside it would only ask for the same canvas again.
6031
+ if (partnerMode && canvasRemoteReadsInFlight > 0) return;
5712
6032
  isLoadingCanvasOnce = false;
5713
6033
  void loadCurrentCanvas();
5714
6034
  }, delayMs);
@@ -5727,6 +6047,9 @@
5727
6047
  */
5728
6048
  function readCanvasIdFromAddressBar(): string | null {
5729
6049
  if (typeof window === 'undefined') return null;
6050
+ // In a partner's page the address bar says nothing about Widgetic canvases (a partner's own `/canvas/…` route
6051
+ // must not be mistaken for one): the page names the canvas through the `canvasId` prop.
6052
+ if (!mayUseAddressBar()) return null;
5730
6053
  try {
5731
6054
  const pathParts = window.location.pathname.split('/');
5732
6055
  const canvasIndex = pathParts.indexOf('canvas');
@@ -5938,7 +6261,7 @@
5938
6261
  }
5939
6262
  } catch (error) {
5940
6263
  console.error('Widget Creator: Load canvases error:', error);
5941
- const defaultError = 'Failed to load canvases';
6264
+ const defaultError = $t('creator.canvas.failedToLoadCanvases');
5942
6265
  const message = toErrorMessage(error, defaultError);
5943
6266
  widgetsError = message;
5944
6267
  const savedCanvasId = routeCanvasId || getSavedSelectedCanvasId();
@@ -5961,7 +6284,7 @@
5961
6284
  }
5962
6285
  if (widgetsError && canvasHydrateRetryCount === 0) {
5963
6286
  showToast('error', defaultError, {
5964
- description: `${message} Retrying when the API is back…`,
6287
+ description: $t('creator.general.retryingWhenTheApiIs', { message }),
5965
6288
  duration: 5000
5966
6289
  });
5967
6290
  }
@@ -6045,8 +6368,9 @@
6045
6368
 
6046
6369
  /** Close canvas dropdown on outside click */
6047
6370
  function handleCanvasDropdownOutsideClick(e: MouseEvent) {
6048
- const target = e.target as HTMLElement;
6049
- if (!target.closest('.canvas-selector-group')) {
6371
+ // The whole path is looked at, not `e.target.closest(…)`: in a shadow root the target seen from `window` is the
6372
+ // shadow's host element, so the dropdown would close on every click, including the one that opens it.
6373
+ if (!eventPathMatches(e, '.canvas-selector-group')) {
6050
6374
  showCanvasDropdown = false;
6051
6375
  if (canvasNameEditing) commitCanvasNameEdit();
6052
6376
  }
@@ -6153,7 +6477,7 @@
6153
6477
  selectedWidgetJsPath = null;
6154
6478
  widgetDetailsStep = 'create';
6155
6479
  lastSavedCanvasObjectCount = 0;
6156
- try { sessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, '0'); } catch { /* ignore */ }
6480
+ try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, '0'); } catch { /* ignore */ }
6157
6481
  canvasRef?.onClearAllObjects();
6158
6482
  // console.log('[CreatorApp] Blank canvas session:', reason, 'epoch', canvasLoadEpoch);
6159
6483
  }
@@ -6459,7 +6783,7 @@
6459
6783
  console.error('[WidgetCreator] Failed to delete canvas:', targetId, err);
6460
6784
  // Keep the dialog open so the user can react; a partial failure leaves
6461
6785
  // the canvas intact on purpose (the API refuses to orphan widgets).
6462
- deleteCanvasError = 'Could not delete this canvas. Some of its widgets could not be removed, so nothing was deleted.';
6786
+ deleteCanvasError = $t('creator.canvas.couldNotDeleteThisCanvas');
6463
6787
  return;
6464
6788
  }
6465
6789
  deleteCanvasTarget = null;
@@ -6471,7 +6795,7 @@
6471
6795
  // if no canvas id, return
6472
6796
  if (!canvasId) {
6473
6797
  // console.log('Widget Creator: loadWidgetsForCanvas: No canvas id, returning');
6474
- widgetsError = 'No canvas id, cannot load widgets!';
6798
+ widgetsError = $t('creator.canvas.noCanvasIdCannotLoad');
6475
6799
  widgets = [];
6476
6800
  selectedWidgetId = null;
6477
6801
  isLoadingWidgets = false;
@@ -6491,7 +6815,9 @@
6491
6815
  }
6492
6816
 
6493
6817
  // Fetch widgets directly by canvasId. Raw JSON keeps thumbnailUrl,
6494
- // which the generated model drops.
6818
+ // which the generated model drops. A refused request or an error answer
6819
+ // is thrown (see readWidgetList), so the catch below shows it and
6820
+ // saysCanvasIsMissing can read a 404 in partner mode.
6495
6821
  const fetched = await readWidgetList(canvasId);
6496
6822
 
6497
6823
  const previousById = new Map(
@@ -6572,15 +6898,19 @@
6572
6898
  }
6573
6899
  } catch (error) {
6574
6900
  console.error('Widget Creator: Failed to load widgets for canvas:', error);
6575
- const defaultError = 'Failed to load widgets';
6901
+ const defaultError = $t('creator.widget.failedToLoadWidgets');
6576
6902
  const message = toErrorMessage(error, defaultError);
6903
+ // Partner mode: "no such canvas" is the answer to the canvas the page named, not a problem with the widget list.
6904
+ if (saysCanvasIsMissing(error)) declareCanvasUnavailable(canvasId?.trim() || null, message);
6577
6905
  widgetsError = message;
6578
6906
  widgets = [];
6579
6907
  selectedWidgetId = null;
6580
- showToast('error', defaultError, {
6581
- description: message,
6582
- duration: 5000
6583
- });
6908
+ if (!canvasUnavailable) {
6909
+ showToast('error', defaultError, {
6910
+ description: message,
6911
+ duration: 5000
6912
+ });
6913
+ }
6584
6914
  } finally {
6585
6915
  isLoadingWidgets = false;
6586
6916
  isLoadingWidgetsOnce = false;
@@ -6652,8 +6982,8 @@
6652
6982
  const restored = await restoreWidgetShapesFromDb();
6653
6983
  if (restored === 0) {
6654
6984
  canvasShapesMissingWarning = true;
6655
- showToast('error', 'Could not restore shapes yet', {
6656
- description: 'Canvas may still be loading. Try Retry load, or wait a moment and click again.',
6985
+ showToast('error', $t('creator.widget.couldNotRestoreShapesYet'), {
6986
+ description: $t('creator.canvas.canvasMayStillBeLoading'),
6657
6987
  duration: 6000,
6658
6988
  });
6659
6989
  }
@@ -6734,7 +7064,7 @@
6734
7064
  refreshLinkedWidgetIds();
6735
7065
  canvasShapesMissingWarning = false;
6736
7066
  if (!options.silent) {
6737
- showToast('success', `Restored ${actuallyRestored} widget shape${actuallyRestored === 1 ? '' : 's'} on canvas`, {
7067
+ showToast('success', $t('creator.canvas.restoredShapes', { count: actuallyRestored }), {
6738
7068
  duration: 6000,
6739
7069
  });
6740
7070
  }
@@ -6904,7 +7234,7 @@
6904
7234
  * a stale widget_id from the previous canvas overwrites the header/primary.
6905
7235
  */
6906
7236
  function resolveEmbeddedDeepLinkWidgetId(): string | null {
6907
- if (typeof window !== 'undefined') {
7237
+ if (typeof window !== 'undefined' && mayUseAddressBar()) {
6908
7238
  try {
6909
7239
  const fromUrl = new URLSearchParams(window.location.search).get('widget_id');
6910
7240
  if (fromUrl && fromUrl.trim()) return fromUrl.trim();
@@ -6978,6 +7308,7 @@
6978
7308
  /** Ensure the address bar points at the canvas we actually loaded (refresh-safe). */
6979
7309
  function syncUrlCanvasId(canvasIdToSync: string | null): void {
6980
7310
  if (typeof window === 'undefined' || !embedded) return;
7311
+ if (!mayUseAddressBar()) return;
6981
7312
  if (!canvasIdToSync || !canvasIdToSync.trim()) return;
6982
7313
  try {
6983
7314
  const url = new URL(window.location.href);
@@ -6993,11 +7324,25 @@
6993
7324
  }
6994
7325
  }
6995
7326
 
7327
+ /** The reads of a canvas's primary widget that are running now, by canvas id. */
7328
+ const primaryWidgetReadsInFlight = new Map<string, Promise<string | null>>();
7329
+
6996
7330
  /**
6997
7331
  * Canvas-only embed deep-link (My widgets / canvas without widget_id):
6998
7332
  * read canvases.primary_widget_id so Creator can open that widget panel.
6999
7333
  */
7000
- async function resolvePrimaryWidgetIdForCanvas(targetCanvasId: string): Promise<string | null> {
7334
+ function resolvePrimaryWidgetIdForCanvas(targetCanvasId: string): Promise<string | null> {
7335
+ const readKey = targetCanvasId?.trim();
7336
+ if (!readKey || canvasUnavailable) return Promise.resolve(null);
7337
+ // Several parts of the start ask for this at the same moment; they share one read of the canvas.
7338
+ const readRunning = primaryWidgetReadsInFlight.get(readKey);
7339
+ if (readRunning) return readRunning;
7340
+ const read = readPrimaryWidgetIdForCanvas(targetCanvasId).finally(() => primaryWidgetReadsInFlight.delete(readKey));
7341
+ primaryWidgetReadsInFlight.set(readKey, read);
7342
+ return read;
7343
+ }
7344
+
7345
+ async function readPrimaryWidgetIdForCanvas(targetCanvasId: string): Promise<string | null> {
7001
7346
  if (!canvasesClient || !targetCanvasId?.trim()) return null;
7002
7347
  try {
7003
7348
  const canvasRecord = await canvasesClient.getCanvas({ id: targetCanvasId });
@@ -7054,6 +7399,8 @@
7054
7399
  targetCanvasId.substring(0, 8),
7055
7400
  err
7056
7401
  );
7402
+ // Partner mode: the first read to be told "no such canvas" says so for the whole creator.
7403
+ if (saysCanvasIsMissing(err)) declareCanvasUnavailable(targetCanvasId, toErrorMessage(err, 'Canvas not found'));
7057
7404
  return null;
7058
7405
  }
7059
7406
  }
@@ -7781,11 +8128,11 @@
7781
8128
  backfillWidgetShapeMetadata();
7782
8129
  syncWidgetShapeLivePreviews();
7783
8130
  // console.log('[WidgetRename] Successfully renamed widget:', widgetId, 'to:', newName);
7784
- showToast('success', `Widget renamed to "${newName}"`);
8131
+ showToast('success', $t('creator.widget.widgetRenamedTo', { name: newName }));
7785
8132
  } catch (error) {
7786
8133
  console.error('[WidgetRename] Failed to rename widget:', error);
7787
- showToast('error', 'Failed to rename widget', {
7788
- description: error instanceof Error ? error.message : 'Unknown error'
8134
+ showToast('error', $t('creator.widget.failedToRenameWidget'), {
8135
+ description: error instanceof Error ? error.message : $t('creator.general.unknownError')
7789
8136
  });
7790
8137
  } finally {
7791
8138
  isRenamingInProgress = false;
@@ -8016,8 +8363,8 @@
8016
8363
  getChatMethodsForWidget(statusWidgetId)?.updateLatestCodegenStatusMessage?.(
8017
8364
  'Generation stopped by user. You can Retry this prompt.',
8018
8365
  );
8019
- showToast('info', 'Generation stopped', {
8020
- description: 'Code generation was cancelled. You can start a new generation.',
8366
+ showToast('info', $t('creator.codegen.generationStopped'), {
8367
+ description: $t('creator.codegen.codeGenerationWasCancelledYou'),
8021
8368
  duration: 3000
8022
8369
  });
8023
8370
  }
@@ -8032,8 +8379,8 @@
8032
8379
  async function processImageFile(file: File): Promise<string | null> {
8033
8380
  // Check file type
8034
8381
  if (!file.type.startsWith('image/')) {
8035
- showToast('error', 'Invalid file type', {
8036
- description: 'Please select an image file (PNG, JPG, GIF, WebP).',
8382
+ showToast('error', $t('creator.general.invalidFileType'), {
8383
+ description: $t('creator.general.pleaseSelectAnImageFile'),
8037
8384
  duration: 3000
8038
8385
  });
8039
8386
  return null;
@@ -8042,8 +8389,8 @@
8042
8389
  // Check file size
8043
8390
  const sizeMB = file.size / (1024 * 1024);
8044
8391
  if (sizeMB > MAX_IMAGE_SIZE_MB) {
8045
- showToast('error', 'Image too large', {
8046
- description: `Maximum image size is ${MAX_IMAGE_SIZE_MB}MB. Your image is ${sizeMB.toFixed(1)}MB.`,
8392
+ showToast('error', $t('creator.general.imageTooLarge'), {
8393
+ description: $t('creator.general.maximumImageSizeIsMb', { maxMb: MAX_IMAGE_SIZE_MB, sizeMb: sizeMB.toFixed(1) }),
8047
8394
  duration: 3000
8048
8395
  });
8049
8396
  return null;
@@ -8051,8 +8398,8 @@
8051
8398
 
8052
8399
  // Check max images limit
8053
8400
  if (promptImages.length >= MAX_PROMPT_IMAGES) {
8054
- showToast('error', 'Too many images', {
8055
- description: `Maximum ${MAX_PROMPT_IMAGES} images allowed. Remove an image first.`,
8401
+ showToast('error', $t('creator.general.tooManyImages'), {
8402
+ description: $t('creator.general.maximumImagesAllowedRemoveAn', { max: MAX_PROMPT_IMAGES }),
8056
8403
  duration: 3000
8057
8404
  });
8058
8405
  return null;
@@ -8065,8 +8412,8 @@
8065
8412
  return base64;
8066
8413
  } catch (error) {
8067
8414
  console.error('[WidgetCreator] Error processing image:', error);
8068
- showToast('error', 'Failed to process image', {
8069
- description: 'Could not read the image file.',
8415
+ showToast('error', $t('creator.general.failedToProcessImage'), {
8416
+ description: $t('creator.general.couldNotReadTheImage'),
8070
8417
  duration: 3000
8071
8418
  });
8072
8419
  return null;
@@ -8111,8 +8458,8 @@
8111
8458
  if (base64) {
8112
8459
  promptImages = [...promptImages, base64];
8113
8460
  savePromptImagesToSession();
8114
- showToast('success', 'Image pasted', {
8115
- description: 'Image added to your prompt.',
8461
+ showToast('success', $t('creator.general.imagePasted'), {
8462
+ description: $t('creator.codegen.imageAddedToYourPrompt'),
8116
8463
  duration: 2000
8117
8464
  });
8118
8465
  }
@@ -8326,7 +8673,8 @@
8326
8673
  }
8327
8674
  // console.log('[Chat] Chat ready for widget', ownerWidgetId?.substring(0, 8), 'methods exposed');
8328
8675
 
8329
- if (typeof window !== 'undefined') {
8676
+ // A console helper of Widgetic's own pages; a partner's page gets no globals from the creator.
8677
+ if (typeof window !== 'undefined' && !partnerMode) {
8330
8678
  (window as Window & { __widgeticAttachReferenceImage?: (url?: string) => Promise<boolean> }).__widgeticAttachReferenceImage =
8331
8679
  attachReferenceImageFromUrl;
8332
8680
  }
@@ -8351,7 +8699,7 @@
8351
8699
  // console.log('[WidgetCreator] Images restored from durable draft:', promptImages.length);
8352
8700
  return;
8353
8701
  }
8354
- const stored = localStorage.getItem(PROMPT_IMAGES_STORAGE_PREFIX + selectedWidgetId);
8702
+ const stored = creatorStorage.getItem(PROMPT_IMAGES_STORAGE_PREFIX + selectedWidgetId);
8355
8703
  if (stored) {
8356
8704
  const parsed = JSON.parse(stored);
8357
8705
  if (Array.isArray(parsed) && parsed.length > 0) {
@@ -8359,7 +8707,7 @@
8359
8707
  // console.log('[WidgetCreator] Images restored from per-widget localStorage:', promptImages.length);
8360
8708
  }
8361
8709
  }
8362
- localStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
8710
+ creatorStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
8363
8711
  } catch (error) {
8364
8712
  console.warn('[WidgetCreator] Could not restore images from durable storage:', error);
8365
8713
  }
@@ -8563,19 +8911,19 @@
8563
8911
  if (!widgetId || isDraftConvertId(widgetId)) return;
8564
8912
  if (codegenCaptureBlocked() || generatingWidgetIds[widgetId]) {
8565
8913
  if (interactive) {
8566
- showToast('info', 'Preview image waits until generation finishes', { duration: 3000 });
8914
+ showToast('info', $t('creator.preview.imageWaitsForGeneration'), { duration: 3000 });
8567
8915
  }
8568
8916
  return;
8569
8917
  }
8570
8918
  if (interactive) {
8571
- showToast('info', 'Saving preview image...', { duration: 2500 });
8919
+ showToast('info', $t('creator.preview.savingImage'), { duration: 2500 });
8572
8920
  }
8573
8921
  try {
8574
8922
  const screenshot = await handleChatScreenshot(widgetId, null, false);
8575
8923
  if (!screenshot) {
8576
8924
  if (interactive) {
8577
- showToast('error', 'Could not save the preview image', {
8578
- description: 'The preview did not return an image. Refresh it, then try again.',
8925
+ showToast('error', $t('creator.preview.couldNotSaveImage'), {
8926
+ description: $t('creator.preview.imageNotReturned'),
8579
8927
  duration: 5000,
8580
8928
  });
8581
8929
  }
@@ -8584,14 +8932,14 @@
8584
8932
  canvasRef?.updateWidgetImage(widgetId, screenshot);
8585
8933
  await persistWidgetListThumbnail(widgetId, screenshot);
8586
8934
  if (interactive) {
8587
- showToast('success', 'Preview image saved', { duration: 2000 });
8935
+ showToast('success', $t('creator.preview.imageSaved'), { duration: 2000 });
8588
8936
  } else {
8589
8937
  console.log('[Chat→Screenshot] List thumbnail saved', widgetId.substring(0, 8));
8590
8938
  }
8591
8939
  } catch (error) {
8592
8940
  console.warn('[Chat→Screenshot] List thumbnail failed', widgetId.substring(0, 8), error);
8593
8941
  if (interactive) {
8594
- showToast('error', 'Could not save the preview image', { duration: 4000 });
8942
+ showToast('error', $t('creator.preview.couldNotSaveImage'), { duration: 4000 });
8595
8943
  }
8596
8944
  }
8597
8945
  }
@@ -8742,13 +9090,13 @@
8742
9090
  if (!iframe?.contentWindow) {
8743
9091
  // console.log('[handleRefreshScreenshot] Preview iframe not ready — skipping capture');
8744
9092
  if (!quiet) {
8745
- showToast('error', 'No valid preview available', { description: 'Generate code first to capture a screenshot.', duration: 5000 });
9093
+ showToast('error', $t('creator.preview.noValidPreviewAvailable'), { description: $t('creator.codegen.generateCodeFirstToCapture'), duration: 5000 });
8746
9094
  }
8747
9095
  return;
8748
9096
  }
8749
9097
 
8750
9098
  if (!quiet) {
8751
- showToast('info', 'Capturing widget screenshot...', { duration: 3000 });
9099
+ showToast('info', $t('creator.widget.capturingWidgetScreenshot'), { duration: 3000 });
8752
9100
  }
8753
9101
 
8754
9102
  const result = await new Promise<{ data: string | null; error: string | null }>((resolve) => {
@@ -8759,6 +9107,8 @@
8759
9107
 
8760
9108
  function handler(event: MessageEvent) {
8761
9109
  if (event.data?.type !== 'widgetic:screenshot') return;
9110
+ // Only the preview that was asked: in a partner's page another frame could answer in its place.
9111
+ if (event.source !== iframe.contentWindow) return;
8762
9112
  clearTimeout(timeout);
8763
9113
  window.removeEventListener('message', handler);
8764
9114
  resolve({
@@ -8784,7 +9134,7 @@
8784
9134
  }, 500);
8785
9135
  void persistWidgetListThumbnail(widgetId, result.data);
8786
9136
  if (!quiet) {
8787
- showToast('success', 'Widget preview updated on canvas', { duration: 2000 });
9137
+ showToast('success', $t('creator.canvas.widgetPreviewUpdatedOnCanvas'), { duration: 2000 });
8788
9138
  } else {
8789
9139
  // console.log('[handleRefreshScreenshot] Canvas shape preview synced (quiet):', widgetId.substring(0, 8));
8790
9140
  }
@@ -8792,13 +9142,13 @@
8792
9142
  const reason = result.error || 'no image data';
8793
9143
  console.warn('[handleRefreshScreenshot] Capture failed:', reason);
8794
9144
  if (!quiet) {
8795
- showToast('error', 'Screenshot capture failed', {
9145
+ showToast('error', $t('creator.general.screenshotCaptureFailed'), {
8796
9146
  description:
8797
9147
  reason === 'html2canvas not loaded'
8798
- ? 'Preview is missing the capture library. Rebuild the widget preview, then try again.'
9148
+ ? $t('creator.codegen.previewIsMissingTheCapture')
8799
9149
  : reason === 'timeout'
8800
- ? 'The widget did not respond in time. Refresh the preview, then try again.'
8801
- : `Capture error: ${reason}. Refresh the preview and retry.`,
9150
+ ? $t('creator.preview.theWidgetDidNotRespond')
9151
+ : $t('creator.preview.captureErrorRefreshThePreview', { reason }),
8802
9152
  duration: 6000,
8803
9153
  });
8804
9154
  }
@@ -8806,7 +9156,7 @@
8806
9156
  } catch (err) {
8807
9157
  console.error('[handleRefreshScreenshot] Screenshot error:', err);
8808
9158
  if (!quiet) {
8809
- showToast('error', 'Screenshot capture failed', { duration: 3000 });
9159
+ showToast('error', $t('creator.general.screenshotCaptureFailed'), { duration: 3000 });
8810
9160
  }
8811
9161
  } finally {
8812
9162
  screenshotCaptureInFlight.delete(widgetId);
@@ -8934,9 +9284,9 @@ Requirements:
8934
9284
  const promptSource = options.prompt || panelPrompt;
8935
9285
  const trimmedPrompt = promptSource.trim();
8936
9286
  if (trimmedPrompt.length < 10) {
8937
- showToast('error', 'Prompt too short', {
9287
+ showToast('error', $t('creator.codegen.promptTooShort'), {
8938
9288
  description:
8939
- 'Please provide a prompt with at least 10 characters describing the widget you want to generate.',
9289
+ $t('creator.codegen.pleaseProvideAPromptWith'),
8940
9290
  duration: 5000
8941
9291
  });
8942
9292
  return;
@@ -8969,8 +9319,8 @@ Requirements:
8969
9319
  setCrossTabGenerating(false, codegenTargetWidgetId);
8970
9320
  patchCodegenUiState(codegenTargetWidgetId, { generateCodeStatus: 'Mock code generation complete!' });
8971
9321
  if (codegenTargetWidgetId === focusedPanelWidgetId) hasChangesToSave = true;
8972
- showToast('success', 'Mock Code Generated', {
8973
- description: 'This is a simulation. No actual code was generated.',
9322
+ showToast('success', $t('creator.codegen.mockCodeGenerated'), {
9323
+ description: $t('creator.codegen.thisIsASimulationNo'),
8974
9324
  duration: 3000
8975
9325
  });
8976
9326
  }, 2000);
@@ -9044,8 +9394,8 @@ Requirements:
9044
9394
  const options = currentGenerationOptions();
9045
9395
  generationOptionsMemory = { ...generationOptionsMemory, [widgetId]: options };
9046
9396
  try {
9047
- localStorage.setItem(languageStorageKey(widgetId), options.language);
9048
- localStorage.setItem(generationOptionsStorageKey(widgetId), JSON.stringify({
9397
+ creatorStorage.setItem(languageStorageKey(widgetId), options.language);
9398
+ creatorStorage.setItem(generationOptionsStorageKey(widgetId), JSON.stringify({
9049
9399
  language: options.language,
9050
9400
  librariesEnabled: options.librariesEnabled,
9051
9401
  libraries: options.libraries,
@@ -9067,7 +9417,7 @@ Requirements:
9067
9417
 
9068
9418
  function readGeneratedLanguage(widgetId: string): 'svelte' | 'react' | null {
9069
9419
  try {
9070
- const value = localStorage.getItem(generatedLanguageStorageKey(widgetId));
9420
+ const value = creatorStorage.getItem(generatedLanguageStorageKey(widgetId));
9071
9421
  return value === 'svelte' || value === 'react' ? value : null;
9072
9422
  } catch (error) {
9073
9423
  console.warn('[WidgetCreator] Could not read generated language', error);
@@ -9077,7 +9427,7 @@ Requirements:
9077
9427
 
9078
9428
  function rememberGeneratedLanguage(widgetId: string, language: 'svelte' | 'react'): void {
9079
9429
  try {
9080
- localStorage.setItem(generatedLanguageStorageKey(widgetId), language);
9430
+ creatorStorage.setItem(generatedLanguageStorageKey(widgetId), language);
9081
9431
  } catch (error) {
9082
9432
  console.warn('[WidgetCreator] Could not store generated language', error);
9083
9433
  }
@@ -9107,7 +9457,7 @@ Requirements:
9107
9457
  let stored: Partial<RememberedGenerationOptions> | null = null;
9108
9458
  if (!inMemory) {
9109
9459
  try {
9110
- const raw = localStorage.getItem(generationOptionsStorageKey(widgetId));
9460
+ const raw = creatorStorage.getItem(generationOptionsStorageKey(widgetId));
9111
9461
  stored = raw ? JSON.parse(raw) : null;
9112
9462
  } catch (error) {
9113
9463
  console.warn('[WidgetCreator] Could not read generation options', error);
@@ -9184,7 +9534,8 @@ Requirements:
9184
9534
  generatingWidgetIds = { ...generatingWidgetIds, [generationWidgetId]: true };
9185
9535
  noteCodegenActive(true);
9186
9536
  screenshotGenerationEpoch += 1;
9187
- document.querySelectorAll('iframe').forEach((frame) => {
9537
+ // The creator's own frames: in a partner's page `document` holds the page's frames, and not these.
9538
+ (getCreatorShadowRoot(creatorRootEl) ?? document).querySelectorAll('iframe').forEach((frame) => {
9188
9539
  try {
9189
9540
  frame.contentWindow?.postMessage({ type: 'widgetic:abort-screenshot' }, '*');
9190
9541
  } catch (err) {
@@ -9251,13 +9602,13 @@ Requirements:
9251
9602
  }
9252
9603
  } catch (repoError) {
9253
9604
  if (repoError instanceof ResponseError && repoError.response?.status === 401) {
9254
- const sessionError = 'Session expired. Sign in again, then retry.';
9605
+ const sessionError = signInAgainText($t('creator.session.sessionExpiredSignInAgain'));
9255
9606
  patchCodegenUiState(generationWidgetId, {
9256
9607
  generateCodeStatus: '❌ Session expired.',
9257
9608
  lastGenerationFailed: true,
9258
9609
  lastGenerationError: sessionError,
9259
9610
  });
9260
- showToast('error', 'Session expired', {
9611
+ showToast('error', $t('creator.session.sessionExpired'), {
9261
9612
  description: sessionError,
9262
9613
  duration: 5000
9263
9614
  });
@@ -9275,8 +9626,8 @@ Requirements:
9275
9626
  lastGenerationFailed: true,
9276
9627
  lastGenerationError: missingRepoError,
9277
9628
  });
9278
- showToast('error', 'Missing repository', {
9279
- description: missingRepoError,
9629
+ showToast('error', $t('creator.codegen.missingRepository'), {
9630
+ description: errorLabel(missingRepoError, $t),
9280
9631
  duration: 5000
9281
9632
  });
9282
9633
  pushCodegenFailureToChat(generationWidgetId, missingRepoError);
@@ -9377,15 +9728,15 @@ Requirements:
9377
9728
  // });
9378
9729
  coderModelForRequest = visionFallback;
9379
9730
  const visionModel = availableModels.find((m) => m.id === visionFallback);
9380
- showToast('info', `Coder: ${visionModel?.name ?? visionFallback} (vision)`, {
9381
- description: 'Cu imagini atașate folosim automat un model vision — același ca pe server.',
9731
+ showToast('info', $t('creator.codegen.coderVision', { model: visionModel?.name ?? visionFallback }), {
9732
+ description: $t('creator.codegen.visionModelNote'),
9382
9733
  duration: 8000
9383
9734
  });
9384
9735
  }
9385
9736
  } else if (promptImpliesVisionReference(prompt) && !options.forkUserMessage) {
9386
- showToast('warning', 'Generare fără imagine', {
9737
+ showToast('warning', $t('creator.codegen.noImageTitle'), {
9387
9738
  description:
9388
- 'Request-ul merge fără vision (DeepSeek etc.). Atașează PNG/JPEG în chat înainte de Send.',
9739
+ $t('creator.codegen.noVisionNote'),
9389
9740
  duration: 8000,
9390
9741
  });
9391
9742
  }
@@ -9476,7 +9827,7 @@ Requirements:
9476
9827
 
9477
9828
  showToast(
9478
9829
  gatedAction === 'answer' ? 'info' : 'warning',
9479
- gatedAction === 'answer' ? 'Answered without generating' : 'No generation started',
9830
+ gatedAction === 'answer' ? $t('creator.codegen.answeredWithoutGenerating') : $t('creator.codegen.noGenerationStarted'),
9480
9831
  {
9481
9832
  description: gatedReply.slice(0, 140),
9482
9833
  duration: 8000,
@@ -9499,8 +9850,8 @@ Requirements:
9499
9850
  lastGenerationFailed: true,
9500
9851
  lastGenerationError: 'Authentication expired. Please login again to continue.',
9501
9852
  });
9502
- showToast('error', 'Authentication expired', {
9503
- description: 'Please login again to continue.',
9853
+ showToast('error', $t('creator.session.authenticationExpired'), {
9854
+ description: $t('creator.session.pleaseLoginAgainToContinue'),
9504
9855
  duration: 5000
9505
9856
  });
9506
9857
  return;
@@ -9515,7 +9866,7 @@ Requirements:
9515
9866
  lastGenerationFailed: true,
9516
9867
  lastGenerationError: normalizedMessage,
9517
9868
  });
9518
- showToast('error', 'Code generation failed', {
9869
+ showToast('error', $t('creator.status.failed'), {
9519
9870
  description: normalizedMessage,
9520
9871
  duration: 5000
9521
9872
  });
@@ -9539,8 +9890,8 @@ Requirements:
9539
9890
  lastGenerationFailed: true,
9540
9891
  lastGenerationError: 'Cannot track code generation progress. No operation ID received from server.',
9541
9892
  });
9542
- showToast('error', 'Missing operation ID', {
9543
- description: 'Cannot track code generation progress.',
9893
+ showToast('error', $t('creator.general.missingOperationId'), {
9894
+ description: $t('creator.codegen.cannotTrackCodeGenerationProgress'),
9544
9895
  duration: 5000
9545
9896
  });
9546
9897
  console.error('Widget Creator: Code generation started, but no operation ID was returned.');
@@ -9590,10 +9941,10 @@ Requirements:
9590
9941
  const toastDescription = isServiceError
9591
9942
  ? errorMsg
9592
9943
  : isSvelteSyntaxError
9593
- ? 'AI generated invalid Svelte syntax. Click "Generate Code" to retry with improved instructions.'
9944
+ ? $t('creator.codegen.aiGeneratedInvalidSvelteSyntax')
9594
9945
  : errorMsg;
9595
9946
 
9596
- showToast('error', isServiceError ? 'Service temporarily unavailable' : 'Code generation failed', {
9947
+ showToast('error', isServiceError ? $t('creator.general.serviceTemporarilyUnavailable') : $t('creator.status.failed'), {
9597
9948
  description: toastDescription,
9598
9949
  duration: isServiceError ? 10000 : 8000
9599
9950
  });
@@ -9821,18 +10172,18 @@ Requirements:
9821
10172
  `Code saved${completedCommitSha ? ` (Commit: ${completedCommitSha.substring(0, 7)})` : ''}, but preview build failed:\n${completedPreviewBuildErr}\n\nRebuilding preview…`,
9822
10173
  true
9823
10174
  );
9824
- showToast('warning', 'Code saved — rebuilding preview', {
10175
+ showToast('warning', $t('creator.codegen.codeSavedRebuildingPreview'), {
9825
10176
  description: completedPreviewBuildErr.length > 120 ? `${completedPreviewBuildErr.slice(0, 120)}…` : completedPreviewBuildErr,
9826
10177
  duration: 8000
9827
10178
  });
9828
10179
  } else {
9829
10180
  showToast(
9830
10181
  'success',
9831
- isFocusedPanel ? 'Code generation completed' : `"${completedWidgetName}" generation completed`,
10182
+ isFocusedPanel ? $t('creator.codegen.codeGenerationCompleted') : $t('creator.codegen.generationCompleted', { name: completedWidgetName }),
9832
10183
  {
9833
10184
  description: isFocusedPanel
9834
- ? 'Code saved. Preview is loading.'
9835
- : 'Switch to that panel to chat, or keep working here.',
10185
+ ? $t('creator.codegen.codeSavedPreviewIsLoading')
10186
+ : $t('creator.general.switchToThatPanelTo'),
9836
10187
  duration: 5000
9837
10188
  }
9838
10189
  );
@@ -9962,8 +10313,8 @@ Requirements:
9962
10313
  patchCodegenUiState(generationWidgetId, {
9963
10314
  generateCodeStatus: '⚠️ A code generation is already running. Please wait for it to finish.',
9964
10315
  });
9965
- showToast('warning', 'Generation already in progress', {
9966
- description: 'Another code generation is already running. Wait for it to finish or cancel it first.',
10316
+ showToast('warning', $t('creator.codegen.generationAlreadyInProgress'), {
10317
+ description: $t('creator.codegen.anotherCodeGenerationIsAlready'),
9967
10318
  duration: 5000
9968
10319
  });
9969
10320
  return;
@@ -9978,12 +10329,12 @@ Requirements:
9978
10329
  lastGenerationFailed: true,
9979
10330
  lastGenerationError: error.message,
9980
10331
  });
9981
- showToast('warning', 'This app needs a refresh', {
10332
+ showToast('warning', $t('creator.common.thisAppNeedsARefresh'), {
9982
10333
  description: error.message,
9983
10334
  duration: 12000,
9984
10335
  action: {
9985
- label: 'Reload',
9986
- onClick: () => window.location.reload()
10336
+ label: $t('creator.common.reload'),
10337
+ onClick: () => reloadThePage()
9987
10338
  }
9988
10339
  });
9989
10340
  return;
@@ -9991,14 +10342,28 @@ Requirements:
9991
10342
 
9992
10343
  // Handle rate limiting (429) — too many API requests in the time window
9993
10344
  if (httpStatus === 429) {
10345
+ // A visitor who used up the budget the partner gave them is told that, and not that the API is busy: a wait
10346
+ // of half a minute would not help them. (The page is told by the limit middleware.)
10347
+ if (partnerMode && (await responseIsALimit(error.response))) {
10348
+ console.warn('Widget Creator: the visitor reached their budget during code generation');
10349
+ const limitMessage = await deriveApiErrorMessage(error, 'Usage limit exceeded');
10350
+ patchCodegenUiState(generationWidgetId, {
10351
+ generateCodeStatus: '⚠️ Limit reached for now. Please try again later.',
10352
+ lastGenerationFailed: true,
10353
+ lastGenerationError: limitMessage,
10354
+ });
10355
+ showToast('warning', $t('creator.general.limitReached'), { description: limitMessage, duration: 8000 });
10356
+ pushCodegenFailureToChat(generationWidgetId, limitMessage);
10357
+ return;
10358
+ }
9994
10359
  console.warn('Widget Creator: Rate limited (429) during code generation');
9995
10360
  patchCodegenUiState(generationWidgetId, {
9996
10361
  generateCodeStatus: '⚠️ Rate limited — too many requests. Wait ~30s and retry.',
9997
10362
  lastGenerationFailed: true,
9998
10363
  lastGenerationError: 'Too many requests, please try again later.',
9999
10364
  });
10000
- showToast('warning', 'Rate limited', {
10001
- description: 'The API rate limit was reached. Please wait about 30 seconds before retrying.',
10365
+ showToast('warning', $t('creator.general.rateLimited'), {
10366
+ description: $t('creator.general.theApiRateLimitWas'),
10002
10367
  duration: 8000
10003
10368
  });
10004
10369
  return;
@@ -10022,7 +10387,7 @@ Requirements:
10022
10387
  lastGenerationError: message,
10023
10388
  });
10024
10389
  clearActiveOperationId(); // Clear persisted operationId on error
10025
- showToast('error', 'Code generation error', { description: message, duration: 6000 });
10390
+ showToast('error', $t('creator.codegen.codeGenerationError'), { description: message, duration: 6000 });
10026
10391
  pushCodegenFailureToChat(generationWidgetId, message);
10027
10392
  } finally {
10028
10393
  noteCodegenActive(false);
@@ -10274,7 +10639,7 @@ Requirements:
10274
10639
  || lastCommitId);
10275
10640
 
10276
10641
  if (!capturedWidgetId || !capturedCanvasId || !capturedRepositoryId) {
10277
- showToast('error', 'Cannot publish', { description: 'Widget, canvas, and repository are required.' });
10642
+ showToast('error', $t('creator.publish.cannotPublish'), { description: $t('creator.canvas.widgetCanvasAndRepositoryAre') });
10278
10643
  return;
10279
10644
  }
10280
10645
 
@@ -10287,7 +10652,7 @@ Requirements:
10287
10652
  publishingWidgetId = capturedWidgetId;
10288
10653
  setCrossTabPublishing(true, capturedWidgetId);
10289
10654
 
10290
- publishWidgetStatus = 'Fetching widget component...';
10655
+ publishWidgetStatus = $t('creator.widget.fetchingWidgetComponent');
10291
10656
 
10292
10657
  if (!componentsClient || !agentClient) {
10293
10658
  throw new Error('API clients are not configured');
@@ -10311,7 +10676,7 @@ Requirements:
10311
10676
  // If no component exists for this widget in the canvas, create one now
10312
10677
  // (in widget-creator, saving to git doesn't auto-create a component record)
10313
10678
  if (!matchedComponent?.id) {
10314
- publishWidgetStatus = 'Creating widget component...';
10679
+ publishWidgetStatus = $t('creator.widget.creatingWidgetComponent');
10315
10680
  const widgetName = getWidgetById(capturedWidgetId)?.name || 'Widget';
10316
10681
  // console.log('[Publish] No component found — creating one for widget:', capturedWidgetId, 'name:', widgetName);
10317
10682
 
@@ -10334,7 +10699,7 @@ Requirements:
10334
10699
  const componentId = matchedComponent.id;
10335
10700
  // console.log('[Publish] Publishing component:', { componentId, capturedWidgetId, capturedCanvasId });
10336
10701
 
10337
- publishWidgetStatus = 'Publishing via Widget Builder...';
10702
+ publishWidgetStatus = $t('creator.publish.publishingViaWidgetBuilder');
10338
10703
 
10339
10704
  const publishData = await agentClient.agentWidgetBuilderPublishWidgetIdPost({
10340
10705
  widgetId: capturedWidgetId,
@@ -10376,13 +10741,13 @@ Requirements:
10376
10741
  applyPublishSuccessToWidgetState(capturedWidgetId, version, artifactUrl, commitSha, commitTitle);
10377
10742
 
10378
10743
  if (!publishOpts.silent) {
10379
- showToast('success', 'Widget published!', {
10380
- description: `Version ${version} is now live.`,
10744
+ showToast('success', $t('creator.publish.widgetPublished'), {
10745
+ description: $t('creator.version.versionIsNowLive', { version }),
10381
10746
  duration: 5000
10382
10747
  });
10383
10748
  } else {
10384
- showToast('success', `Live: v${version}`, {
10385
- description: publishOpts.fromCodegen ? 'Published automatically after code generation.' : `Version ${version} is now live.`,
10749
+ showToast('success', $t('creator.general.liveV', { version }), {
10750
+ description: publishOpts.fromCodegen ? $t('creator.publish.publishedAutomaticallyAfterCodeGeneration') : $t('creator.version.versionIsNowLive', { version }),
10386
10751
  duration: 4000
10387
10752
  });
10388
10753
  }
@@ -10402,14 +10767,14 @@ Requirements:
10402
10767
  isPublishing = false;
10403
10768
  publishingWidgetId = null;
10404
10769
  setCrossTabPublishing(false, capturedWidgetId);
10405
- const publishErrorText = normalizeErrorMessage(err) || 'An unexpected error occurred. Please try again.';
10770
+ const publishErrorText = normalizeErrorMessage(err) || $t('creator.general.anUnexpectedErrorOccurredPlease');
10406
10771
  if (isPlanLimitMessage(publishErrorText) && capturedWidgetId) {
10407
10772
  publishPlanMessageByWidgetId = {
10408
10773
  ...publishPlanMessageByWidgetId,
10409
10774
  [capturedWidgetId]: publishErrorText,
10410
10775
  };
10411
10776
  } else {
10412
- showToast('error', 'Publish failed', {
10777
+ showToast('error', $t('creator.publish.publishFailed'), {
10413
10778
  description: publishErrorText,
10414
10779
  duration: 8000
10415
10780
  });
@@ -10421,7 +10786,7 @@ Requirements:
10421
10786
 
10422
10787
  // ===================== Auth Automation =====================
10423
10788
  import { userSession, setSession, clearSession, restoreSession } from './stores/userSession.js';
10424
- import { get } from 'svelte/store';
10789
+ import { get, writable } from 'svelte/store';
10425
10790
 
10426
10791
 
10427
10792
  // Token expiration check interval
@@ -10441,7 +10806,8 @@ Requirements:
10441
10806
  agentHarnessOutput,
10442
10807
  dynamicWorkerPreviewStatus,
10443
10808
  setAuthToken as setWsAuthToken,
10444
- setWebsocketApiUrl
10809
+ setWebsocketApiUrl,
10810
+ resetRealtimeState
10445
10811
  } from './stores/websocketStore.js';
10446
10812
 
10447
10813
  let lastHarnessChatLine = '';
@@ -10459,7 +10825,14 @@ Requirements:
10459
10825
  console.warn('[CreatorApp] No PUBLIC_GOOGLE_FONTS_API_KEY / VITE_GOOGLE_FONTS_API_KEY — FontIC uses fallback catalog');
10460
10826
  }
10461
10827
  setWebsocketApiUrl(apiRoot ?? null);
10462
- if (embedded) {
10828
+ if (partnerMode) {
10829
+ // Take the page's token at once, and keep taking it: the page renews it before it expires, and the
10830
+ // clients are bound to whichever token this last adopted.
10831
+ void adoptHostToken('initial');
10832
+ hostTokenPump = setInterval(() => {
10833
+ void adoptHostToken('initial');
10834
+ }, HOST_TOKEN_PUMP_MS);
10835
+ } else if (embedded) {
10463
10836
  syncSessionFromSiteAuth();
10464
10837
  } else {
10465
10838
  restoreSession();
@@ -10498,37 +10871,37 @@ Requirements:
10498
10871
  // Prompt images are restored only after a widget is selected. Restoring the
10499
10872
  // legacy global key here can rehydrate already-sent/deleted attachments.
10500
10873
  try {
10501
- localStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
10874
+ creatorStorage.removeItem(PROMPT_IMAGES_STORAGE_KEY);
10502
10875
  } catch {
10503
10876
  /* ignore */
10504
10877
  }
10505
10878
 
10506
- // Cross-tab operation sync: listen for localStorage changes from other tabs
10507
- window.addEventListener('storage', handleCrossTabStorageEvent);
10508
- window.addEventListener('widgetic:session-extended', handleSiteSessionExtended);
10879
+ // Cross-tab operation sync: listen for localStorage changes from other tabs. (Partner mode keeps its state in
10880
+ // memory, so there are no other tabs to hear from, and nothing on the partner's window to listen to.)
10881
+ if (mayListenToSiteEvents()) {
10882
+ window.addEventListener('storage', handleCrossTabStorageEvent);
10883
+ window.addEventListener('widgetic:session-extended', handleSiteSessionExtended);
10509
10884
 
10510
- // Clean up cross-tab flags when tab is closed/refreshed. The handler lives at
10511
- // component scope so `onDestroy` can remove the same reference.
10512
- window.addEventListener('beforeunload', handleBeforeUnload);
10513
- // Keep a component-scope binding so onDestroy can remove the listener —
10514
- // the arrow itself is scoped to this onMount callback.
10515
- handleBeforeUnloadRef = handleBeforeUnload;
10885
+ // Clean up cross-tab flags when tab is closed/refreshed. The handler lives at
10886
+ // component scope so `onDestroy` can remove the same reference.
10887
+ window.addEventListener('beforeunload', handleBeforeUnload);
10888
+ // Keep a component-scope binding so onDestroy can remove the listener —
10889
+ // the arrow itself is scoped to this onMount callback.
10890
+ handleBeforeUnloadRef = handleBeforeUnload;
10891
+ }
10516
10892
 
10517
10893
  // Read canvas id from the route. The route path (`/canvas/<canvasId>`) is the
10518
10894
  // AUTHORITATIVE canvas (site links, refresh, deep-links); localStorage is only a
10519
10895
  // fallback and must never win over it.
10520
10896
  if (!routeCanvasId) {
10521
10897
  try {
10522
- const sub = pageStore.subscribe(($page) => {
10523
- // `readCanvasIdFromAddressBar()` also covers the legacy query string, so an
10524
- // old bookmark `/canvas?canvas_id=…` still resolves to its canvas.
10525
- const nextCanvasId = readCanvasIdFromAddressBar();
10526
- // Never clobber an already-known canvas with null.
10527
- if (nextCanvasId) routeCanvasId = nextCanvasId;
10528
- });
10529
- setTimeout(() => {
10530
- if (sub && typeof sub === 'function') sub();
10531
- }, 0);
10898
+ // `readCanvasIdFromAddressBar()` also covers the legacy query string, so an
10899
+ // old bookmark `/canvas?canvas_id=…` still resolves to its canvas. (This used to be read through
10900
+ // SvelteKit's page store, whose first value is all that was ever used; the package no longer
10901
+ // depends on SvelteKit, so it works outside the Widgetic site too.)
10902
+ const nextCanvasId = readCanvasIdFromAddressBar();
10903
+ // Never clobber an already-known canvas with null.
10904
+ if (nextCanvasId) routeCanvasId = nextCanvasId;
10532
10905
  } catch (e) {
10533
10906
  console.error('Error reading canvas id from route:', e);
10534
10907
  }
@@ -10551,6 +10924,8 @@ Requirements:
10551
10924
  // The proxy injects a script that sends postMessage when SvelteKit finishes
10552
10925
  // attaching event handlers (buttons become interactive at this point).
10553
10926
  const handleHydrationSignal = (event: MessageEvent) => {
10927
+ // In a partner's page `window` also hears the page's other frames; only the creator's previews count.
10928
+ if (!messageIsFromCreatorFrame(event, creatorRootEl)) return;
10554
10929
  if (event.data?.type === 'sveltekit-hydration-complete') {
10555
10930
  // console.log('Received SvelteKit hydration complete signal from iframe');
10556
10931
  previewHydrating = false;
@@ -10565,6 +10940,7 @@ Requirements:
10565
10940
  // Listen for runtime error signals from the preview iframe.
10566
10941
  // NOTE: WidgetDetails owns this. Do not also flip orphan CreatorApp flags here.
10567
10942
  const handleIframeRuntimeError = (event: MessageEvent) => {
10943
+ if (!messageIsFromCreatorFrame(event, creatorRootEl)) return;
10568
10944
  if (event.data?.type === 'sveltekit-runtime-error') {
10569
10945
  console.warn(
10570
10946
  '[CreatorApp] Preview runtime signal (handled by WidgetDetails):',
@@ -10579,6 +10955,7 @@ Requirements:
10579
10955
  // an HTML page with a postMessage instead of JSON. We auto-fetch a fresh token
10580
10956
  // and reload the iframe seamlessly.
10581
10957
  const handleTokenExpired = async (event: MessageEvent) => {
10958
+ if (!messageIsFromCreatorFrame(event, creatorRootEl)) return;
10582
10959
  if (event.data?.type === 'preview-token-expired') {
10583
10960
  console.warn('Preview token expired — delegating refresh to WidgetDetails');
10584
10961
  widgetDetails?.refreshPreview();
@@ -10629,10 +11006,23 @@ Requirements:
10629
11006
  }
10630
11007
  if (isPublishing) setCrossTabPublishing(false);
10631
11008
  }
11009
+ // Partner mode ends with the creator: the token pump stops, and nothing the creator holds about this visitor
11010
+ // outlives it (the page may start the next visitor in the same tab). Last, because the cleanup above still
11011
+ // writes through the same storage.
11012
+ if (hostTokenPump) {
11013
+ clearInterval(hostTokenPump);
11014
+ hostTokenPump = null;
11015
+ }
11016
+ if (partnerMode) {
11017
+ clearSession();
11018
+ setFileBrowserUploadConfig(null);
11019
+ resetRealtimeState();
11020
+ leavePartnerMode();
11021
+ }
10632
11022
  });
10633
11023
 
10634
11024
  onMount(() => {
10635
- if (typeof window === 'undefined') return;
11025
+ if (typeof window === 'undefined' || !mayUseAddressBar()) return;
10636
11026
  if (new URLSearchParams(window.location.search).get('attachStairsRef') === '1') {
10637
11027
  wantStairsReferenceAttach = true;
10638
11028
  const url = new URL(window.location.href);
@@ -10645,18 +11035,22 @@ Requirements:
10645
11035
  // Register click-outside listener for canvas dropdown
10646
11036
  onMount(() => {
10647
11037
  window.addEventListener('click', handleCanvasDropdownOutsideClick);
10648
- window.addEventListener(HOST_WIDGET_RENAMED_EVENT, handleHostWidgetRenamedEvent);
10649
- window.addEventListener(HOST_REQUEST_PUBLISH_EVENT, handleHostRequestPublishEvent);
10650
- window.addEventListener(HOST_TOGGLE_DEBUG_EVENT, handleHostToggleDebugEvent);
10651
- window.addEventListener(HOST_TOGGLE_WIREFRAME_EVENT, handleHostToggleWireframeEvent);
10652
- window.addEventListener(HOST_TOGGLE_ADVANCED_EVENT, handleHostToggleAdvancedEvent);
10653
- window.addEventListener(HOST_OPEN_WIDGET_DETAILS_EVENT, handleHostOpenWidgetDetailsEvent);
10654
- window.addEventListener(HOST_DUPLICATE_WIDGET_EVENT, handleHostDuplicateWidgetEvent);
10655
- window.addEventListener(HOST_DELETE_WIDGET_EVENT, handleHostDeleteWidgetEvent);
10656
- window.addEventListener(HOST_SAVE_CANVAS_EVENT, handleHostSaveCanvasEvent);
10657
- window.addEventListener(HOST_SET_PRIMARY_WIDGET_EVENT, handleHostSetPrimaryWidgetEvent);
10658
- window.addEventListener(HOST_REQUEST_CANVAS_WIDGETS_EVENT, handleHostRequestCanvasWidgetsEvent);
10659
- window.addEventListener(HOST_MOVE_CANVAS_FOLDER_EVENT, handleHostMoveCanvasFolderEvent);
11038
+ // The `widgetic:host-*` events are the Widgetic site's header talking to the creator; a partner's page has no
11039
+ // such header, and a page-wide listener there would answer to whatever the partner's own scripts dispatch.
11040
+ if (mayListenToSiteEvents()) {
11041
+ window.addEventListener(HOST_WIDGET_RENAMED_EVENT, handleHostWidgetRenamedEvent);
11042
+ window.addEventListener(HOST_REQUEST_PUBLISH_EVENT, handleHostRequestPublishEvent);
11043
+ window.addEventListener(HOST_TOGGLE_DEBUG_EVENT, handleHostToggleDebugEvent);
11044
+ window.addEventListener(HOST_TOGGLE_WIREFRAME_EVENT, handleHostToggleWireframeEvent);
11045
+ window.addEventListener(HOST_TOGGLE_ADVANCED_EVENT, handleHostToggleAdvancedEvent);
11046
+ window.addEventListener(HOST_OPEN_WIDGET_DETAILS_EVENT, handleHostOpenWidgetDetailsEvent);
11047
+ window.addEventListener(HOST_DUPLICATE_WIDGET_EVENT, handleHostDuplicateWidgetEvent);
11048
+ window.addEventListener(HOST_DELETE_WIDGET_EVENT, handleHostDeleteWidgetEvent);
11049
+ window.addEventListener(HOST_SAVE_CANVAS_EVENT, handleHostSaveCanvasEvent);
11050
+ window.addEventListener(HOST_SET_PRIMARY_WIDGET_EVENT, handleHostSetPrimaryWidgetEvent);
11051
+ window.addEventListener(HOST_REQUEST_CANVAS_WIDGETS_EVENT, handleHostRequestCanvasWidgetsEvent);
11052
+ window.addEventListener(HOST_MOVE_CANVAS_FOLDER_EVENT, handleHostMoveCanvasFolderEvent);
11053
+ }
10660
11054
  emitCreatorDebugChanged();
10661
11055
  emitCreatorWireframeChanged();
10662
11056
  emitCreatorAdvancedChanged();
@@ -10667,6 +11061,8 @@ Requirements:
10667
11061
  onMount(() => {
10668
11062
  const handleEscapeCapture = (e: KeyboardEvent) => {
10669
11063
  if (e.key !== 'Escape') return;
11064
+ // In a partner's page an Escape that started outside the creator is the partner's (their own dialog).
11065
+ if (!eventIsFromCreator(e, creatorRootEl)) return;
10670
11066
  if (lightboxImage) {
10671
11067
  lightboxImage = null;
10672
11068
  e.stopImmediatePropagation();
@@ -10684,9 +11080,10 @@ Requirements:
10684
11080
  onMount(() => {
10685
11081
  const handlePasteCapture = async (e: ClipboardEvent) => {
10686
11082
  if (!showWidgetDetails || !selectedWidgetId) return;
10687
- const target = e.target as HTMLElement;
10688
- // Only intercept if paste originates from inside widget details or widgets list panels
10689
- const isInsidePanel = target?.closest?.('.widget-details-floating-panel, .widgets-list-panel, [data-widget-details]');
11083
+ if (!eventIsFromCreator(e, creatorRootEl)) return;
11084
+ // Only intercept if paste originates from inside widget details or widgets list panels. (The event's whole
11085
+ // path is looked at, not `e.target.closest(…)`: in a shadow root `target` is the shadow's host element.)
11086
+ const isInsidePanel = eventPathMatches(e, '.widget-details-floating-panel, .widgets-list-panel, [data-widget-details]');
10690
11087
  if (!isInsidePanel) return;
10691
11088
  const items = e.clipboardData?.items;
10692
11089
  if (!items) return;
@@ -10699,7 +11096,7 @@ Requirements:
10699
11096
  const base64 = await processImageFile(file);
10700
11097
  if (base64) {
10701
11098
  chatMethods?.addImageAttachment?.(base64, file.name || 'pasted-image.png');
10702
- showToast('success', 'Image pasted to prompt', { duration: 2000 });
11099
+ showToast('success', $t('creator.codegen.imagePastedToPrompt'), { duration: 2000 });
10703
11100
  }
10704
11101
  }
10705
11102
  return;
@@ -10729,7 +11126,7 @@ Requirements:
10729
11126
 
10730
11127
  function saveCommitIdForWidget(widgetId: string, commitId: string) {
10731
11128
  commitIdMemoryCache.set(widgetId, commitId);
10732
- try { localStorage.setItem(COMMIT_ID_STORAGE_PREFIX + widgetId, commitId); } catch (e) { /* ignore */ }
11129
+ try { creatorStorage.setItem(COMMIT_ID_STORAGE_PREFIX + widgetId, commitId); } catch (e) { /* ignore */ }
10733
11130
  }
10734
11131
 
10735
11132
  function loadCommitIdForWidget(widgetId: string): string | null {
@@ -10737,7 +11134,7 @@ Requirements:
10737
11134
  return commitIdMemoryCache.get(widgetId) ?? null;
10738
11135
  }
10739
11136
  try {
10740
- const id = localStorage.getItem(COMMIT_ID_STORAGE_PREFIX + widgetId);
11137
+ const id = creatorStorage.getItem(COMMIT_ID_STORAGE_PREFIX + widgetId);
10741
11138
  if (id) {
10742
11139
  commitIdMemoryCache.set(widgetId, id);
10743
11140
  return id;
@@ -10754,15 +11151,15 @@ Requirements:
10754
11151
  function savePendingPublishShaForWidget(widgetId: string, commitId: string) {
10755
11152
  const sha = normalizeCommitSha(commitId) || commitId;
10756
11153
  if (!widgetId || !sha) return;
10757
- try { sessionStorage.setItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId, sha); } catch (e) { /* ignore */ }
11154
+ try { creatorSessionStorage.setItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId, sha); } catch (e) { /* ignore */ }
10758
11155
  }
10759
11156
 
10760
11157
  function loadPendingPublishShaForWidget(widgetId: string): string | null {
10761
- try { return sessionStorage.getItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId); } catch (e) { return null; }
11158
+ try { return creatorSessionStorage.getItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId); } catch (e) { return null; }
10762
11159
  }
10763
11160
 
10764
11161
  function clearPendingPublishShaForWidget(widgetId: string) {
10765
- try { sessionStorage.removeItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId); } catch (e) { /* ignore */ }
11162
+ try { creatorSessionStorage.removeItem(PENDING_PUBLISH_STORAGE_PREFIX + widgetId); } catch (e) { /* ignore */ }
10766
11163
  }
10767
11164
 
10768
11165
  const COMMIT_MESSAGE_REGEX = /Commit:?\s+([a-f0-9]{7,40})/i;
@@ -10846,18 +11243,31 @@ Requirements:
10846
11243
  return typeof raw === 'string' && raw.trim().length > 0 ? raw.trim() : null;
10847
11244
  }
10848
11245
 
11246
+ /**
11247
+ * The line of a code generation that is under way, as a visitor reads it ("Generating code... (40%)"). It is one of the
11248
+ * creator's own lines that the status bar says in the page's language (`i18n/statusText.ts` knows both forms).
11249
+ */
11250
+ function codegenProgressLine(pct: number | null): string {
11251
+ return pct != null && pct > 0 ? `Generating code... (${pct}%)` : 'Generating code...';
11252
+ }
11253
+
11254
+ /** The lines of debug mode, which a partner's visitor never reads: the server's own stage, or the operation's status and number. */
11255
+ function codegenProgressDebugLine(op: OperationStatus, stage: string | null, pct: number | null): string {
11256
+ if (stage) {
11257
+ return pct != null && pct > 0 ? `${stage} (${pct}%)` : stage;
11258
+ }
11259
+ const progressText = pct != null ? `${pct}%` : '';
11260
+ return progressText ? `Generating code... ${progressText}` : `Generating code (${op.status})...`;
11261
+ }
11262
+
10849
11263
  function formatCodegenProgressStatus(op: OperationStatus): string {
10850
11264
  const stage = getOperationStageMessage(op.metadata as Record<string, unknown> | undefined);
10851
11265
  const pct = typeof op.progress === 'number' ? op.progress : null;
10852
11266
  // User mode: never expose model names / provider in the status line.
10853
11267
  if (!debugMode) {
10854
- return pct != null && pct > 0 ? `Generating code... (${pct}%)` : 'Generating code...';
11268
+ return codegenProgressLine(pct);
10855
11269
  }
10856
- if (stage) {
10857
- return pct != null && pct > 0 ? `${stage} (${pct}%)` : stage;
10858
- }
10859
- const progressText = pct != null ? `${pct}%` : '';
10860
- return progressText ? `Generating code... ${progressText}` : `Generating code (${op.status})...`;
11270
+ return codegenProgressDebugLine(op, stage, pct);
10861
11271
  }
10862
11272
 
10863
11273
  function pushCodegenProgressToUi(op: OperationStatus, widgetId: string | null | undefined) {
@@ -11187,7 +11597,7 @@ Requirements:
11187
11597
  let storedPrompt = DEFAULT_PROMPT;
11188
11598
  try {
11189
11599
  storedPrompt =
11190
- localStorage.getItem(PROMPT_TEXT_STORAGE_PREFIX + widgetId) ?? DEFAULT_PROMPT;
11600
+ creatorStorage.getItem(PROMPT_TEXT_STORAGE_PREFIX + widgetId) ?? DEFAULT_PROMPT;
11191
11601
  } catch {
11192
11602
  /* ignore */
11193
11603
  }
@@ -11729,20 +12139,19 @@ Requirements:
11729
12139
  return newestDraft != null ? `v${newestDraft}` : null;
11730
12140
  }
11731
12141
 
11732
- function formatPublishHistoryDate(record: {
11733
- publishedAt?: string;
11734
- published_at?: string;
11735
- }): string {
11736
- const d = new Date(record.publishedAt ?? record.published_at ?? '');
11737
- if (isNaN(d.getTime())) return '—';
11738
- const month = String(d.getMonth() + 1).padStart(2, '0');
11739
- const day = String(d.getDate()).padStart(2, '0');
11740
- const timePart = d.toLocaleTimeString(undefined, {
11741
- hour: '2-digit',
11742
- minute: '2-digit',
11743
- hour12: false,
11744
- });
11745
- return `${month}/${day}/${d.getFullYear()} ${timePart}`;
12142
+ /**
12143
+ * The date of a version, written the way the page's language writes dates. A template that shows it passes `$languageTag`
12144
+ * so the row is written again when the page changes the language; the canvas, which asks for the options when it needs
12145
+ * them, gets whatever language is current.
12146
+ */
12147
+ function formatPublishHistoryDate(
12148
+ record: {
12149
+ publishedAt?: string;
12150
+ published_at?: string;
12151
+ },
12152
+ dateLanguage: string = get(languageTag)
12153
+ ): string {
12154
+ return versionDateText(new Date(record.publishedAt ?? record.published_at ?? ''), dateLanguage);
11746
12155
  }
11747
12156
 
11748
12157
  function resolveWidgetShapeVersionOptions(
@@ -11783,7 +12192,7 @@ Requirements:
11783
12192
  const isPublished = !!(record.publishedAt ?? record.published_at);
11784
12193
  options.push({
11785
12194
  id: `v:${version}`,
11786
- label: `Version ${version}`,
12195
+ label: $t('creator.version.version', { version }),
11787
12196
  shortLabel: `v${version}`,
11788
12197
  dateLabel: formatPublishHistoryDate(record),
11789
12198
  // Only a published version can be what visitors see.
@@ -11795,7 +12204,7 @@ Requirements:
11795
12204
  if (options.length === 0 && liveVersion != null) {
11796
12205
  options.push({
11797
12206
  id: `v:${liveVersion}`,
11798
- label: `Version ${liveVersion}`,
12207
+ label: $t('creator.version.version', { version: liveVersion }),
11799
12208
  shortLabel: `v${liveVersion}`,
11800
12209
  dateLabel: '—',
11801
12210
  isLive: true,
@@ -12030,6 +12439,7 @@ Requirements:
12030
12439
  void restoredViewingVersionByWidgetId;
12031
12440
  void dropdownVersionByWidgetId;
12032
12441
  void panelDisplayRevision;
12442
+ void $t;
12033
12443
  const nextHeads: Record<string, string | null> = {};
12034
12444
  const nextLabels: Record<string, Record<string, string>> = {};
12035
12445
  const nextPrompts: Record<string, Record<string, string>> = {};
@@ -12574,7 +12984,8 @@ Requirements:
12574
12984
 
12575
12985
  // Widgets Panel sizing — dynamically adapts to auth panel height
12576
12986
  const topBarHeight = 56; // h-14 (3.5rem) top bar
12577
- const embeddedSiteHeaderHeight = 56; // site AppHeader when CreatorApp is embedded in /canvas
12987
+ // site AppHeader when CreatorApp is embedded in /canvas; a partner's page has no such header above the creator.
12988
+ const embeddedSiteHeaderHeight = partnerMode ? 8 : 56;
12578
12989
  const widgetsPanelBottomMargin = 130; // kept for details panel default sizing
12579
12990
  $: widgetsPanelTopOffset = embedded ? embeddedSiteHeaderHeight : topBarHeight + 8;
12580
12991
  let widgetsPanelWidth = 450;
@@ -12622,14 +13033,16 @@ Requirements:
12622
13033
  widgetsPanelY = Math.round(rect.top);
12623
13034
  }
12624
13035
 
13036
+ /** The drag cursor of the panel's edges and of the panel itself (on the page's <body> on the site, in the creator's own area in a partner's page). */
13037
+ const widgetsPanelDragFeedback = createDragFeedback();
13038
+
12625
13039
  function startWidgetsPanelResize(e: MouseEvent) {
12626
13040
  e.preventDefault();
12627
13041
  e.stopPropagation();
12628
13042
  isResizingWidgetsPanel = true;
12629
13043
  widgetsResizeStartX = e.clientX;
12630
13044
  widgetsResizeStartWidth = widgetsPanelWidth;
12631
- document.body.style.cursor = 'col-resize';
12632
- document.body.style.userSelect = 'none';
13045
+ widgetsPanelDragFeedback.start(creatorRootEl, 'col-resize');
12633
13046
  document.addEventListener('mousemove', onWidgetsPanelResize);
12634
13047
  document.addEventListener('mouseup', stopWidgetsPanelResize);
12635
13048
  }
@@ -12643,8 +13056,7 @@ Requirements:
12643
13056
 
12644
13057
  function stopWidgetsPanelResize() {
12645
13058
  isResizingWidgetsPanel = false;
12646
- document.body.style.cursor = '';
12647
- document.body.style.userSelect = '';
13059
+ widgetsPanelDragFeedback.stop();
12648
13060
  document.removeEventListener('mousemove', onWidgetsPanelResize);
12649
13061
  document.removeEventListener('mouseup', stopWidgetsPanelResize);
12650
13062
  }
@@ -12658,8 +13070,7 @@ Requirements:
12658
13070
  widgetsResizeStartY = e.clientY;
12659
13071
  widgetsResizeStartWidth = widgetsPanelWidth;
12660
13072
  widgetsResizeStartHeight = widgetsPanelHeight;
12661
- document.body.style.cursor = 'nwse-resize';
12662
- document.body.style.userSelect = 'none';
13073
+ widgetsPanelDragFeedback.start(creatorRootEl, 'nwse-resize');
12663
13074
  document.addEventListener('mousemove', onWidgetsPanelCornerResize);
12664
13075
  document.addEventListener('mouseup', stopWidgetsPanelCornerResize);
12665
13076
  }
@@ -12678,8 +13089,7 @@ Requirements:
12678
13089
 
12679
13090
  function stopWidgetsPanelCornerResize() {
12680
13091
  isResizingWidgetsPanelCorner = false;
12681
- document.body.style.cursor = '';
12682
- document.body.style.userSelect = '';
13092
+ widgetsPanelDragFeedback.stop();
12683
13093
  document.removeEventListener('mousemove', onWidgetsPanelCornerResize);
12684
13094
  document.removeEventListener('mouseup', stopWidgetsPanelCornerResize);
12685
13095
  }
@@ -12698,7 +13108,7 @@ Requirements:
12698
13108
  widgetsPanelY = y;
12699
13109
  // Direct DOM write keeps drag smooth even if Svelte batching lags on inline style updates.
12700
13110
  if (widgetsPanelEl) {
12701
- widgetsPanelEl.style.left = `${x}px`;
13111
+ widgetsPanelEl.style.left = `${x}px`; // rtl-ok: the panel is put in pixels from the left edge of the screen and dragged there
12702
13112
  widgetsPanelEl.style.top = `${y}px`;
12703
13113
  }
12704
13114
  }
@@ -12713,8 +13123,7 @@ Requirements:
12713
13123
  widgetsPanelDragStartY = e.clientY;
12714
13124
  widgetsPanelInitialX = widgetsPanelX;
12715
13125
  widgetsPanelInitialY = widgetsPanelY < 0 ? widgetsPanelTopOffset : widgetsPanelY;
12716
- document.body.style.cursor = 'grabbing';
12717
- document.body.style.userSelect = 'none';
13126
+ widgetsPanelDragFeedback.start(creatorRootEl, 'grabbing');
12718
13127
  document.addEventListener('pointermove', onWidgetsPanelDrag);
12719
13128
  document.addEventListener('pointerup', stopWidgetsPanelDrag);
12720
13129
  document.addEventListener('pointercancel', stopWidgetsPanelDrag);
@@ -12743,8 +13152,7 @@ Requirements:
12743
13152
  function stopWidgetsPanelDrag(e?: PointerEvent) {
12744
13153
  if (!isDraggingWidgetsPanel) return;
12745
13154
  isDraggingWidgetsPanel = false;
12746
- document.body.style.cursor = '';
12747
- document.body.style.userSelect = '';
13155
+ widgetsPanelDragFeedback.stop();
12748
13156
  document.removeEventListener('pointermove', onWidgetsPanelDrag);
12749
13157
  document.removeEventListener('pointerup', stopWidgetsPanelDrag);
12750
13158
  document.removeEventListener('pointercancel', stopWidgetsPanelDrag);
@@ -13203,13 +13611,13 @@ Requirements:
13203
13611
  const nextVersion = (ps.lastPublishedVersion ?? 0) + 1;
13204
13612
 
13205
13613
  if (panelIsPublishing) {
13206
- return { disabled: true, label: 'Publishing...', reason: 'Publishing in progress…', showDisabledHint: false };
13614
+ return { disabled: true, label: $t('creator.publish.publishing'), reason: $t('creator.publish.publishingInProgress'), showDisabledHint: false };
13207
13615
  }
13208
13616
  if (anotherPanelIsPublishing) {
13209
13617
  return {
13210
13618
  disabled: true,
13211
13619
  label: getPublishButtonLabelFallback(ps),
13212
- reason: 'Another widget is publishing — wait for it to finish.',
13620
+ reason: $t('creator.publish.anotherWidgetIsPublishingWait'),
13213
13621
  showDisabledHint: true,
13214
13622
  };
13215
13623
  }
@@ -13217,7 +13625,7 @@ Requirements:
13217
13625
  return {
13218
13626
  disabled: true,
13219
13627
  label: getPublishButtonLabelFallback(ps),
13220
- reason: 'Publish is running in another browser tab.',
13628
+ reason: $t('creator.publish.publishIsRunningInAnother'),
13221
13629
  showDisabledHint: true,
13222
13630
  };
13223
13631
  }
@@ -13225,7 +13633,7 @@ Requirements:
13225
13633
  return {
13226
13634
  disabled: true,
13227
13635
  label: getPublishButtonLabelFallback(ps),
13228
- reason: 'Code generation in progress — wait until it finishes.',
13636
+ reason: $t('creator.codegen.codeGenerationInProgressWait'),
13229
13637
  showDisabledHint: true,
13230
13638
  };
13231
13639
  }
@@ -13233,7 +13641,7 @@ Requirements:
13233
13641
  return {
13234
13642
  disabled: true,
13235
13643
  label: getPublishButtonLabelFallback(ps),
13236
- reason: 'Canvas is required before publishing.',
13644
+ reason: $t('creator.canvas.canvasIsRequiredBeforePublishing'),
13237
13645
  showDisabledHint: true,
13238
13646
  };
13239
13647
  }
@@ -13241,7 +13649,7 @@ Requirements:
13241
13649
  return {
13242
13650
  disabled: true,
13243
13651
  label: getPublishButtonLabelFallback(ps),
13244
- reason: 'Repository missing — use Rebuild code or regenerate to create one.',
13652
+ reason: $t('creator.codegen.repositoryMissingUseRebuildCode'),
13245
13653
  showDisabledHint: true,
13246
13654
  };
13247
13655
  }
@@ -13249,13 +13657,13 @@ Requirements:
13249
13657
  return {
13250
13658
  disabled: true,
13251
13659
  label: getPublishButtonLabelFallback(ps),
13252
- reason: 'Sign in again to publish.',
13660
+ reason: signInAgainText($t('creator.session.signInAgainToPublish')),
13253
13661
  showDisabledHint: true,
13254
13662
  };
13255
13663
  }
13256
13664
  const previewBlockReason = getVersionPreviewPublishBlockReason(widgetId, targetVersion);
13257
13665
  if (previewBlockReason) {
13258
- return { disabled: true, label: 'Publish', reason: previewBlockReason, showDisabledHint: true };
13666
+ return { disabled: true, label: $t('creator.common.publish'), reason: errorLabel(previewBlockReason, $t), showDisabledHint: true };
13259
13667
  }
13260
13668
  // An explicit Draft owns its commit: HEAD being Live must not block it.
13261
13669
  // Keep all shared auth/canvas/repository/concurrency checks above this branch.
@@ -13265,27 +13673,27 @@ Requirements:
13265
13673
  );
13266
13674
  const validVersion = targetVersion !== '' && Number.isInteger(Number(targetVersion)) && Number(targetVersion) > 0;
13267
13675
  const reason = !validVersion || !record
13268
- ? 'The selected draft version was not found.'
13676
+ ? $t('creator.version.theSelectedDraftVersionWas')
13269
13677
  : (record.publishedAt ?? record.published_at)
13270
- ? 'This version is already published.'
13678
+ ? $t('creator.publish.thisVersionIsAlreadyPublished')
13271
13679
  : !(record.commitSha ?? record.commit_sha)
13272
- ? 'This draft has no recorded commit to publish.'
13680
+ ? $t('creator.publish.thisDraftHasNoRecorded')
13273
13681
  : null;
13274
- return { disabled: !!reason, label: 'Publish', reason, showDisabledHint: !!reason };
13682
+ return { disabled: !!reason, label: $t('creator.common.publish'), reason, showDisabledHint: !!reason };
13275
13683
  }
13276
13684
 
13277
13685
  if (!hasCode) {
13278
13686
  return {
13279
13687
  disabled: true,
13280
13688
  label: getPublishButtonLabelFallback(ps),
13281
- reason: 'Generate widget code before publishing.',
13689
+ reason: $t('creator.publish.generateWidgetCodeBeforePublishing'),
13282
13690
  showDisabledHint: true,
13283
13691
  };
13284
13692
  }
13285
13693
 
13286
13694
  // Never published → allow Publish once code exists.
13287
13695
  if (ps.lastPublishedVersion === null) {
13288
- return { disabled: false, label: 'Publish Widget', reason: null, showDisabledHint: false };
13696
+ return { disabled: false, label: $t('creator.publish.publishWidget'), reason: null, showDisabledHint: false };
13289
13697
  }
13290
13698
 
13291
13699
  const headSha = resolvePublishHeadCommitId(widgetId, ps);
@@ -13306,8 +13714,8 @@ Requirements:
13306
13714
  if (headSha && liveSha && commitsMatch(headSha, liveSha) && !pendingPublish && !unpublishedAhead) {
13307
13715
  return {
13308
13716
  disabled: true,
13309
- label: 'No new version to publish',
13310
- reason: `Latest commit (${formatCommitShaShort(headSha)}) is already live at v${ps.lastPublishedVersion}.`,
13717
+ label: $t('creator.publish.noNewVersionToPublish'),
13718
+ reason: $t('creator.general.latestCommitIsAlreadyLive', { commit: formatCommitShaShort(headSha), version: ps.lastPublishedVersion }),
13311
13719
  showDisabledHint: false,
13312
13720
  };
13313
13721
  }
@@ -13322,7 +13730,7 @@ Requirements:
13322
13730
  // });
13323
13731
  return {
13324
13732
  disabled: false,
13325
- label: `Publish new v${nextVersion}`,
13733
+ label: $t('creator.publish.publishNewV', { version: nextVersion }),
13326
13734
  reason: null,
13327
13735
  showDisabledHint: false,
13328
13736
  };
@@ -13332,7 +13740,7 @@ Requirements:
13332
13740
  if (headSha && liveSha && !commitsMatch(headSha, liveSha)) {
13333
13741
  return {
13334
13742
  disabled: false,
13335
- label: `Publish new v${nextVersion}`,
13743
+ label: $t('creator.publish.publishNewV', { version: nextVersion }),
13336
13744
  reason: null,
13337
13745
  showDisabledHint: false,
13338
13746
  };
@@ -13342,15 +13750,15 @@ Requirements:
13342
13750
  if (!headSha) {
13343
13751
  return {
13344
13752
  disabled: true,
13345
- label: 'No new version to publish',
13346
- reason: 'Generate or rebuild so we can detect a new commit to publish.',
13753
+ label: $t('creator.publish.noNewVersionToPublish'),
13754
+ reason: $t('creator.publish.generateOrRebuildSoWe'),
13347
13755
  showDisabledHint: true,
13348
13756
  };
13349
13757
  }
13350
13758
 
13351
13759
  return {
13352
13760
  disabled: true,
13353
- label: 'No new version to publish',
13761
+ label: $t('creator.publish.noNewVersionToPublish'),
13354
13762
  reason: null,
13355
13763
  showDisabledHint: false,
13356
13764
  };
@@ -13441,7 +13849,7 @@ Requirements:
13441
13849
  const gateBefore = getPublishGateForPanel(panelWidgetId, targetVersion ?? null);
13442
13850
  if (gateBefore.disabled) {
13443
13851
  if (gateBefore.reason) {
13444
- showToast('info', 'Cannot publish yet', { description: gateBefore.reason, duration: 5000 });
13852
+ showToast('info', $t('creator.publish.cannotPublishYet'), { description: gateBefore.reason, duration: 5000 });
13445
13853
  }
13446
13854
  return;
13447
13855
  }
@@ -13454,7 +13862,7 @@ Requirements:
13454
13862
  const gateAfter = getPublishGateForPanel(panelWidgetId, targetVersion ?? null);
13455
13863
  if (gateAfter.disabled) {
13456
13864
  if (gateAfter.reason) {
13457
- showToast('info', 'Cannot publish yet', { description: gateAfter.reason, duration: 5000 });
13865
+ showToast('info', $t('creator.publish.cannotPublishYet'), { description: gateAfter.reason, duration: 5000 });
13458
13866
  }
13459
13867
  return;
13460
13868
  }
@@ -13482,7 +13890,7 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
13482
13890
 
13483
13891
  if (publishResult.status === 'success') {
13484
13892
  if (isFocusedPublish) {
13485
- publishWidgetStatus = `Published v${publishResult.version ?? '?'} successfully!`;
13893
+ publishWidgetStatus = $t('creator.publish.publishedVSuccessfully', { version: publishResult.version ?? '?' });
13486
13894
  }
13487
13895
  const publishedVersion = publishResult.version ?? 1;
13488
13896
  applyPublishSuccessToWidgetState(
@@ -13493,8 +13901,8 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
13493
13901
  publishResult.commitTitle ?? null
13494
13902
  );
13495
13903
  const publishedName = getWidgetById(publishWidgetId)?.name || 'Widget';
13496
- showToast('success', `"${publishedName}" published!`, {
13497
- description: `Version ${publishResult.version ?? ''} is live and ready to embed.`,
13904
+ showToast('success', $t('creator.publish.published', { name: publishedName }), {
13905
+ description: $t('creator.embed.versionIsLiveAndReady', { version: publishResult.version ?? '' }),
13498
13906
  duration: 6000
13499
13907
  });
13500
13908
  if (publishWidgetId) {
@@ -13515,8 +13923,8 @@ $: if ($widgetPublishStatus.timestamp && $widgetPublishStatus.widgetId) {
13515
13923
  if (isFocusedPublish) {
13516
13924
  publishWidgetStatus = null;
13517
13925
  }
13518
- showToast('error', 'Widget publish failed', {
13519
- description: publishResult.message || publishResult.error?.details || 'Build failed. Check logs for details.',
13926
+ showToast('error', $t('creator.publish.widgetPublishFailed'), {
13927
+ description: publishResult.message || publishResult.error?.details || $t('creator.codegen.buildFailedCheckLogsFor'),
13520
13928
  duration: 8000
13521
13929
  });
13522
13930
  }
@@ -13657,7 +14065,7 @@ async function loadPublishHistoryForPanel(widgetId: string, opts: { silent?: boo
13657
14065
  publishHistoryResolvedForWidgetId = widgetId;
13658
14066
  }
13659
14067
  if (!opts.silent && widgetId === selectedWidgetId) {
13660
- showToast('error', 'Failed to load publish history');
14068
+ showToast('error', $t('creator.publish.failedToLoadPublishHistory'));
13661
14069
  }
13662
14070
  } finally {
13663
14071
  if (!opts.silent && widgetId === selectedWidgetId) {
@@ -13691,15 +14099,15 @@ async function setLiveVersionForWidget(widgetId: string, version: number) {
13691
14099
  (row) => Number(row.version) === version,
13692
14100
  );
13693
14101
  if (record && !(record.publishedAt ?? record.published_at)) {
13694
- showToast('info', 'This is a draft version', {
13695
- description: 'Press Publish to make the latest generated code live.',
14102
+ showToast('info', $t('creator.version.thisIsADraftVersion'), {
14103
+ description: $t('creator.publish.pressPublishToMakeThe'),
13696
14104
  });
13697
14105
  return;
13698
14106
  }
13699
14107
 
13700
14108
  isSettingLiveVersion = version;
13701
14109
  if (!widgetsClient) {
13702
- showToast('error', 'Widgets API client is not configured');
14110
+ showToast('error', $t('creator.widget.widgetsApiClientIsNot'));
13703
14111
  isSettingLiveVersion = null;
13704
14112
  return;
13705
14113
  }
@@ -13738,13 +14146,13 @@ async function setLiveVersionForWidget(widgetId: string, version: number) {
13738
14146
  if (widgetId === selectedWidgetId || widgetId === focusedPanelWidgetId) {
13739
14147
  revealCompositionPreview();
13740
14148
  }
13741
- showToast('success', `Live: v${version}`, {
13742
- description: 'This version is now what visitors see on your sites.',
14149
+ showToast('success', $t('creator.general.liveV', { version }), {
14150
+ description: $t('creator.version.thisVersionIsNowWhat'),
13743
14151
  duration: 5000
13744
14152
  });
13745
14153
  } catch (err: any) {
13746
14154
  console.error('[PublishHistory] set-live unexpected error:', err);
13747
- showToast('error', 'Failed to set live version');
14155
+ showToast('error', $t('creator.publish.failedToSetLiveVersion'));
13748
14156
  } finally {
13749
14157
  isSettingLiveVersion = null;
13750
14158
  }
@@ -13758,7 +14166,7 @@ async function setLiveVersionForWidget(widgetId: string, version: number) {
13758
14166
  async function renameVersionTitleForWidget(widgetId: string, version: number, title: string) {
13759
14167
  if (!widgetId || !$userSession?.jwt) return;
13760
14168
  if (!widgetsClient) {
13761
- showToast('error', 'Widgets API client is not configured');
14169
+ showToast('error', $t('creator.widget.widgetsApiClientIsNot'));
13762
14170
  return;
13763
14171
  }
13764
14172
 
@@ -13791,7 +14199,7 @@ async function renameVersionTitleForWidget(widgetId: string, version: number, ti
13791
14199
  record.commit_title = stored ?? null;
13792
14200
  }
13793
14201
  panelDisplayRevision += 1;
13794
- showToast('success', stored ? 'Version renamed' : 'Version title cleared');
14202
+ showToast('success', stored ? $t('creator.version.versionRenamed') : $t('creator.version.versionTitleCleared'));
13795
14203
  } catch (err) {
13796
14204
  // Roll the row back; nothing else needs reloading — the write did not land.
13797
14205
  if (record) {
@@ -13799,8 +14207,8 @@ async function renameVersionTitleForWidget(widgetId: string, version: number, ti
13799
14207
  record.commit_title = previousTitle;
13800
14208
  }
13801
14209
  panelDisplayRevision += 1;
13802
- showToast('error', 'Could not rename the version', {
13803
- description: err instanceof ResponseError ? 'The server refused the rename.' : 'Check your connection and try again.',
14210
+ showToast('error', $t('creator.version.couldNotRenameTheVersion'), {
14211
+ description: err instanceof ResponseError ? $t('creator.general.theServerRefusedTheRename') : $t('creator.general.checkYourConnectionAndTry'),
13804
14212
  });
13805
14213
  } finally {
13806
14214
  renamingTitleFor = null;
@@ -13826,7 +14234,9 @@ function togglePublishHistory(triggerEl?: HTMLElement | null) {
13826
14234
  liveHistoryPanelTop = Math.round(rect.bottom + 4);
13827
14235
  // Rows inset their action button 12px from the panel edge (panel p-1 4px + row px-2 8px).
13828
14236
  // Shift right by 12px so the per-row action buttons line up under the header action button.
13829
- liveHistoryPanelRight = Math.round(window.innerWidth - rect.right) - 12;
14237
+ // On a right to left screen the cluster is at the other end of the header, so it is the left edge that lines up
14238
+ // and the list grows toward the middle of the panel.
14239
+ liveHistoryPanelPlacement = listAlignedToEnd($textDirection, rect, window.innerWidth, 12);
13830
14240
  }
13831
14241
  loadPublishHistory();
13832
14242
  }
@@ -14045,7 +14455,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14045
14455
  authStatus = `${defaultErrorMessage}: Unable to reach the server. Please verify the API gateway is running and try again.`;
14046
14456
  showToast('error', defaultErrorMessage, {
14047
14457
  description:
14048
- 'Unable to reach the API gateway. Please ensure the server is running and try again.',
14458
+ $t('creator.general.unableToReachTheApi'),
14049
14459
  duration: 6000
14050
14460
  });
14051
14461
  return;
@@ -14067,6 +14477,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14067
14477
  hasValidToken = false;
14068
14478
  inlinePanelView = null;
14069
14479
  selectedWidget = null;
14480
+ if (partnerMode) {
14481
+ // The page owns the sign-in: tell it, and stay where we are.
14482
+ endHostSession('The session has been signed out.', 'SIGNED_OUT');
14483
+ return;
14484
+ }
14070
14485
  if (typeof window !== 'undefined') {
14071
14486
  window.location.href = '/login';
14072
14487
  }
@@ -14078,6 +14493,15 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14078
14493
  function updateTokenStatus() {
14079
14494
  // console.log('WidgetCreator.updateTokenStatus: currentUserToken:', currentUserToken);
14080
14495
 
14496
+ // Partner mode: the token is an opaque editor session token, not a JWT, so there is nothing to decode. The page
14497
+ // keeps it fresh (adoptHostToken); it is good until the page says the session is over.
14498
+ if (partnerMode) {
14499
+ hasValidToken = !!currentUserToken && !hostSessionEnded;
14500
+ tokenExpired = hostSessionEnded;
14501
+ tokenTimeLeft = hasValidToken ? Number.MAX_SAFE_INTEGER : 0;
14502
+ return;
14503
+ }
14504
+
14081
14505
  // if the session has a jwt, decode the token and update the token status
14082
14506
  if (currentUserToken) {
14083
14507
  // decode the token
@@ -14140,6 +14564,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14140
14564
  // and show a warning instead of abruptly cutting off the operation
14141
14565
  function checkTokenExpiration() {
14142
14566
  updateTokenStatus();
14567
+ // Partner mode: tokens are never "expired" by the clock here; the page renews them, and a session the page cannot
14568
+ // renew is reported by adoptHostToken.
14569
+ if (partnerMode) return hasValidToken;
14143
14570
  if (currentUserToken) {
14144
14571
  if (tokenExpired || tokenTimeLeft <= 0) {
14145
14572
  const hasActiveOperations = isGeneratingCode || (showPreviewModal && previewLoading);
@@ -14369,9 +14796,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14369
14796
  const widget = getWidgetById(widgetId);
14370
14797
  if (!widget) {
14371
14798
  console.warn('[WidgetCreator] Widget Image clicked but widget not found:', widgetId);
14372
- showToast('warning', 'Unlinked widget shape', {
14799
+ showToast('warning', $t('creator.widget.unlinkedWidgetShape'), {
14373
14800
  description:
14374
- 'This shape points to a deleted or moved widget. Select it and press Delete, or use "Remove from canvas" in the sidebar.',
14801
+ $t('creator.canvas.thisShapePointsToA'),
14375
14802
  duration: 8000,
14376
14803
  });
14377
14804
  return;
@@ -14430,20 +14857,20 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14430
14857
 
14431
14858
  if (!widgetsClient || !hasValidToken) {
14432
14859
  console.warn('[WidgetCreator] Cannot duplicate widget — not authenticated');
14433
- showToast('error', 'Login required to duplicate widget');
14860
+ showToast('error', $t('creator.session.loginRequiredToDuplicateWidget'));
14434
14861
  return;
14435
14862
  }
14436
14863
 
14437
14864
  if (isWidgetOperationInProgress) {
14438
14865
  console.warn('[WidgetCreator] Another widget operation in progress, skipping duplicate');
14439
- showToast('warning', 'Please wait for the current operation to finish');
14866
+ showToast('warning', $t('creator.general.pleaseWaitForTheCurrent'));
14440
14867
  return;
14441
14868
  }
14442
14869
 
14443
14870
  try {
14444
14871
  isWidgetOperationInProgress = true;
14445
14872
  canvasRef?.markSelectedAsDuplicating();
14446
- showToast('info', 'Duplicating widget...', { duration: 2000 });
14873
+ showToast('info', $t('creator.widget.duplicatingWidget'), { duration: 2000 });
14447
14874
 
14448
14875
  const response = await widgetsClient.duplicateWidget({
14449
14876
  id: sourceWidgetId,
@@ -14453,7 +14880,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14453
14880
 
14454
14881
  if (!newWidget?.id) {
14455
14882
  console.error('[WidgetCreator] duplicateWidget returned no data', response);
14456
- showToast('error', 'Failed to duplicate widget');
14883
+ showToast('error', $t('creator.widget.failedToDuplicateWidget'));
14457
14884
  return;
14458
14885
  }
14459
14886
 
@@ -14535,10 +14962,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14535
14962
  await selectWidget(asWidgetSummary(newWidget), { skipPlaceShape: true });
14536
14963
  notifyHostWidgetName(getWidgetById(canvasPrimaryWidgetId) ?? getWidgetById(sourceWidgetId));
14537
14964
 
14538
- showToast('success', 'Widget duplicated', {
14965
+ showToast('success', $t('creator.widget.widgetDuplicated'), {
14539
14966
  description: sourceHasCode
14540
- ? `"${newWidget.name}" created with existing code`
14541
- : `"${newWidget.name}" created`
14967
+ ? $t('creator.codegen.createdWithExistingCode', { name: newWidget.name })
14968
+ : $t('creator.general.created', { name: newWidget.name })
14542
14969
  });
14543
14970
 
14544
14971
  setTimeout(() => handleWidgetDataChanged(newWidget.id), 1500);
@@ -14585,8 +15012,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14585
15012
  }, 6000);
14586
15013
  } catch (err) {
14587
15014
  console.error('[WidgetCreator] Failed to duplicate widget:', err);
14588
- showToast('error', 'Failed to duplicate widget', {
14589
- description: err instanceof Error ? err.message : 'Unknown error'
15015
+ showToast('error', $t('creator.widget.failedToDuplicateWidget'), {
15016
+ description: err instanceof Error ? err.message : $t('creator.general.unknownError')
14590
15017
  });
14591
15018
  } finally {
14592
15019
  isWidgetOperationInProgress = false;
@@ -14615,7 +15042,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14615
15042
  if (result.deleteFromDb) {
14616
15043
  await deleteWidgetFromDb(widgetId);
14617
15044
  } else {
14618
- showToast('info', 'Shape removed from canvas', { description: `Widget "${widgetName}" kept in database` });
15045
+ showToast('info', $t('creator.canvas.shapeRemovedFromCanvas'), { description: $t('creator.widget.widgetKeptInDatabase2', { name: widgetName }) });
14619
15046
  }
14620
15047
  return true;
14621
15048
  }
@@ -14645,11 +15072,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14645
15072
  panelDisplayRevision += 1;
14646
15073
  backfillWidgetShapeMetadata();
14647
15074
  syncWidgetShapeLivePreviews();
14648
- showToast('success', `Widget renamed to "${newName}"`);
15075
+ showToast('success', $t('creator.widget.widgetRenamedTo', { name: newName }));
14649
15076
  } catch (error) {
14650
15077
  console.error('[WidgetCreator] Failed to rename widget:', error);
14651
- showToast('error', 'Failed to rename widget', {
14652
- description: error instanceof Error ? error.message : 'Unknown error'
15078
+ showToast('error', $t('creator.widget.failedToRenameWidget'), {
15079
+ description: error instanceof Error ? error.message : $t('creator.general.unknownError')
14653
15080
  });
14654
15081
  }
14655
15082
  }
@@ -14730,8 +15157,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14730
15157
  canvasHydrateRetryCount = 0;
14731
15158
  clearCanvasHydrateRetry();
14732
15159
  clearCanvasLoadFailsafe();
15160
+ announceReadyOnce();
14733
15161
  }
14734
15162
  function armCanvasLoadFailsafe(reason: string, forCanvasId: string) {
15163
+ // The failsafe ends in "the canvas is loaded": not for a canvas the visitor cannot open.
15164
+ if (canvasUnavailable) return;
14735
15165
  const failsafeKey = forCanvasId || '__pending__';
14736
15166
  if (canvasLoadFailsafeArmedForId === failsafeKey && canvasLoadFailsafeTimer) return;
14737
15167
  if (canvasLoadFailsafeTimer) clearTimeout(canvasLoadFailsafeTimer);
@@ -14746,8 +15176,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14746
15176
  return;
14747
15177
  }
14748
15178
  markCanvasStateLoaded();
14749
- showToast('warning', 'Canvas is taking longer than expected', {
14750
- description: 'You can keep editing widgets. Retry load if shapes are missing.',
15179
+ showToast('warning', $t('creator.canvas.canvasIsTakingLongerThan'), {
15180
+ description: $t('creator.widget.youCanKeepEditingWidgets'),
14751
15181
  duration: 8000,
14752
15182
  });
14753
15183
  }, timeoutMs);
@@ -14755,6 +15185,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14755
15185
  async function tryLoadCanvasState(): Promise<{ loaded: boolean; widgetIds: string[] }> {
14756
15186
  const emptyResult = { loaded: false, widgetIds: [] as string[] };
14757
15187
  const loadEpoch = canvasLoadEpoch;
15188
+ // Partner mode: the page's canvas is not the visitor's; asking for it again would not change the answer.
15189
+ if (canvasUnavailable) return emptyResult;
14758
15190
  if (ignoreIncomingCanvasLoads) {
14759
15191
  // console.log('[CanvasDebug] tryLoadCanvasState skipped — new widget blank canvas');
14760
15192
  canvasRef?.onClearAllObjects();
@@ -14797,7 +15229,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14797
15229
  let localCachedJson: string | null = null;
14798
15230
  try {
14799
15231
  localCachedJson = (await readCanvasState(canvasId)) ?? (() => {
14800
- try { return localStorage.getItem(getCanvasStorageKey()); } catch { return null; }
15232
+ try { return creatorStorage.getItem(getCanvasStorageKey()); } catch { return null; }
14801
15233
  })();
14802
15234
  if (localCachedJson && canvasRef) {
14803
15235
  const parsed = JSON.parse(localCachedJson);
@@ -14816,10 +15248,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14816
15248
  }
14817
15249
 
14818
15250
  // ── Revalidate against remote API (single request, no artificial sleep loops) ──
15251
+ canvasRemoteReadsInFlight += 1;
14819
15252
  try {
14820
15253
  if (canvasesClient) {
14821
15254
  let canvasContent: any = null;
14822
- for (let attempt = 0; attempt < 5; attempt++) {
15255
+ // A canvas that comes back without content is read once more in case it was only just saved. On the site a
15256
+ // few more times; a partner's visitor starts from an empty canvas more often than not, and should not wait
15257
+ // seconds (and ask a dozen times) to be told that is what it is.
15258
+ const maxCanvasReadAttempts = partnerMode ? 2 : 5;
15259
+ for (let attempt = 0; attempt < maxCanvasReadAttempts; attempt++) {
15260
+ // Another read has already found out there is no such canvas for this visitor.
15261
+ if (canvasUnavailable) return emptyResult;
14823
15262
  try {
14824
15263
  const canvasResponse = await withCanvasApiTimeout(
14825
15264
  canvasesClient.getCanvasRaw({ id: canvasId }),
@@ -14836,9 +15275,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14836
15275
  console.log('[CanvasDebug] getCanvas returned no canvasContent, retry', attempt + 1);
14837
15276
  } catch (getErr) {
14838
15277
  console.warn('[CanvasDebug] getCanvas failed, retry', attempt + 1, getErr);
14839
- if (attempt >= 4) throw getErr;
15278
+ // "No such canvas" is an answer, not a hiccup: asking again would only get it again.
15279
+ if (saysCanvasIsMissing(getErr) || attempt >= maxCanvasReadAttempts - 1) throw getErr;
14840
15280
  }
14841
- if (attempt < 4) {
15281
+ if (attempt < maxCanvasReadAttempts - 1) {
14842
15282
  await new Promise((resolve) => setTimeout(resolve, 400 * (attempt + 1)));
14843
15283
  }
14844
15284
  }
@@ -14877,7 +15317,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14877
15317
  canvasShapesLoaded = true;
14878
15318
  } catch (loadErr) {
14879
15319
  console.warn('[WidgetCreator] canvasRef.loadCanvas failed/timed out — clearing loading overlay:', loadErr);
14880
- canvasApiLoadError = toErrorMessage(loadErr, 'Canvas shapes failed to render');
15320
+ canvasApiLoadError = toErrorMessage(loadErr, $t('creator.canvas.canvasShapesFailedToRender'));
14881
15321
  }
14882
15322
  if (canvasShapesLoaded) canvasApiLoadError = null;
14883
15323
  }
@@ -14888,7 +15328,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14888
15328
  setTimeout(() => { isLoadCooldownActive = false; }, 3000);
14889
15329
  lastSavedCanvasObjectCount = objectCount;
14890
15330
  setTimeout(refreshLinkedWidgetIds, 500);
14891
- try { sessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
15331
+ try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
14892
15332
  // console.log('[WidgetCreator] Canvas state validated from API (autosave cooldown 3s)');
14893
15333
  return { loaded: true, widgetIds: widgetIdsOnCanvas };
14894
15334
  } else {
@@ -14899,19 +15339,28 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14899
15339
  }
14900
15340
  } catch (err) {
14901
15341
  console.warn('[WidgetCreator] Failed to load canvas from API:', err);
14902
- const errMsg = toErrorMessage(err, 'Failed to load canvas from API');
15342
+ const errMsg = toErrorMessage(err, $t('creator.canvas.failedToLoadCanvasFrom'));
14903
15343
  canvasApiLoadError = errMsg;
15344
+ // Partner mode: the API says the canvas does not exist for this visitor. It is not an empty canvas to start on
15345
+ // (the fallbacks below would call it one and say the creator is ready): the page is told, and that is the end.
15346
+ if (saysCanvasIsMissing(err)) {
15347
+ declareCanvasUnavailable(canvasId || null, errMsg);
15348
+ return emptyResult;
15349
+ }
14904
15350
  if (/timed out|failed to fetch|network|econnrefused|503|502|load canvases/i.test(errMsg)) {
14905
15351
  console.log('[CanvasDebug] Skip localStorage canvas fallback after API/network error');
14906
15352
  return emptyResult;
14907
15353
  }
14908
- if (/quota|limit|billing|exceeded|402|403|503/i.test(errMsg)) {
14909
- showToast('error', 'Canvas load failed — check Supabase billing', {
15354
+ // (The hint about the Widgetic site's own database billing is for its team, not for a partner's visitor.)
15355
+ if (!partnerMode && /quota|limit|billing|exceeded|402|403|503/i.test(errMsg)) {
15356
+ showToast('error', $t('creator.canvas.canvasLoadFailedCheckSupabase'), {
14910
15357
  description:
14911
- 'API may be throttled or unavailable. Widget list still loads from DB; canvas shapes need a successful canvas fetch.',
15358
+ $t('creator.canvas.apiMayBeThrottledOr'),
14912
15359
  duration: 10000,
14913
15360
  });
14914
15361
  }
15362
+ } finally {
15363
+ canvasRemoteReadsInFlight -= 1;
14915
15364
  }
14916
15365
 
14917
15366
  // Fallback: if SWR hasn't painted yet and API failed, try loading from localStorage
@@ -14921,7 +15370,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14921
15370
  }
14922
15371
  try {
14923
15372
  const saved = (await readCanvasState(canvasId)) ?? (() => {
14924
- try { return localStorage.getItem(getCanvasStorageKey()); } catch { return null; }
15373
+ try { return creatorStorage.getItem(getCanvasStorageKey()); } catch { return null; }
14925
15374
  })();
14926
15375
  if (saved && canvasRef) {
14927
15376
  let parsed: any = null;
@@ -14947,7 +15396,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14947
15396
  setTimeout(() => { isLoadCooldownActive = false; }, 3000);
14948
15397
  lastSavedCanvasObjectCount = objectCount;
14949
15398
  setTimeout(refreshLinkedWidgetIds, 500);
14950
- try { sessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
15399
+ try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
14951
15400
  // console.log('[WidgetCreator] Canvas state loaded from localStorage (autosave cooldown 3s)');
14952
15401
  return { loaded: true, widgetIds: widgetIdsOnCanvas };
14953
15402
  } else {
@@ -14964,7 +15413,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
14964
15413
  // Both API and localStorage returned empty — this is genuinely a new/empty canvas
14965
15414
  markCanvasStateLoaded();
14966
15415
  lastSavedCanvasObjectCount = 0;
14967
- try { sessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, '0'); } catch {}
15416
+ try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, '0'); } catch {}
14968
15417
  // console.log(
14969
15418
  // `[CanvasDebug] Loading canvas ${canvasId}: NO shapes found anywhere - starting fresh`
14970
15419
  // );
@@ -15057,8 +15506,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15057
15506
  `[CanvasDebug] BLOCKING save: would overwrite ${lastSavedCanvasObjectCount} shapes with 0 (isUnmount=${isUnmountSave}, force=${force})`
15058
15507
  );
15059
15508
  if (force) {
15060
- showToast('error', 'Save blocked', {
15061
- description: 'Canvas snapshot looked empty — refresh and try again.',
15509
+ showToast('error', $t('creator.general.saveBlocked'), {
15510
+ description: $t('creator.canvas.canvasSnapshotLookedEmptyRefresh'),
15062
15511
  });
15063
15512
  }
15064
15513
  return;
@@ -15068,7 +15517,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15068
15517
  }
15069
15518
 
15070
15519
  lastSavedCanvasObjectCount = objectCount;
15071
- try { sessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
15520
+ try { creatorSessionStorage.setItem(CANVAS_OBJ_COUNT_KEY, String(objectCount)); } catch {}
15072
15521
  emitCreatorSaveState(false);
15073
15522
 
15074
15523
  // Save to durable L1 fallback (always, even with 0 objects for legitimate clears)
@@ -15080,7 +15529,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15080
15529
  if (!isAnyWidgetGenerating() || force || isUnmountSave) {
15081
15530
  measureSync('canvas-autosave:localStorage-mirror', () => {
15082
15531
  try {
15083
- localStorage.setItem(getCanvasStorageKey(), json);
15532
+ creatorStorage.setItem(getCanvasStorageKey(), json);
15084
15533
  } catch (err) {
15085
15534
  console.warn('[WidgetCreator] Failed to save canvas to localStorage:', err);
15086
15535
  }
@@ -15112,7 +15561,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15112
15561
  }
15113
15562
  lastResolvedAutosaveSequence = currentSeq;
15114
15563
  if (force) {
15115
- showToast('success', 'Canvas saved', { duration: 2000 });
15564
+ showToast('success', $t('creator.canvas.canvasSaved'), { duration: 2000 });
15116
15565
  }
15117
15566
  // console.log(
15118
15567
  // `[CanvasDebug] Canvas ${canvasId} saved to API: ${objectCount} shapes (seq ${currentSeq})`
@@ -15120,14 +15569,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15120
15569
  } catch (err) {
15121
15570
  console.warn('[WidgetCreator] Failed to save canvas to API:', err);
15122
15571
  if (force) {
15123
- showToast('error', 'Canvas save failed', {
15124
- description: 'Kept a local copy — check your connection and retry.',
15572
+ showToast('error', $t('creator.canvas.canvasSaveFailed'), {
15573
+ description: $t('creator.general.keptALocalCopyCheck'),
15125
15574
  });
15126
15575
  }
15127
15576
  }
15128
15577
  } else if (force) {
15129
- showToast('success', 'Canvas saved locally', {
15130
- description: canvasId ? 'API client unavailable.' : 'No canvas id yet.',
15578
+ showToast('success', $t('creator.canvas.canvasSavedLocally'), {
15579
+ description: canvasId ? $t('creator.general.apiClientUnavailable') : $t('creator.canvas.noCanvasIdYet'),
15131
15580
  duration: 2500,
15132
15581
  });
15133
15582
  }
@@ -15148,12 +15597,12 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15148
15597
  // console.log('[WidgetCreator] Convert to widget (draft, v2):', payload);
15149
15598
 
15150
15599
  if (!$userSession.user || !hasValidToken) {
15151
- showToast('error', 'Please login first');
15600
+ showToast('error', $t('creator.session.pleaseLoginFirst'));
15152
15601
  return;
15153
15602
  }
15154
15603
  if (isWidgetOperationInProgress) {
15155
15604
  console.warn('[WidgetCreator] Another widget operation in progress, skipping convert');
15156
- showToast('warning', 'Please wait for the current operation to finish');
15605
+ showToast('warning', $t('creator.general.pleaseWaitForTheCurrent'));
15157
15606
  return;
15158
15607
  }
15159
15608
 
@@ -15165,8 +15614,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15165
15614
  payload.screenshot?.length ?? 0,
15166
15615
  ') — keeping original shapes so the sketch is not lost'
15167
15616
  );
15168
- showToast('warning', 'Screenshot could not be captured', {
15169
- description: 'Fix the selection (zoom out / deselect) and try Convert again.',
15617
+ showToast('warning', $t('creator.general.screenshotCouldNotBeCaptured'), {
15618
+ description: $t('creator.general.fixTheSelectionZoomOut'),
15170
15619
  duration: 10000
15171
15620
  });
15172
15621
  return;
@@ -15254,15 +15703,15 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15254
15703
  }
15255
15704
 
15256
15705
  authStatus = 'Widget draft ready — send the prompt to generate.';
15257
- showToast('info', 'Widget draft created', {
15258
- description: 'Edit the sketch freely. Sending the prompt creates the widget.'
15706
+ showToast('info', $t('creator.widget.widgetDraftCreated'), {
15707
+ description: $t('creator.codegen.editTheSketchFreelySending')
15259
15708
  });
15260
15709
  } catch (error) {
15261
15710
  console.error('[WidgetCreator] Convert to widget (draft) error:', error);
15262
15711
  draftConvertObjectIds.delete(draftId);
15263
15712
  draftConvertScreenshots.delete(draftId);
15264
15713
  authStatus = toErrorMessage(error, 'Failed to prepare widget draft.');
15265
- showToast('error', 'Failed to prepare widget draft');
15714
+ showToast('error', $t('creator.widget.failedToPrepareWidgetDraft'));
15266
15715
  } finally {
15267
15716
  isWidgetOperationInProgress = false;
15268
15717
  setTimeout(() => {
@@ -15304,7 +15753,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15304
15753
  // Canvas sketch snapshot is stored on the widget for future reference
15305
15754
  content: { source: 'canvas_convert', prompt },
15306
15755
  isDraft: true,
15307
- description: draftName,
15756
+ // (No `description`: a new widget has no such field, the API ignored it, and a partner's session is
15757
+ // refused for sending a field it may not write.)
15308
15758
  ...(canvasId ? { canvasId } : {}),
15309
15759
  ...embeddedWidgetProjectContext()
15310
15760
  }
@@ -15315,13 +15765,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15315
15765
  const createEnvelope = response as unknown as { error?: string; message?: string };
15316
15766
  if (!response || createEnvelope.error || createEnvelope.message) {
15317
15767
  console.error('[WidgetCreator] Widget create on first send failed:', response);
15318
- showToast('error', 'Failed to create widget from design');
15768
+ showToast('error', $t('creator.widget.failedToCreateWidgetFrom'));
15319
15769
  return null;
15320
15770
  }
15321
15771
 
15322
15772
  const newWidget = asWidgetSummary((response as { data?: unknown }).data ?? response);
15323
15773
  if (!newWidget?.id) {
15324
- showToast('warning', 'Widget created but no ID returned');
15774
+ showToast('warning', $t('creator.widget.widgetCreatedButNoId'));
15325
15775
  return null;
15326
15776
  }
15327
15777
  const widgetId: string = newWidget.id;
@@ -15456,13 +15906,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15456
15906
  pendingChatDraftText = '';
15457
15907
 
15458
15908
  authStatus = 'Widget created from design.';
15459
- showToast('success', 'Widget created', {
15460
- description: `"${draftName}" is ready — generation started`
15909
+ showToast('success', $t('creator.widget.widgetCreated'), {
15910
+ description: $t('creator.codegen.isReadyGenerationStarted', { name: draftName })
15461
15911
  });
15462
15912
  return widgetId;
15463
15913
  } catch (error) {
15464
15914
  console.error('[WidgetCreator] finalizeDraftConversion error:', error);
15465
- showToast('error', 'Failed to finalize widget conversion');
15915
+ showToast('error', $t('creator.widget.failedToFinalizeWidgetConversion'));
15466
15916
  return null;
15467
15917
  } finally {
15468
15918
  suppressWidgetDetailsClose = false;
@@ -15556,8 +16006,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15556
16006
  async function recreateRepositoryForWidget(widget: WidgetSummary) {
15557
16007
  if (!$userSession.user || !hasValidToken) {
15558
16008
  console.warn('Cannot create repository: not authenticated');
15559
- showToast('error', 'Authentication required', {
15560
- description: 'Please login before creating a repository.',
16009
+ showToast('error', $t('creator.session.authenticationRequired'), {
16010
+ description: $t('creator.session.pleaseLoginBeforeCreatingA'),
15561
16011
  duration: 5000
15562
16012
  });
15563
16013
  return;
@@ -15570,8 +16020,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15570
16020
  currentRepositoryId = repoId;
15571
16021
  widgetDetails?.setCurrentRepositoryId(repoId);
15572
16022
  }
15573
- showToast('success', 'Repository created', {
15574
- description: `Repository ${repoId.slice(0, 8)}… is now linked to this widget.`
16023
+ showToast('success', $t('creator.codegen.repositoryCreated'), {
16024
+ description: $t('creator.codegen.repositoryIsNowLinkedTo', { id: repoId.slice(0, 8) })
15575
16025
  });
15576
16026
  }
15577
16027
  }
@@ -15580,8 +16030,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15580
16030
  const repoId = normalizeRepositoryId(widget);
15581
16031
  if (repoId) {
15582
16032
  // Repository exists - show info
15583
- showToast('info', 'Repository exists', {
15584
- description: `Repo ID: ${repoId.slice(0, 8)}…\nTo delete, use the Delete widget button.`
16033
+ showToast('info', $t('creator.codegen.repositoryExists'), {
16034
+ description: $t('creator.widget.repoIdToDeleteUse', { id: repoId.slice(0, 8) })
15585
16035
  });
15586
16036
  } else {
15587
16037
  // Create repository
@@ -15619,8 +16069,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15619
16069
  return false;
15620
16070
  }
15621
16071
 
15622
- // check if the repository belongs to the current user
15623
- const repoOwnerMatches = repoDetails.userId === $userSession.user?.id;
16072
+ // check if the repository belongs to the current user. In a partner's page the repository belongs to the
16073
+ // partner's account, never to the visitor, and the gateway has already checked that this visitor may open it
16074
+ // (it answers 404 otherwise), so there is no owner to compare here.
16075
+ const repoOwnerMatches = partnerMode || repoDetails.userId === $userSession.user?.id;
15624
16076
  // if the repository does not belong to the current user, show a warning and return false
15625
16077
  if (!repoOwnerMatches) {
15626
16078
  console.warn('Repository belongs to a different user. Re-creating.', {
@@ -15629,9 +16081,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15629
16081
  currentUser: $userSession.user?.id
15630
16082
  });
15631
16083
  if (!silent) {
15632
- showToast('warning', 'Repository owned by another account', {
16084
+ showToast('warning', $t('creator.codegen.repositoryOwnedByAnotherAccount'), {
15633
16085
  description:
15634
- 'This widget references a repository owned by a different user. A new repository will be provisioned to avoid permission issues.',
16086
+ $t('creator.session.thisWidgetReferencesARepository'),
15635
16087
  duration: 6000
15636
16088
  });
15637
16089
  }
@@ -15639,8 +16091,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15639
16091
  }
15640
16092
 
15641
16093
  if (!silent) {
15642
- showToast('info', 'Repository found', {
15643
- description: `Linked to repository ${repoDetails.id.slice(0, 8)}...`
16094
+ showToast('info', $t('creator.codegen.repositoryFound'), {
16095
+ description: $t('creator.codegen.linkedToRepository', { id: repoDetails.id.slice(0, 8) })
15644
16096
  });
15645
16097
  }
15646
16098
  return true;
@@ -15657,14 +16109,17 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15657
16109
  if (retryDetails?.id) return true;
15658
16110
  } catch (retryError) {
15659
16111
  if (retryError instanceof ResponseError && retryError.response?.status === 401) {
15660
- if (!silent) {
15661
- showToast('warning', 'Session expired', {
15662
- description: 'Sign in again, then retry. The widget repository is still linked.',
15663
- duration: 6000
15664
- });
15665
- }
15666
- if (typeof window !== 'undefined') {
15667
- window.dispatchEvent(new CustomEvent('widgetic:session-needs-reauth'));
16112
+ if (partnerMode) {
16113
+ // The page's token was refused twice (the renewal already ran): the session is over.
16114
+ endHostSession('The API refused the session token.', 'SESSION_REFUSED');
16115
+ } else {
16116
+ if (!silent) {
16117
+ showToast('warning', $t('creator.session.sessionExpired'), {
16118
+ description: $t('creator.session.signInAgainThenRetry'),
16119
+ duration: 6000
16120
+ });
16121
+ }
16122
+ announceToSite('widgetic:session-needs-reauth');
15668
16123
  }
15669
16124
  throw retryError;
15670
16125
  }
@@ -15677,9 +16132,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15677
16132
  status
15678
16133
  });
15679
16134
  if (!silent) {
15680
- showToast('warning', 'Repository reference invalid', {
16135
+ showToast('warning', $t('creator.codegen.repositoryReferenceInvalid'), {
15681
16136
  description:
15682
- 'Supabase does not have this repository or you no longer own it. A fresh repository will be provisioned.',
16137
+ $t('creator.codegen.supabaseDoesNotHaveThis'),
15683
16138
  duration: 6000
15684
16139
  });
15685
16140
  }
@@ -15689,8 +16144,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15689
16144
 
15690
16145
  console.error('Failed to verify repository', error);
15691
16146
  if (!silent) {
15692
- const message = await deriveApiErrorMessage(error, 'Unable to verify repository status.');
15693
- showToast('error', 'Repository verification failed', {
16147
+ const message = await deriveApiErrorMessage(error, $t('creator.codegen.unableToVerifyRepositoryStatus'));
16148
+ showToast('error', $t('creator.codegen.repositoryVerificationFailed'), {
15694
16149
  description: message,
15695
16150
  duration: 5000
15696
16151
  });
@@ -15719,8 +16174,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15719
16174
  const repoId = (repoData?.id || repoData?.repoId || repoData?.repo_id || null) as string | null;
15720
16175
 
15721
16176
  if (!repoId) {
15722
- showToast('error', 'Repository creation failed', {
15723
- description: 'Could not determine repository ID after creation.',
16177
+ showToast('error', $t('creator.codegen.repositoryCreationFailed'), {
16178
+ description: $t('creator.codegen.couldNotDetermineRepositoryId'),
15724
16179
  duration: 5000
15725
16180
  });
15726
16181
  return null;
@@ -15739,24 +16194,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15739
16194
  })
15740
16195
  .catch((err) => {
15741
16196
  console.error('Widget Creator: Failed to persist repository ID for widget', err);
15742
- showToast('warning', 'Repository created but not persisted', {
16197
+ showToast('warning', $t('creator.codegen.repositoryCreatedButNotPersisted'), {
15743
16198
  description:
15744
- 'Repository exists but failed to sync with widget record. Try generating code to resync.',
16199
+ $t('creator.codegen.repositoryExistsButFailedTo'),
15745
16200
  duration: 6000
15746
16201
  });
15747
16202
  });
15748
16203
 
15749
16204
  if (!silent) {
15750
- showToast('success', 'Repository created', {
15751
- description: `Repository ${repoId.slice(0, 8)}… ready for use.`
16205
+ showToast('success', $t('creator.codegen.repositoryCreated'), {
16206
+ description: $t('creator.codegen.repositoryReadyForUse', { id: repoId.slice(0, 8) })
15752
16207
  });
15753
16208
  }
15754
16209
 
15755
16210
  return repoId;
15756
16211
  } catch (error) {
15757
16212
  console.error('Failed to create repository for widget:', error);
15758
- showToast('error', 'Repository creation failed', {
15759
- description: error?.message || 'Check console for details.',
16213
+ showToast('error', $t('creator.codegen.repositoryCreationFailed'), {
16214
+ description: error?.message || $t('creator.general.checkConsoleForDetails'),
15760
16215
  duration: 5000
15761
16216
  });
15762
16217
  return null;
@@ -15849,6 +16304,21 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15849
16304
  }
15850
16305
  }
15851
16306
 
16307
+ /**
16308
+ * In a partner's page: a press inside the creator puts the keyboard focus in the creator, so that the keys the visitor
16309
+ * presses next (Delete, Ctrl+Z, the arrows ...) are the creator's and not the page's. The creator is in a shadow root
16310
+ * there, and a press on something that cannot take the focus itself (a panel's background, the canvas) would leave the
16311
+ * focus on the page's <body>, outside the shadow root, where the creator does not hear the keys. A control that can
16312
+ * take the focus still gets it: the browser gives it the focus after this, as the press's own default.
16313
+ */
16314
+ function keepFocusInCreator(): void {
16315
+ const creatorRoot = creatorRootEl;
16316
+ if (!creatorRoot) return;
16317
+ const focusRoot = creatorRoot.getRootNode() as Document | ShadowRoot;
16318
+ if (focusRoot.activeElement && creatorRoot.contains(focusRoot.activeElement)) return;
16319
+ creatorRoot.focus({ preventScroll: true });
16320
+ }
16321
+
15852
16322
  // Svelte action: auto-focus element when mounted (for ESC key to work in modal)
15853
16323
  function focusOnMount(node) {
15854
16324
  // Use requestAnimationFrame to ensure DOM is fully rendered
@@ -15861,6 +16331,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15861
16331
  <svelte:window
15862
16332
  onkeydown={(e) => {
15863
16333
  if (e.key === 'Escape') {
16334
+ // In a partner's page an Escape that started outside the creator is the partner's (their own dialog).
16335
+ if (!eventIsFromCreator(e, creatorRootEl)) return;
15864
16336
  if (showPreviewModal) { showPreviewModal = false; return; }
15865
16337
  }
15866
16338
  }}
@@ -15871,7 +16343,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15871
16343
  }}
15872
16344
  />
15873
16345
 
15874
- <div class="widget-creator-root-page-ct relative flex flex-col w-full h-full {className}" style={style}>
16346
+ <!-- Partner mode: the creator is a place the keyboard can be "in" (shortcuts are for the canvas only while the focus is inside it, see `keepFocusInCreator`); the root takes the focus programmatically (tabindex -1), it is not a tab stop. -->
16347
+ <!-- svelte-ignore a11y_no_noninteractive_tabindex -->
16348
+ <div
16349
+ bind:this={creatorRootEl}
16350
+ class="widget-creator-root-page-ct relative flex flex-col w-full h-full {partnerMode ? 'outline-none' : ''} {className}"
16351
+ dir={$textDirection}
16352
+ style={style}
16353
+ tabindex={partnerMode ? -1 : undefined}
16354
+ onpointerdowncapture={partnerMode ? keepFocusInCreator : undefined}
16355
+ >
15875
16356
 
15876
16357
  <!-- AUTH SCREEN - Show when user is NOT logged in (standalone only) -->
15877
16358
  {#if !embedded && !$userSession.user}
@@ -15955,7 +16436,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15955
16436
  </div>
15956
16437
  {#if debugModeAvailable}
15957
16438
  <span
15958
- class="wc-build-info text-[10px] font-mono text-gray-400 leading-none pl-0.5"
16439
+ class="wc-build-info text-[10px] font-mono text-gray-400 leading-none ps-0.5"
15959
16440
  title="Deployed build — remove when beta ends"
15960
16441
  >{buildLabel}</span>
15961
16442
  {/if}
@@ -16045,18 +16526,22 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16045
16526
  <div class="canvas-state-warning-banner rounded-lg border px-4 py-3 shadow-md text-sm
16046
16527
  {canvasApiLoadError ? 'border-red-200 bg-red-50 text-red-900' : 'border-amber-200 bg-amber-50 text-amber-900'}">
16047
16528
  {#if canvasApiLoadError}
16048
- <p class="font-semibold">Canvas shapes failed to load</p>
16529
+ <p class="font-semibold">{canvasUnavailable ? $t('creator.canvas.canvasUnavailable') : $t('creator.canvas.canvasShapesFailedToLoad')}</p>
16049
16530
  <p class="text-xs mt-1">{canvasApiLoadError}</p>
16531
+ {#if !partnerMode}
16050
16532
  <p class="text-xs mt-1 opacity-90">If Supabase shows a billing/quota warning, upgrade or review billing — API reads may fail while the widget list still loads.</p>
16533
+ {/if}
16051
16534
  {:else}
16052
- <p class="font-semibold">Canvas appears empty but {widgets.length} widget{widgets.length === 1 ? '' : 's'} exist on this canvas</p>
16053
- <p class="text-xs mt-1">Shape data may be missing from the saved canvas (failed autosave or API quota). Widgets still work from the list — click Restore shapes to re-add placeholders on the canvas.</p>
16535
+ <p class="font-semibold">{$t('creator.canvas.appearsEmptyButWidgets', { count: widgets.length })}</p>
16536
+ <p class="text-xs mt-1">{$t('creator.canvas.shapeDataMayBeMissing')}</p>
16054
16537
  {/if}
16055
16538
  <div class="canvas-state-warning-actions flex gap-2 mt-3">
16056
- <Button variant="outline" size="sm" onclick={retryLoadCanvas}>Retry load</Button>
16539
+ {#if !canvasUnavailable}
16540
+ <Button variant="outline" size="sm" onclick={retryLoadCanvas}>{$t('creator.general.retryLoad')}</Button>
16541
+ {/if}
16057
16542
  {#if canvasShapesMissingWarning}
16058
- <Button variant="default" size="sm" onclick={() => void handleRestoreShapesClick()}>Restore shapes</Button>
16059
- <Button variant="outline" size="sm" onclick={() => { canvasShapesMissingWarning = false; }}>Dismiss</Button>
16543
+ <Button variant="default" size="sm" onclick={() => void handleRestoreShapesClick()}>{$t('creator.widget.restoreShapes')}</Button>
16544
+ <Button variant="outline" size="sm" onclick={() => { canvasShapesMissingWarning = false; }}>{$t('creator.general.dismiss')}</Button>
16060
16545
  {/if}
16061
16546
  </div>
16062
16547
  </div>
@@ -16065,6 +16550,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16065
16550
  {#if WidgeticCanvas}
16066
16551
  <svelte:component this={WidgeticCanvas}
16067
16552
  bind:this={canvasRef}
16553
+ locale={locale}
16554
+ messages={canvasMessages}
16068
16555
  showContainerFrame={!embedded}
16069
16556
  widgetSelectionLayerTarget="floating-panels-overlay"
16070
16557
  bind:wireframeMode={canvasWireframeMode}
@@ -16168,7 +16655,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16168
16655
  <div
16169
16656
  bind:this={widgetsPanelEl}
16170
16657
  class="widgets-floating-panel pointer-events-auto fixed bg-white/95 backdrop-blur-sm rounded-lg shadow-lg border border-gray-300 pt-0 pb-2.5 px-2.5 flex flex-col gap-3 overflow-hidden"
16171
- style="min-width: {WIDGETS_PANEL_MIN_WIDTH}px; width: {widgetsPanelWidth}px; left: {widgetsPanelX}px; top: {widgetsPanelTopPx}px; z-index: {widgetsPanelZIndex}; {isWidgetsPanelMinimized ? 'height: auto; max-height: none;' : `height: ${widgetsPanelHeight}px;`}"
16658
+ style="min-width: {WIDGETS_PANEL_MIN_WIDTH}px; width: {widgetsPanelWidth}px; left: {widgetsPanelX}px; /* rtl-ok: the panel is put in pixels from the left edge of the screen and dragged there */ top: {widgetsPanelTopPx}px; z-index: {widgetsPanelZIndex}; {isWidgetsPanelMinimized ? 'height: auto; max-height: none;' : `height: ${widgetsPanelHeight}px;`}"
16172
16659
  onmousedown={raiseWidgetsPanelToFront}
16173
16660
  >
16174
16661
  <!-- Drag bar -->
@@ -16176,7 +16663,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16176
16663
  class="widgets-panel-drag-bar relative flex items-center justify-between px-1 py-1.5 -mx-2.5 bg-gray-100 border-b border-gray-200 rounded-t-lg cursor-grab active:cursor-grabbing select-none shrink-0 touch-none"
16177
16664
  onpointerdown={startWidgetsPanelDrag}
16178
16665
  >
16179
- <span class="text-xs font-semibold text-gray-500 pl-2">Widgets List</span>
16666
+ <span class="text-xs font-semibold text-gray-500 ps-2">Widgets List</span>
16180
16667
  <div class="absolute left-1/2 -translate-x-1/2 flex items-center">
16181
16668
  <div class="grid grid-cols-3 gap-[3px]">
16182
16669
  <div class="w-[3px] h-[3px] rounded-full bg-gray-400"></div>
@@ -16189,7 +16676,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16189
16676
  </div>
16190
16677
  <!-- svelte-ignore a11y-click-events-have-key-events -->
16191
16678
  <button
16192
- class="widgets-panel-minimize-btn flex items-center justify-center w-6 h-6 rounded hover:bg-gray-200 transition-colors mr-1 cursor-pointer"
16679
+ class="widgets-panel-minimize-btn flex items-center justify-center w-6 h-6 rounded hover:bg-gray-200 transition-colors me-1 cursor-pointer"
16193
16680
  title={isWidgetsPanelMinimized ? 'Expand panel' : 'Minimize panel'}
16194
16681
  onclick={(e) => { e.stopPropagation(); isWidgetsPanelMinimized = !isWidgetsPanelMinimized; }}
16195
16682
  onmousedown={(e) => e.stopPropagation()}
@@ -16200,9 +16687,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16200
16687
  </button>
16201
16688
  </div> <!-- end of widgets-panel-drag-bar -->
16202
16689
 
16203
- <!-- Right-edge resize handle -->
16204
- <div
16205
- class="widgets-panel-resize-handle absolute top-0 right-0 w-[10px] h-full cursor-col-resize z-10 flex items-center justify-center hover:bg-blue-100/60 transition-colors"
16690
+ <!-- Right-edge resize handle. rtl-ok: the panel grows from its left edge on every screen, so the handle that widens it is on its right edge -->
16691
+ <div class="widgets-panel-resize-handle absolute top-0 right-0 w-[10px] h-full cursor-col-resize z-10 flex items-center justify-center hover:bg-blue-100/60 transition-colors"
16206
16692
  onmousedown={startWidgetsPanelResize}
16207
16693
  >
16208
16694
  <svg class="w-[4px] h-6 text-gray-400" viewBox="0 0 4 24" fill="currentColor">
@@ -16277,7 +16763,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16277
16763
 
16278
16764
  <!-- Widgets List Container -->
16279
16765
  <div
16280
- class="widgets-list-outer flex flex-col flex-1 min-h-0 border border-gray-200 rounded p-2.5 pr-0 {isWidgetsPanelMinimized ? 'overflow-hidden' : ''}"
16766
+ class="widgets-list-outer flex flex-col flex-1 min-h-0 border border-gray-200 rounded p-2.5 pe-0 {isWidgetsPanelMinimized ? 'overflow-hidden' : ''}"
16281
16767
  style={isWidgetsPanelMinimized ? 'max-height: 76px;' : ''}
16282
16768
  >
16283
16769
 
@@ -16427,11 +16913,12 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16427
16913
 
16428
16914
  <!-- svelte-ignore a11y-no-static-element-interactions -->
16429
16915
  {#if !isWidgetsPanelMinimized}
16430
- <div
16431
- class="widgets-panel-corner-resize absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize z-10 group"
16916
+ <!-- rtl-ok: the bottom right corner is where the panel is resized from, on every screen -->
16917
+ <div class="widgets-panel-corner-resize absolute bottom-0 right-0 w-4 h-4 cursor-nwse-resize z-10 group"
16432
16918
  onmousedown={startWidgetsPanelCornerResize}
16433
16919
  title="Resize panel"
16434
16920
  >
16921
+ <!-- rtl-ok: the grip is drawn in the bottom right corner, as the handle is -->
16435
16922
  <svg class="w-3 h-3 absolute bottom-0.5 right-0.5 text-gray-400 group-hover:text-gray-600 transition-colors" viewBox="0 0 6 6" fill="currentColor">
16436
16923
  <circle cx="5" cy="1" r="0.7"/>
16437
16924
  <circle cx="3" cy="3" r="0.7"/>
@@ -16607,10 +17094,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16607
17094
  // console.log('[WidgetCreator] Suppressed automatic build-from-repo chat message:', rebuildMsg);
16608
17095
  } else if (isPanelFocused) {
16609
17096
  chatMethods?.addAssistantMessage(rebuildMsg, false);
16610
- showToast('success', 'Preview rebuilt', {
17097
+ showToast('success', $t('creator.preview.rebuilt'), {
16611
17098
  description: buildMs
16612
- ? `Recompiled in ${buildMs}ms — commit ${shaLabel}.`
16613
- : `Commit ${shaLabel}. Preview refreshed.`,
17099
+ ? $t('creator.preview.recompiledIn', { ms: buildMs, commit: shaLabel })
17100
+ : $t('creator.preview.commitRefreshed', { commit: shaLabel }),
16614
17101
  duration: 6000,
16615
17102
  });
16616
17103
  }
@@ -16621,7 +17108,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16621
17108
  // console.log('[WidgetCreator] Retry repository for widget:', widgetId);
16622
17109
  const widget = getWidgetById(widgetId);
16623
17110
  if (!widget) {
16624
- showToast('error', 'Widget not found');
17111
+ showToast('error', $t('creator.widget.notFound'));
16625
17112
  return;
16626
17113
  }
16627
17114
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [widgetId]: 'pending' };
@@ -16635,8 +17122,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16635
17122
  widgetDetails?.setCurrentRepositoryId(repoId);
16636
17123
  }
16637
17124
  getWidgetDetailsRef(widgetId)?.showNoCodeYetState?.();
16638
- showToast('success', 'Repository created', {
16639
- description: `Preparing code generation...`
17125
+ showToast('success', $t('creator.codegen.repositoryCreated'), {
17126
+ description: $t('creator.status.preparingCodeGeneration')
16640
17127
  });
16641
17128
 
16642
17129
  // Restore prompt from localStorage or DB, then auto-generate
@@ -16645,7 +17132,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16645
17132
  // Source 1: durable draft store / localStorage (persisted at conversion time)
16646
17133
  const storedPromptText = await readWidgetDraft(widgetId)
16647
17134
  .then((draft) => draft?.promptText ?? null)
16648
- .catch(() => localStorage.getItem(PROMPT_TEXT_STORAGE_PREFIX + widgetId));
17135
+ .catch(() => creatorStorage.getItem(PROMPT_TEXT_STORAGE_PREFIX + widgetId));
16649
17136
  if (storedPromptText && storedPromptText !== DEFAULT_PROMPT) {
16650
17137
  loadPromptForWidget(widgetId);
16651
17138
  hasPrompt = true;
@@ -16696,13 +17183,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16696
17183
  }
16697
17184
  } else {
16698
17185
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [widgetId]: 'failed' };
16699
- showToast('error', 'Failed to create repository');
17186
+ showToast('error', $t('creator.codegen.failedToCreateRepository'));
16700
17187
  }
16701
17188
  } catch (err: any) {
16702
17189
  repositorySetupByWidgetId = { ...repositorySetupByWidgetId, [widgetId]: 'failed' };
16703
17190
  console.error('[WidgetCreator] Failed to retry repository:', err);
16704
- showToast('error', 'Failed to create repository', {
16705
- description: err?.message || 'Unknown error'
17191
+ showToast('error', $t('creator.codegen.failedToCreateRepository'), {
17192
+ description: err?.message || $t('creator.general.unknownError')
16706
17193
  });
16707
17194
  }
16708
17195
  }}
@@ -16765,11 +17252,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16765
17252
  >
16766
17253
  <svelte:fragment slot="header-meta">
16767
17254
  {#if saveStatus === 'saving' && isPanelFocused}
16768
- <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 animate-pulse">Saving...</span>
17255
+ <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-blue-100 text-blue-700 animate-pulse">{$t('creator.general.saving')}</span>
16769
17256
  {:else if saveStatus === 'saved' && isPanelFocused}
16770
- <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-green-100 text-green-700">Saved</span>
17257
+ <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-green-100 text-green-700">{$t('creator.general.saved')}</span>
16771
17258
  {:else if saveStatus === 'error' && isPanelFocused}
16772
- <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-700">Save Error</span>
17259
+ <span class="wc-header-save-status text-[10px] px-1.5 py-0.5 rounded bg-red-100 text-red-700">{$t('creator.general.saveError')}</span>
16773
17260
  {/if}
16774
17261
  {#if debugMode}
16775
17262
  <span class="wc-header-commit text-[10px] text-gray-500 whitespace-nowrap">
@@ -16819,7 +17306,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16819
17306
  ? !(viewingRecord.publishedAt ?? viewingRecord.published_at)
16820
17307
  : false}
16821
17308
  <div class="wc-version-history-ct relative shrink-0 flex items-center gap-0.5">
16822
- <HoverTooltip text="Switch version" maxWidth={120}>
17309
+ <HoverTooltip text={$t('creator.common.switchVersion')} maxWidth={120}>
16823
17310
  <button
16824
17311
  type="button"
16825
17312
  onclick={(e) => {
@@ -16842,16 +17329,16 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16842
17329
  runPublishForPanel(panelWidgetId);
16843
17330
  }}
16844
17331
  disabled={isPublishDisabledForPanel(panelWidgetId) || (isPublishing && publishingWidgetId === panelWidgetId)}
16845
- title={getPublishDisabledReasonForPanel(panelWidgetId) ?? 'Publish the latest generated code as the Live version'}
17332
+ title={getPublishDisabledReasonForPanel(panelWidgetId) ?? $t('creator.publish.publishTheLatestGeneratedCode')}
16846
17333
  class="wc-version-publish-btn shrink-0 inline-flex items-center justify-center min-w-[4.75rem] w-[4.75rem] text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
16847
17334
  >
16848
- {isPublishing && publishingWidgetId === panelWidgetId ? '...' : 'Publish'}
17335
+ {isPublishing && publishingWidgetId === panelWidgetId ? '...' : $t('creator.common.publish')}
16849
17336
  </button>
16850
17337
  {:else if viewingIsLive}
16851
17338
  <span
16852
17339
  class="wc-version-live-btn shrink-0 inline-flex items-center justify-center min-w-[4.75rem] w-[4.75rem] text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded bg-emerald-100 text-emerald-600 opacity-80"
16853
- title="Live — generate new code to Publish a new version"
16854
- >Live</span>
17340
+ title={$t('creator.publish.liveGenerateNewCodeTo')}
17341
+ >{$t('creator.common.live')}</span>
16855
17342
  {:else if viewingIsDraft}
16856
17343
  {#if viewingIsDraft}
16857
17344
  <button
@@ -16864,10 +17351,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16864
17351
  runPublishForPanel(panelWidgetId, Number(viewingVersion));
16865
17352
  }}
16866
17353
  disabled={!canPublishDraftVersionForPanel(panelWidgetId, viewingVersion) || getPublishGateForPanel(panelWidgetId, Number(viewingVersion)).disabled}
16867
- title="Build this draft version and make it the Live version"
17354
+ title={$t('creator.common.buildThisDraftVersionAnd')}
16868
17355
  class="wc-version-publish-btn shrink-0 inline-flex items-center justify-center min-w-[4.75rem] w-[4.75rem] text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-emerald-600 bg-emerald-600 text-white hover:bg-emerald-700 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
16869
17356
  >
16870
- {isPublishing && publishingWidgetId === panelWidgetId ? '...' : 'Publish'}
17357
+ {isPublishing && publishingWidgetId === panelWidgetId ? '...' : $t('creator.common.publish')}
16871
17358
  </button>
16872
17359
  {/if}
16873
17360
  {:else}
@@ -16881,40 +17368,40 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16881
17368
  }
16882
17369
  }}
16883
17370
  disabled={isSettingLiveVersion === Number(viewingVersion)}
16884
- title="Publish this version so visitors see it on your website"
17371
+ title={$t('creator.publish.publishThisVersionSoVisitors')}
16885
17372
  class="wc-version-set-live-btn shrink-0 inline-flex items-center justify-center min-w-[4.75rem] w-[4.75rem] text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-emerald-300 text-emerald-700 hover:bg-emerald-100 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer"
16886
17373
  >
16887
- {isSettingLiveVersion === Number(viewingVersion) ? '...' : 'Set live'}
17374
+ {isSettingLiveVersion === Number(viewingVersion) ? '...' : $t('creator.common.setLive')}
16888
17375
  </button>
16889
17376
  {/if}
16890
17377
  {#if isHistoryOpen && isPanelFocused}
16891
17378
  <Portal target="wc-live-history-portal-{panelWidgetId}">
16892
17379
  <button
16893
17380
  type="button"
16894
- class="wc-live-history-backdrop fixed left-0 right-0 bottom-0 top-14 z-[9998] cursor-default bg-transparent"
16895
- aria-label="Close version history"
17381
+ class="wc-live-history-backdrop fixed start-0 end-0 bottom-0 top-14 z-[9998] cursor-default bg-transparent"
17382
+ aria-label={$t('creator.version.closeVersionHistory')}
16896
17383
  onclick={() => { isHistoryOpen = false; }}
16897
17384
  ></button>
16898
17385
  {@const hasChatScroll = ps.publishHistory.length > 5}
16899
17386
  <div
16900
17387
  class="wc-version-history-panel rounded-md border border-emerald-200 bg-white shadow-lg p-1 z-[9999] w-max"
16901
- style="position: fixed; top: {liveHistoryPanelTop}px; right: {liveHistoryPanelRight}px;"
17388
+ style="position: fixed; top: {liveHistoryPanelTop}px; {liveHistoryPanelPlacement}"
16902
17389
  >
16903
17390
  {#if isLoadingHistory}
16904
- <p class="text-xs text-emerald-500 animate-pulse text-center py-2">Loading history...</p>
17391
+ <p class="text-xs text-emerald-500 animate-pulse text-center py-2">{$t('creator.general.loadingHistory')}</p>
16905
17392
  {:else if ps.publishHistory.length === 0}
16906
- <p class="text-xs text-emerald-400 text-center py-2">No history records yet. Generate or publish to start tracking.</p>
17393
+ <p class="text-xs text-emerald-400 text-center py-2">{$t('creator.publish.noHistoryRecordsYetGenerate')}</p>
16907
17394
  {:else}
16908
17395
  <div
16909
17396
  class="wc-version-history-scroll flex flex-col gap-1 overflow-x-hidden {hasChatScroll ? 'overflow-y-auto' : 'overflow-y-visible'}"
16910
- style="{hasChatScroll ? 'max-height: 185px; margin-right: -4px; padding-right: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
17397
+ style="{hasChatScroll ? 'max-height: 185px; margin-inline-end: -4px; padding-inline-end: 4px;' : 'max-height: none;'} scrollbar-width: thin; scrollbar-color: rgba(0,0,0,0.2) transparent;"
16911
17398
  >
16912
17399
  {#each ps.publishHistory as record (record.id)}
16913
17400
  {@const rowVersion = Number(record.version)}
16914
17401
  {@const rowIsDraft = !(record.publishedAt ?? record.published_at)}
16915
17402
  {@const rowIsViewing = rowVersion === Number(viewingVersion)}
16916
17403
  {@const rowIsLive = !rowIsDraft && rowVersion === Number(panelPublishedVersion)}
16917
- {@const rowDateLabel = formatPublishHistoryDate(record)}
17404
+ {@const rowDateLabel = formatPublishHistoryDate(record, $languageTag)}
16918
17405
  {@const publishGate = getPublishGateForPanel(panelWidgetId, rowVersion)} <VersionDropdownRow
16919
17406
  versionLabel={'v' + rowVersion}
16920
17407
  commitSha={record.commitSha ?? record.commit_sha ?? null}
@@ -16979,9 +17466,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16979
17466
  <div class="flex items-center justify-between gap-2 min-w-0">
16980
17467
  <div class="generate-code-status-el text-xs flex-1 min-w-0 truncate {ps.lastGenerationFailed ? 'text-red-600' : 'text-gray-500'}">
16981
17468
  {#if ps.lastGenerationFailed}
16982
- <span class="text-red-500 font-medium">Generation Failed</span>
17469
+ <span class="text-red-500 font-medium">{$t('creator.codegen.generationFailed')}</span>
16983
17470
  {:else}
16984
- <span class="text-gray-400">Status:</span> {ps.generateCodeStatus || 'Ready'}
17471
+ <span class="text-gray-400">{$t('creator.status.label')}</span> {statusLabel(ps.generateCodeStatus, $t)}
16985
17472
  {/if}
16986
17473
  </div>
16987
17474
  </div>
@@ -16995,7 +17482,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
16995
17482
  size="sm"
16996
17483
  class="bg-red-600 hover:bg-red-700 text-white rounded-lg"
16997
17484
  >
16998
- Upgrade
17485
+ {$t('creator.general.upgrade')}
16999
17486
  </Button>
17000
17487
  <Button
17001
17488
  onclick={() => {
@@ -17007,14 +17494,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17007
17494
  size="sm"
17008
17495
  class="border-gray-300 text-gray-600 hover:bg-gray-50 rounded-lg"
17009
17496
  >
17010
- Dismiss
17497
+ {$t('creator.general.dismiss')}
17011
17498
  </Button>
17012
17499
  </div>
17013
17500
  </div>
17014
17501
  {/if}
17015
17502
  {#if ps.lastGenerationFailed}
17016
17503
  <div class="p-3 bg-red-50 border border-red-200" style="border-radius: 0;">
17017
- <p class="text-xs text-red-700 whitespace-pre-wrap">{ps.lastGenerationError}</p>
17504
+ <p class="text-xs text-red-700 whitespace-pre-wrap">{errorLabel(ps.lastGenerationError, $t)}</p>
17018
17505
  <div class="flex gap-2 mt-3 justify-center">
17019
17506
  {#if isPlanLimitMessage(ps.lastGenerationError)}
17020
17507
  <Button
@@ -17023,7 +17510,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17023
17510
  size="sm"
17024
17511
  class="bg-red-600 hover:bg-red-700 text-white rounded-lg"
17025
17512
  >
17026
- Upgrade
17513
+ {$t('creator.general.upgrade')}
17027
17514
  </Button>
17028
17515
  {:else}
17029
17516
  <Button
@@ -17038,7 +17525,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17038
17525
  size="sm"
17039
17526
  class="bg-red-600 hover:bg-red-700 text-white rounded-lg"
17040
17527
  >
17041
- Retry
17528
+ {$t('creator.common.retry')}
17042
17529
  </Button>
17043
17530
  {/if}
17044
17531
  <Button
@@ -17059,7 +17546,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17059
17546
  size="sm"
17060
17547
  class="border-gray-300 text-gray-600 hover:bg-gray-50 rounded-lg"
17061
17548
  >
17062
- Dismiss
17549
+ {$t('creator.general.dismiss')}
17063
17550
  </Button>
17064
17551
  </div>
17065
17552
  </div>
@@ -17126,6 +17613,9 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17126
17613
  />
17127
17614
  {/snippet}
17128
17615
  <Chat class="code-generation-chat w-full h-full rounded-none border-0"
17616
+ locale={locale}
17617
+ messages={chatMessages}
17618
+ storedLineLabel={(line) => conversationLineLabel(line, $t)}
17129
17619
  actionBarExtras={generationOptionChecks}
17130
17620
  style="height: 100%; min-height: {chatUserHeight == null ? CHAT_AUTO_MIN_HEIGHT : CHAT_MIN_HEIGHT}px;"
17131
17621
  resizeExpandsContainer={true}
@@ -17138,7 +17628,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17138
17628
  id: panelWidgetId,
17139
17629
  type: ContextType.FRAME,
17140
17630
  parentId: panelWidgetId,
17141
- title: panelWidget?.name || 'Widget',
17631
+ title: panelWidget?.name || $t('creator.widget.fallbackName'),
17142
17632
  }}
17143
17633
  config={{
17144
17634
  features: {
@@ -17163,6 +17653,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17163
17653
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
17164
17654
  onSendMessage={(content, attachments) => handleChatSendMessage(content, attachments, panelWidgetId)}
17165
17655
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
17656
+ onUpgradePlans={openUpgradePlans}
17166
17657
  onUploadChatFile={handleChatUploadFile}
17167
17658
  onTakeScreenshot={() => handleChatScreenshot(panelWidgetId)}
17168
17659
  isCompleted={!!conversationCompletedByWidgetId[panelWidgetId]}
@@ -17208,7 +17699,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17208
17699
  {#if panelHasUnpublishedChanges}
17209
17700
  <div class="edit-unpublished-banner-ct mx-3 mt-2 px-2 py-1.5 rounded-md border border-amber-200 bg-amber-50 text-amber-800 text-xs flex items-center gap-2 shrink-0">
17210
17701
  <p class="edit-unpublished-banner-text leading-snug min-w-0 flex-1 truncate">
17211
- <strong class="font-semibold">Newer than Live v{ps.lastPublishedVersion ?? '—'}</strong>
17702
+ <strong class="font-semibold">{$t('creator.preview.newerThanLive', { version: ps.lastPublishedVersion ?? '—' })}</strong>
17212
17703
  {#if debugMode}
17213
17704
  <span class="font-mono">{formatCommitShaShort(ps.lastCommitId)}</span>
17214
17705
  ahead of
@@ -17227,7 +17718,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17227
17718
  {#if isPublishing && publishingWidgetId === panelWidgetId}
17228
17719
  <span>⏳</span>
17229
17720
  {:else}
17230
- <span>Retry publish</span>
17721
+ <span>{$t('creator.publish.retryPublish')}</span>
17231
17722
  {/if}
17232
17723
  </Button>
17233
17724
  </div>
@@ -17235,8 +17726,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17235
17726
 
17236
17727
  {#if isEditStepWithoutPublishForPanel(panelWidgetId)}
17237
17728
  <div class="edit-not-published-banner-ct mx-3 mt-2 px-3 py-2 rounded-md border border-amber-200 bg-amber-50 text-amber-800 text-xs">
17238
- <strong class="font-semibold">Not published yet.</strong>
17239
- Generate on Create, preview the result, then Publish when you are ready.
17729
+ <strong class="font-semibold">{$t('creator.publish.notPublishedYet')}</strong>
17730
+ {$t('creator.publish.generateOnCreatePreviewThe')}
17240
17731
  </div>
17241
17732
  {/if}
17242
17733
 
@@ -17247,11 +17738,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17247
17738
  <div class="composition-builder-unavailable-header flex items-start gap-2">
17248
17739
  <span class="text-xl shrink-0" aria-hidden="true">⚠️</span>
17249
17740
  <div class="composition-builder-unavailable-copy min-w-0">
17250
- <p class="text-sm font-semibold">Preview builder is unavailable</p>
17741
+ <p class="text-sm font-semibold">{$t('creator.codegen.previewBuilderIsUnavailable')}</p>
17251
17742
  <p class="text-xs mt-1 text-amber-800 leading-relaxed">
17252
- The widget code was saved, but the preview service could not compile it. This is not a Svelte syntax error. Go back to Create and use Rebuild.
17743
+ {$t('creator.codegen.theWidgetCodeWasSaved')}
17253
17744
  </p>
17254
- <p class="text-[11px] mt-2 text-amber-700 wrap-break-word">{getPanelPreviewCompileError(panelWidgetId)}</p>
17745
+ <p class="text-[11px] mt-2 text-amber-700 wrap-break-word">{errorLabel(getPanelPreviewCompileError(panelWidgetId), $t)}</p>
17255
17746
  </div>
17256
17747
  </div>
17257
17748
  <Button
@@ -17263,7 +17754,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17263
17754
  void getWidgetDetailsRef(panelWidgetId)?.triggerBuildFromRepo?.({ force: true });
17264
17755
  }}
17265
17756
  >
17266
- 🔄 Rebuild in Create
17757
+ {$t('creator.codegen.rebuildInCreate')}
17267
17758
  </Button>
17268
17759
  </div>
17269
17760
  {:else if panelHasCompileErrorState}
@@ -17271,11 +17762,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17271
17762
  <div class="composition-compile-error-header flex items-start gap-2">
17272
17763
  <span class="text-xl shrink-0" aria-hidden="true">⚠️</span>
17273
17764
  <div class="composition-compile-error-copy min-w-0">
17274
- <p class="text-sm font-semibold">Code does not compile</p>
17765
+ <p class="text-sm font-semibold">{$t('creator.codegen.codeDoesNotCompile')}</p>
17275
17766
  <p class="text-xs mt-1 text-red-800 leading-relaxed">
17276
- Fix the syntax error in Create (Step 1), then publish to unlock composition editing.
17767
+ {$t('creator.composition.fixTheSyntaxErrorIn')}
17277
17768
  </p>
17278
- <p class="text-[11px] font-mono mt-2 text-red-700 wrap-break-word">{getPanelPreviewCompileError(panelWidgetId)}</p>
17769
+ <p class="text-[11px] font-mono mt-2 text-red-700 wrap-break-word">{errorLabel(getPanelPreviewCompileError(panelWidgetId), $t)}</p>
17279
17770
  </div>
17280
17771
  </div>
17281
17772
  <Button
@@ -17283,7 +17774,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17283
17774
  class="fix-compile-in-create-btn w-fit"
17284
17775
  onclick={() => fixWidgetCompileError(panelWidgetId, getPanelPreviewCompileError(panelWidgetId))}
17285
17776
  >
17286
- 🔧 Fix in Create
17777
+ {$t('creator.general.fixInCreate')}
17287
17778
  </Button>
17288
17779
  </div>
17289
17780
  {/if}
@@ -17291,13 +17782,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17291
17782
 
17292
17783
  {#if panelHasCompileErrorState}
17293
17784
  <div class="composition-compile-error-ct mx-3 mt-2 px-3 py-3 rounded-md border border-amber-200 bg-amber-50 text-amber-900 text-xs">
17294
- <strong class="font-semibold">Latest code does not compile.</strong>
17295
- <span class="ml-1">Preview may show Live v{ps.lastPublishedVersion} while HEAD is broken.</span>
17785
+ <strong class="font-semibold">{$t('creator.codegen.latestCodeDoesNotCompile')}</strong>
17786
+ <span class="ms-1">{$t('creator.preview.mayShowLive', { version: ps.lastPublishedVersion })}</span>
17296
17787
  <button
17297
17788
  type="button"
17298
- class="ml-2 underline font-medium cursor-pointer"
17789
+ class="ms-2 underline font-medium cursor-pointer"
17299
17790
  onclick={() => fixWidgetCompileError(panelWidgetId, getPanelPreviewCompileError(panelWidgetId))}
17300
- >Fix in Create</button>
17791
+ >{$t('creator.general.fixInCreate2')}</button>
17301
17792
  </div>
17302
17793
  {/if}
17303
17794
 
@@ -17305,20 +17796,21 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17305
17796
  {#if ps.compositionDesignSchema || ps.compositionContentSchema}
17306
17797
  <div class="compositions-bar flex items-center gap-2 px-3 py-2 bg-gray-50 shrink-0 flex-nowrap">
17307
17798
  <!-- Composition selector dropdown -->
17799
+ <!-- A visitor of a partner can add and rename compositions but not delete them (the gateway does not let a session do that), so the delete control is not offered. -->
17308
17800
  <SelectorDropdown
17309
17801
  class="compositions-selector"
17310
17802
  items={getCompositionDropdownItemsFromList(ps.compositions)}
17311
17803
  selectedId={ps.selectedComposition?.id || null}
17312
- label="Compositions:"
17804
+ label={$t('creator.composition.compositions')}
17313
17805
  labelPosition="inline"
17314
- placeholder={ps.selectedComposition?.name || 'Select composition'}
17315
- newButtonLabel="New"
17806
+ placeholder={ps.selectedComposition?.name || $t('creator.composition.selectComposition')}
17807
+ newButtonLabel={$t('creator.common.new')}
17316
17808
  accentColor="#3B82F6"
17317
17809
  nameWidth="140px"
17318
17810
  loading={isPanelFocused && compositionsLoading}
17319
17811
  allowRename={!!ps.selectedComposition}
17320
17812
  onselect={(item) => { if (!isPanelFocused) focusWidgetPanel(panelWidgetId); handleCompositionDropdownSelect(item); }}
17321
- ondelete={(item) => { if (!isPanelFocused) focusWidgetPanel(panelWidgetId); handleCompositionDropdownDelete(item); }}
17813
+ ondelete={partnerMode ? undefined : (item) => { if (!isPanelFocused) focusWidgetPanel(panelWidgetId); handleCompositionDropdownDelete(item); }}
17322
17814
  onnew={() => { if (!isPanelFocused) focusWidgetPanel(panelWidgetId); handleCompositionDropdownNew(); }}
17323
17815
  onrename={(id, name) => { if (!isPanelFocused) focusWidgetPanel(panelWidgetId); handleCompositionDropdownRename(id, name); }}
17324
17816
  />
@@ -17347,11 +17839,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17347
17839
  </svg>
17348
17840
  {/if}
17349
17841
  {#if compositionSaving}
17350
- Saving
17842
+ {$t('creator.general.saving2')}
17351
17843
  {:else if ps.selectedComposition}
17352
- {ps.compositionDirty ? 'Save' : 'Saved'}
17844
+ {ps.compositionDirty ? $t('creator.general.save') : $t('creator.general.saved')}
17353
17845
  {:else}
17354
- Save
17846
+ {$t('creator.general.save')}
17355
17847
  {/if}
17356
17848
  </button>
17357
17849
  </div>
@@ -17361,10 +17853,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17361
17853
  {#if deletingCompositionId}
17362
17854
  <div class="compositions-delete-confirm fixed inset-0 flex items-center justify-center bg-black/30" style="z-index: 99999;">
17363
17855
  <div class="bg-white rounded-lg shadow-lg p-4 max-w-xs text-center">
17364
- <p class="text-sm text-gray-700 mb-3">Delete this composition?</p>
17856
+ <p class="text-sm text-gray-700 mb-3">{$t('creator.composition.deleteThisComposition')}</p>
17365
17857
  <div class="flex gap-2 justify-center">
17366
- <Button variant="outline" size="sm" onclick={() => deletingCompositionId = null}>Cancel</Button>
17367
- <Button variant="default" size="sm" onclick={deleteComposition} class="bg-red-600 hover:bg-red-700 border-red-600">Delete</Button>
17858
+ <Button variant="outline" size="sm" onclick={() => deletingCompositionId = null}>{$t('creator.general.cancel')}</Button>
17859
+ <Button variant="default" size="sm" onclick={deleteComposition} class="bg-red-600 hover:bg-red-700 border-red-600">{$t('creator.common.delete')}</Button>
17368
17860
  </div>
17369
17861
  </div>
17370
17862
  </div>
@@ -17387,7 +17879,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17387
17879
  }}
17388
17880
  class="text-xs px-2 py-1 rounded bg-blue-100 text-blue-700 hover:bg-blue-200 w-fit transition-colors"
17389
17881
  >
17390
- Retry
17882
+ {$t('creator.common.retry')}
17391
17883
  </button>
17392
17884
  </div>
17393
17885
  {:else if ps.compositionDesignSchema || ps.compositionContentSchema}
@@ -17410,6 +17902,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17410
17902
  height="620px"
17411
17903
  showDragHandle={false}
17412
17904
  enableDrag={false}
17905
+ {mediaLibrary}
17413
17906
  defaultTab="design"
17414
17907
  on:propertyChange={handleEditorPropertyChange}
17415
17908
  on:contentItemsChanged={handleEditorContentItemsChanged}
@@ -17418,8 +17911,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17418
17911
  </div>
17419
17912
  {:else}
17420
17913
  <div class="flex flex-col items-center justify-center py-8 text-center">
17421
- <p class="text-sm text-gray-500">No editable settings available yet.</p>
17422
- <p class="text-xs text-gray-400 mt-1">Generate code first to customize colors, text, and content.</p>
17914
+ <p class="text-sm text-gray-500">{$t('creator.general.noEditableSettingsAvailableYet')}</p>
17915
+ <p class="text-xs text-gray-400 mt-1">{$t('creator.codegen.generateCodeFirstToCustomize')}</p>
17423
17916
  </div>
17424
17917
  {/if}
17425
17918
 
@@ -17428,8 +17921,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17428
17921
  {:else}
17429
17922
  <div class="flex flex-col items-center justify-center py-12 text-center px-4">
17430
17923
  <div class="text-3xl mb-3">🎨</div>
17431
- <p class="text-sm font-medium text-gray-600">No widget code yet</p>
17432
- <p class="text-xs text-gray-400 mt-1">Go to Step 1 (Create) to generate widget code first.</p>
17924
+ <p class="text-sm font-medium text-gray-600">{$t('creator.codegen.noWidgetCodeYet')}</p>
17925
+ <p class="text-xs text-gray-400 mt-1">{$t('creator.codegen.goToStep1Create')}</p>
17433
17926
  </div>
17434
17927
  {/if}
17435
17928
  </div>
@@ -17445,29 +17938,29 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17445
17938
  {#if panelWidgetId && ps.lastPublishedVersion !== null}
17446
17939
  <div class="embed-section flex flex-col gap-4 p-3">
17447
17940
  <div class="embed-section-header">
17448
- <h3 class="text-sm font-semibold text-gray-700">Embed Your Widget</h3>
17941
+ <h3 class="text-sm font-semibold text-gray-700">{$t('creator.embed.embedYourWidget')}</h3>
17449
17942
  {#if ps.lastPublishedVersion !== null}
17450
- <p class="text-xs text-gray-500 mt-1">Set dimensions and copy the embed code below.</p>
17943
+ <p class="text-xs text-gray-500 mt-1">{$t('creator.embed.setDimensionsAndCopyThe')}</p>
17451
17944
  {/if}
17452
17945
  </div>
17453
17946
 
17454
17947
  {#if ps.lastPublishedVersion === null}
17455
17948
  <div class="embed-unpublished-ct flex flex-col items-center justify-center py-8 text-center px-4">
17456
17949
  <div class="text-3xl mb-3">📦</div>
17457
- <p class="text-sm font-medium text-gray-600">Widget not published yet</p>
17458
- <p class="text-xs text-gray-400 mt-1">Publish your widget from the Create step to generate an embed code.</p>
17950
+ <p class="text-sm font-medium text-gray-600">{$t('creator.publish.widgetNotPublishedYet')}</p>
17951
+ <p class="text-xs text-gray-400 mt-1">{$t('creator.publish.publishYourWidgetFromThe')}</p>
17459
17952
  </div>
17460
17953
  {:else}
17461
17954
 
17462
17955
  <!-- Embed Dimensions -->
17463
17956
  <div class="embed-dimensions-ct flex flex-col gap-2">
17464
- <label class="text-xs font-medium text-gray-600" for="embed-width-input">Dimensions</label>
17957
+ <label class="text-xs font-medium text-gray-600" for="embed-width-input">{$t('creator.general.dimensions')}</label>
17465
17958
  <div class="embed-dimensions-row flex items-center gap-2">
17466
17959
  <div class="embed-dim-input flex items-center gap-1">
17467
- <span class="text-[10px] text-gray-400 font-medium">W</span>
17960
+ <span class="text-[10px] text-gray-400 font-medium">{$t('creator.general.w')}</span>
17468
17961
  <input
17469
17962
  id="embed-width-input"
17470
- aria-label="Embed width"
17963
+ aria-label={$t('creator.embed.embedWidth')}
17471
17964
  type="number"
17472
17965
  min="100"
17473
17966
  max="4000"
@@ -17484,10 +17977,10 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17484
17977
  </div>
17485
17978
  <span class="text-gray-300 text-xs">×</span>
17486
17979
  <div class="embed-dim-input flex items-center gap-1">
17487
- <span class="text-[10px] text-gray-400 font-medium">H</span>
17980
+ <span class="text-[10px] text-gray-400 font-medium">{$t('creator.general.h')}</span>
17488
17981
  <input
17489
17982
  id="embed-height-input"
17490
- aria-label="Embed height"
17983
+ aria-label={$t('creator.embed.embedHeight')}
17491
17984
  type="number"
17492
17985
  min="50"
17493
17986
  max="4000"
@@ -17502,14 +17995,14 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17502
17995
  class="w-16 text-xs px-1.5 py-1 rounded border border-gray-300 text-center"
17503
17996
  />
17504
17997
  </div>
17505
- <span class="text-[10px] text-gray-400">px</span>
17998
+ <span class="text-[10px] text-gray-400">{$t('creator.general.px')}</span>
17506
17999
  {#if embedDimensionsChanged && selectedComposition}
17507
18000
  <button
17508
18001
  type="button"
17509
- class="embed-save-dims-btn ml-auto px-2.5 py-1 text-[10px] font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50 transition-colors cursor-pointer"
18002
+ class="embed-save-dims-btn ms-auto px-2.5 py-1 text-[10px] font-medium rounded border border-blue-500 text-blue-600 hover:bg-blue-50 transition-colors cursor-pointer"
17510
18003
  onclick={saveEmbedDimensions}
17511
18004
  >
17512
- {isSavingEmbedDims ? 'Saving' : 'Save'}
18005
+ {isSavingEmbedDims ? $t('creator.general.saving2') : $t('creator.general.save')}
17513
18006
  </button>
17514
18007
  {/if}
17515
18008
  </div>
@@ -17534,22 +18027,22 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17534
18027
  <div class="embed-code-ct flex flex-col gap-2">
17535
18028
  <div class="embed-code-header flex items-center justify-between">
17536
18029
  <!-- svelte-ignore a11y_label_has_associated_control -->
17537
- <label class="text-xs font-medium text-gray-600">Embed Code ({EMBED_FORMAT_LABELS[effectiveFormat]})</label>
18030
+ <label class="text-xs font-medium text-gray-600">{$t('creator.embed.codeTitle', { format: embedFormatLabel(effectiveFormat, $t) })}</label>
17538
18031
  <!-- svelte-ignore a11y_consider_explicit_label -->
17539
18032
  <button
17540
18033
  type="button"
17541
- title="Copy Embed Code"
18034
+ title={$t('creator.embed.copyEmbedCode')}
17542
18035
  onclick={() => {
17543
18036
  navigator.clipboard.writeText(effectiveEmbedCode);
17544
- showToast('success', 'Embed code copied!', { duration: 2000 });
18037
+ showToast('success', $t('creator.embed.copied'), { duration: 2000 });
17545
18038
  }}
17546
18039
  class="embed-copy-btn flex items-center gap-1 px-2 py-0.5 text-[10px] font-medium rounded text-gray-500 hover:text-gray-700 hover:bg-gray-100 transition-colors cursor-pointer"
17547
18040
  >
17548
18041
  <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><rect x="9" y="9" width="13" height="13" rx="2" ry="2" stroke-width="2"/><path d="M5 15H4a2 2 0 01-2-2V4a2 2 0 012-2h9a2 2 0 012 2v1" stroke-width="2"/></svg>
17549
- Copy
18042
+ {$t('creator.general.copy')}
17550
18043
  </button>
17551
18044
  </div>
17552
- <div class="embed-format-selector flex items-center gap-1 mb-1" role="tablist" aria-label="Embed format">
18045
+ <div class="embed-format-selector flex items-center gap-1 mb-1" role="tablist" aria-label={$t('creator.embed.embedFormat')}>
17553
18046
  {#each EMBED_FORMATS as fmt}
17554
18047
  <button
17555
18048
  type="button"
@@ -17558,13 +18051,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17558
18051
  class="embed-format-tab px-2.5 py-1 text-[11px] font-medium rounded border transition-colors {embedFormat === fmt ? 'border-blue-500 bg-blue-50 text-blue-700' : 'border-gray-300 text-gray-600 hover:bg-gray-50'}"
17559
18052
  onclick={() => { embedFormat = fmt; }}
17560
18053
  >
17561
- {EMBED_FORMAT_LABELS[fmt]}
18054
+ {embedFormatLabel(fmt, $t)}
17562
18055
  </button>
17563
18056
  {/each}
17564
18057
  </div>
17565
18058
  {#if embedFormat === 'web-component' && effectiveFormat === 'iframe'}
17566
18059
  <p class="embed-format-fallback-note text-[10px] text-amber-600 bg-amber-50 border border-amber-200 rounded px-2 py-1">
17567
- Web Component format requires a composition. Select a composition first — falling back to iframe for direct widget URL.
18060
+ {$t('creator.composition.webComponentFormatRequiresA')}
17568
18061
  </p>
17569
18062
  {/if}
17570
18063
  <div class="embed-code-block max-h-40 overflow-y-auto overflow-x-hidden rounded-lg scrollbar-thin">
@@ -17575,7 +18068,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17575
18068
  <!-- Direct URL -->
17576
18069
  <!-- svelte-ignore a11y_label_has_associated_control -->
17577
18070
  <div class="embed-url-ct flex flex-col gap-2">
17578
- <label class="text-xs font-medium text-gray-600">{selectedComposition ? 'Composition URL' : 'Direct Widget URL'}</label>
18071
+ <label class="text-xs font-medium text-gray-600">{selectedComposition ? $t('creator.composition.compositionUrl') : $t('creator.widget.directWidgetUrl')}</label>
17579
18072
  <div class="flex items-center gap-2">
17580
18073
  <input
17581
18074
  type="text"
@@ -17588,7 +18081,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17588
18081
  onclick={() => openEmbedTestPage(testPageHref)}
17589
18082
  class="px-3 py-1.5 text-xs rounded bg-blue-600 text-white hover:bg-blue-700 transition-colors whitespace-nowrap cursor-pointer"
17590
18083
  >
17591
- Test Page ↗
18084
+ {$t('creator.general.testPage')}
17592
18085
  </button>
17593
18086
  </div>
17594
18087
  </div>
@@ -17599,8 +18092,8 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17599
18092
  {:else}
17600
18093
  <div class="flex flex-col items-center justify-center py-12 text-center px-4">
17601
18094
  <div class="text-3xl mb-3">🔗</div>
17602
- <p class="text-sm font-medium text-gray-600">Widget not published yet</p>
17603
- <p class="text-xs text-gray-400 mt-1">Publish your widget from the Create step to get embed code.</p>
18095
+ <p class="text-sm font-medium text-gray-600">{$t('creator.publish.widgetNotPublishedYet')}</p>
18096
+ <p class="text-xs text-gray-400 mt-1">{$t('creator.publish.publishYourWidgetFromTheCreate')}</p>
17604
18097
  </div>
17605
18098
  {/if}
17606
18099
  </div>
@@ -17626,12 +18119,12 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17626
18119
  <!-- svelte-ignore a11y_img_redundant_alt -->
17627
18120
  <img
17628
18121
  src={lightboxImage}
17629
- alt="Zoomed reference"
18122
+ alt={$t('creator.general.zoomedReference')}
17630
18123
  style="max-width: 90vw; max-height: 90vh; object-fit: contain; border-radius: 0.5rem; box-shadow: 0 25px 50px rgba(0,0,0,0.25);"
17631
18124
  />
17632
18125
  <button
17633
18126
  type="button"
17634
- style="position: absolute; top: 1rem; right: 1rem; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.9); color: #374151; border-radius: 9999px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border: none; cursor: pointer; font-size: 1.125rem; font-weight: 700;"
18127
+ style="position: absolute; top: 1rem; inset-inline-end: 1rem; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center; background: rgba(255,255,255,0.9); color: #374151; border-radius: 9999px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); border: none; cursor: pointer; font-size: 1.125rem; font-weight: 700;"
17635
18128
  onclick={(e) => { e.stopPropagation(); lightboxImage = null; }}
17636
18129
  >✕</button>
17637
18130
  </div>
@@ -17685,15 +18178,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17685
18178
  <!-- Dialog.Root (bits-ui AlertDialogRoot) exposes no class prop — styling hooks
17686
18179
  live on Content/Header below. -->
17687
18180
  <Dialog.Root bind:open={deleteDialogOpen} onOpenChange={(open) => { if (!open) handleDeleteDialogResponse('cancel'); }}>
17688
- <Dialog.Content class="confirm-delete-dialog-content max-w-md bg-white z-9999">
18181
+ <Dialog.Content closeLabel={$t('creator.common.close')} class="confirm-delete-dialog-content max-w-md bg-white z-9999">
17689
18182
  <Dialog.Header class="confirm-delete-dialog-header">
17690
- <Dialog.Title>Delete Widget Shape</Dialog.Title>
18183
+ <Dialog.Title>{$t('creator.widget.deleteWidgetShape')}</Dialog.Title>
17691
18184
  <Dialog.Description>
17692
- {#if deleteDialogStep === 'confirm-remove'}
17693
- Remove <strong>"{deleteDialogWidgetName}"</strong> from the canvas? This also deletes the associated widget.
17694
- {:else}
17695
- Also delete the widget <strong>"{deleteDialogWidgetName}"</strong> from the database?
17696
- {/if}
18185
+ {#each sentenceParts(deleteDialogStep === 'confirm-remove' ? 'creator.dialog.removeShape' : 'creator.dialog.alsoDeleteWidget', ['name'], $t) as part}
18186
+ {#if 'text' in part}{part.text}{:else}<strong>"{deleteDialogWidgetName}"</strong>{/if}
18187
+ {/each}
17697
18188
  </Dialog.Description>
17698
18189
  </Dialog.Header>
17699
18190
 
@@ -17703,23 +18194,23 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17703
18194
  type="button"
17704
18195
  class="px-4 py-2 text-sm rounded-lg border border-gray-300 hover:bg-gray-100 cursor-pointer"
17705
18196
  onclick={() => handleDeleteDialogResponse('cancel')}
17706
- >Cancel</button>
18197
+ >{$t('creator.general.cancel')}</button>
17707
18198
  <button
17708
18199
  type="button"
17709
18200
  class="px-4 py-2 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white cursor-pointer"
17710
18201
  onclick={() => handleDeleteDialogResponse('remove-and-ask-db')}
17711
- >Delete</button>
18202
+ >{$t('creator.common.delete')}</button>
17712
18203
  {:else if ASK_DELETE_FROM_DB_CONFIRM}
17713
18204
  <button
17714
18205
  type="button"
17715
18206
  class="px-4 py-2 text-sm rounded-lg border border-gray-300 hover:bg-gray-100 cursor-pointer"
17716
18207
  onclick={() => handleDeleteDialogResponse('keep-in-db')}
17717
- >Keep in Database</button>
18208
+ >{$t('creator.general.keepInDatabase')}</button>
17718
18209
  <button
17719
18210
  type="button"
17720
18211
  class="px-4 py-2 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white cursor-pointer"
17721
18212
  onclick={() => handleDeleteDialogResponse('delete-from-db')}
17722
- >Delete from Database</button>
18213
+ >{$t('creator.general.deleteFromDatabase')}</button>
17723
18214
  {/if}
17724
18215
  </div>
17725
18216
  </Dialog.Content>
@@ -17727,24 +18218,24 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17727
18218
 
17728
18219
  <!-- Delete Canvas Confirmation Dialog -->
17729
18220
  <Dialog.Root bind:open={showDeleteCanvasDialog} onOpenChange={(open) => { if (!open) { showDeleteCanvasDialog = false; deleteCanvasTarget = null; } }}>
17730
- <Dialog.Content class="confirm-delete-canvas-dialog-content max-w-sm bg-white z-9999">
18221
+ <Dialog.Content closeLabel={$t('creator.common.close')} class="confirm-delete-canvas-dialog-content max-w-sm bg-white z-9999">
17731
18222
  <Dialog.Header class="confirm-delete-canvas-dialog-header">
17732
- <Dialog.Title>Delete Canvas</Dialog.Title>
18223
+ <Dialog.Title>{$t('creator.canvas.deleteCanvas')}</Dialog.Title>
17733
18224
  <Dialog.Description>
17734
- Are you sure you want to delete <strong>"{deleteCanvasTarget?.name || ''}"</strong>? This action cannot be undone.
18225
+ {#each sentenceParts('creator.dialog.deleteCanvas', ['name'], $t) as part}
18226
+ {#if 'text' in part}{part.text}{:else}<strong>"{deleteCanvasTarget?.name || ''}"</strong>{/if}
18227
+ {/each}
17735
18228
  </Dialog.Description>
17736
18229
  </Dialog.Header>
17737
18230
 
17738
18231
  {#if deleteCanvasPreviewLoading}
17739
18232
  <p class="confirm-delete-canvas-preview-loading text-sm text-gray-500 pt-2">
17740
- Checking what will be deleted…
18233
+ {$t('creator.general.checkingWhatWillBeDeleted')}
17741
18234
  </p>
17742
18235
  {:else if deleteCanvasPreview && deleteCanvasPreview.widgetCount > 0}
17743
18236
  <div class="confirm-delete-canvas-preview pt-2">
17744
18237
  <p class="text-sm text-gray-700">
17745
- This will also delete
17746
- <strong>{deleteCanvasPreview.widgetCount}</strong>
17747
- {deleteCanvasPreview.widgetCount === 1 ? 'widget' : 'widgets'} on this canvas:
18238
+ {$t('creator.dialog.alsoDeleteWidgets', { count: deleteCanvasPreview.widgetCount })}
17748
18239
  </p>
17749
18240
  <ul class="confirm-delete-canvas-preview-groups mt-2 space-y-1.5 max-h-40 overflow-y-auto scrollbar-thin text-sm">
17750
18241
  {#each deleteCanvasPreview.groups as group}
@@ -17759,7 +18250,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17759
18250
  </ul>
17760
18251
  {#if deleteCanvasPreview.groups.length > 1}
17761
18252
  <p class="confirm-delete-canvas-preview-warning text-xs text-amber-700 mt-2">
17762
- These widgets belong to more than one project.
18253
+ {$t('creator.widget.theseWidgetsBelongToMore')}
17763
18254
  </p>
17764
18255
  {/if}
17765
18256
  </div>
@@ -17774,12 +18265,12 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17774
18265
  type="button"
17775
18266
  class="px-4 py-2 text-sm rounded-lg border border-gray-300 hover:bg-gray-100 cursor-pointer"
17776
18267
  onclick={() => { showDeleteCanvasDialog = false; deleteCanvasTarget = null; deleteCanvasError = ''; }}
17777
- >Cancel</button>
18268
+ >{$t('creator.general.cancel')}</button>
17778
18269
  <button
17779
18270
  type="button"
17780
18271
  class="px-4 py-2 text-sm rounded-lg bg-red-600 hover:bg-red-700 text-white cursor-pointer"
17781
18272
  onclick={handleDeleteCanvasConfirm}
17782
- >Delete</button>
18273
+ >{$t('creator.common.delete')}</button>
17783
18274
  </div>
17784
18275
  </Dialog.Content>
17785
18276
  </Dialog.Root>
@@ -17792,29 +18283,29 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17792
18283
  if (!open) confirmGenerateWidgetId = null;
17793
18284
  }}
17794
18285
  >
17795
- <Dialog.Content class="confirm-generate-dialog-content max-w-lg bg-white z-9999">
18286
+ <Dialog.Content closeLabel={$t('creator.common.close')} class="confirm-generate-dialog-content max-w-lg bg-white z-9999">
17796
18287
  <Dialog.Header class="confirm-generate-dialog-header">
17797
- <Dialog.Title>Confirm Code Generation</Dialog.Title>
18288
+ <Dialog.Title>{$t('creator.codegen.confirmCodeGeneration')}</Dialog.Title>
17798
18289
  <Dialog.Description>
17799
18290
  {promptImages.length > 0
17800
- ? 'Review the prompt and reference image before starting generation.'
17801
- : 'Describe the widget you want. You can attach a screenshot first if you have a design.'}
18291
+ ? $t('creator.codegen.reviewThePromptAndReference')
18292
+ : $t('creator.codegen.describeTheWidgetYouWant')}
17802
18293
  </Dialog.Description>
17803
18294
  </Dialog.Header>
17804
18295
  <div class="flex flex-col gap-3 py-3 px-1">
17805
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">Prompt</div>
18296
+ <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.prompt')}</div>
17806
18297
  <textarea
17807
18298
  bind:value={codeGenerationPrompt}
17808
18299
  class="w-full min-h-[80px] max-h-[160px] rounded-md border border-gray-300 p-2 text-sm resize-y focus:outline-none focus:ring-2 focus:ring-blue-400 focus:border-transparent"
17809
- placeholder="Describe what you want..."
18300
+ placeholder={$t('creator.general.describeWhatYouWant')}
17810
18301
  ></textarea>
17811
18302
  {#if promptImages.length > 0}
17812
- <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">Reference Images ({promptImages.length})</div>
18303
+ <div class="text-xs font-medium text-gray-500 uppercase tracking-wide">{$t('creator.codegen.referenceImages', { count: promptImages.length })}</div>
17813
18304
  <div class="flex gap-2 flex-wrap">
17814
18305
  {#each promptImages as img, i}
17815
18306
  <div class="relative">
17816
- <span class="absolute top-0.5 left-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{i + 1}</span>
17817
- <img src={img} alt="Reference {i + 1}" class="w-16 h-16 rounded border border-gray-200 object-cover" />
18307
+ <span class="absolute top-0.5 start-0.5 z-10 w-4 h-4 flex items-center justify-center rounded-full bg-blue-600 text-white text-[9px] font-bold shadow">{i + 1}</span>
18308
+ <img src={img} alt={$t('creator.codegen.referenceNumber', { number: i + 1 })} class="w-16 h-16 rounded border border-gray-200 object-cover" />
17818
18309
  </div>
17819
18310
  {/each}
17820
18311
  </div>
@@ -17825,7 +18316,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17825
18316
  confirmGenerateDialogOpen = false;
17826
18317
  syncPromptToChatDraft();
17827
18318
  }}>
17828
- Edit Prompt First
18319
+ {$t('creator.codegen.editPromptFirst')}
17829
18320
  </Button>
17830
18321
  <Button variant="default" size="sm" onclick={() => {
17831
18322
  const targetWidgetId = confirmGenerateWidgetId ?? selectedWidgetId ?? undefined;
@@ -17833,7 +18324,7 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17833
18324
  confirmGenerateWidgetId = null;
17834
18325
  generateCode({ widgetId: targetWidgetId });
17835
18326
  }}>
17836
- 🚀 Generate Now
18327
+ {$t('creator.codegen.generateNow')}
17837
18328
  </Button>
17838
18329
  </div>
17839
18330
  </Dialog.Content>