@widgetic/creator 0.4.8 → 0.4.10

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.
@@ -36,6 +36,7 @@
36
36
  import { parseVersionPreviewError } from './utils/versionPreviewError.js';
37
37
  import { widgetBuilderRequestInit } from './utils/widgetBuilderRequest.js';
38
38
  import { gzipRequestBodyMiddleware } from './utils/gzipRequestMiddleware.js';
39
+ import type { SelectedWidgetElementReference } from './utils/widgetElementSelector.js';
39
40
  import BrandKitPanel from './components/BrandKitPanel.svelte';
40
41
 
41
42
  /**
@@ -589,38 +590,33 @@
589
590
 
590
591
  // console.log('[SDK] Initializing authenticated clients with new token');
591
592
  setWebsocketApiUrl(apiRoot ?? null);
592
-
593
- canvasesClient = apiBasePath
594
- ? new CanvasesApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
595
- : new CanvasesApi({ accessToken: token, middleware: clientMiddleware });
596
- widgetsClient = apiBasePath
597
- ? new WidgetsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
598
- : new WidgetsApi({ accessToken: token, middleware: clientMiddleware });
599
- agentClient = apiBasePath
600
- ? new AgentApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
601
- : new AgentApi({ accessToken: token, middleware: clientMiddleware });
602
- operationsClient = apiBasePath
603
- ? new OperationsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
604
- : new OperationsApi({ accessToken: token, middleware: clientMiddleware });
605
- conversationsClient = apiBasePath
606
- ? new ConversationsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
607
- : new ConversationsApi({ accessToken: token, middleware: clientMiddleware });
608
- messagesClient = apiBasePath
609
- ? new MessagesApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
610
- : new MessagesApi({ accessToken: token, middleware: clientMiddleware });
611
- compositionsClient = apiBasePath
612
- ? new CompositionsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
613
- : new CompositionsApi({ accessToken: token, middleware: clientMiddleware });
614
- uploadsClient = apiBasePath
615
- ? new UploadsApi({ basePath: apiBasePath, accessToken: token, middleware: clientMiddleware })
616
- : new UploadsApi({ accessToken: token, middleware: clientMiddleware });
593
+
594
+ // Bearer only. These routes answer the preflight without
595
+ // Access-Control-Allow-Credentials, so a cookie on the call is blocked.
596
+ const clientOptions = {
597
+ ...(apiBasePath ? { basePath: apiBasePath } : {}),
598
+ accessToken: token,
599
+ credentials: 'omit' as const,
600
+ middleware: clientMiddleware
601
+ };
602
+
603
+ canvasesClient = new CanvasesApi(clientOptions);
604
+ widgetsClient = new WidgetsApi(clientOptions);
605
+ agentClient = new AgentApi(clientOptions);
606
+ operationsClient = new OperationsApi(clientOptions);
607
+ conversationsClient = new ConversationsApi(clientOptions);
608
+ messagesClient = new MessagesApi(clientOptions);
609
+ compositionsClient = new CompositionsApi(clientOptions);
610
+ uploadsClient = new UploadsApi(clientOptions);
617
611
  // The trial and credit counter is an account matter: a visitor of a partner has none, and a session may not ask for it
618
612
  // (so there is no client for it at all, and nothing can ask by mistake).
619
613
  usersClient = partnerMode
620
614
  ? null
621
- : apiBasePath
622
- ? new UsersApi({ basePath: apiBasePath, accessToken: token })
623
- : new UsersApi({ accessToken: token });
615
+ : new UsersApi({
616
+ ...(apiBasePath ? { basePath: apiBasePath } : {}),
617
+ accessToken: token,
618
+ credentials: 'omit'
619
+ });
624
620
 
625
621
  authenticatedClientsToken = token;
626
622
  try {
@@ -1627,6 +1623,63 @@
1627
1623
  return result;
1628
1624
  }
1629
1625
 
1626
+ /** Widget Element Selector state per widget (disabled by default until toggled in Chat). */
1627
+ let selectorEnabledByWidgetId: Record<string, boolean> = {};
1628
+ let selectedElementsByWidgetId: Record<string, SelectedWidgetElementReference[]> = {};
1629
+
1630
+ function handleToggleWidgetSelector(widgetId: string, active: boolean): void {
1631
+ if (!widgetId) return;
1632
+ selectorEnabledByWidgetId = {
1633
+ ...selectorEnabledByWidgetId,
1634
+ [widgetId]: active,
1635
+ };
1636
+ panelDisplayRevision += 1;
1637
+ }
1638
+
1639
+ function handleSelectWidgetElement(
1640
+ widgetId: string,
1641
+ element: SelectedWidgetElementReference,
1642
+ ): void {
1643
+ if (!widgetId || !element) return;
1644
+ const existing = selectedElementsByWidgetId[widgetId] ?? [];
1645
+ const duplicateIndex = existing.findIndex(
1646
+ (item) =>
1647
+ item.selector === element.selector &&
1648
+ (item.textSnippet || '') === (element.textSnippet || ''),
1649
+ );
1650
+ const nextList =
1651
+ duplicateIndex >= 0
1652
+ ? existing.map((item, idx) => (idx === duplicateIndex ? element : item))
1653
+ : [...existing, element].slice(-8);
1654
+ selectedElementsByWidgetId = {
1655
+ ...selectedElementsByWidgetId,
1656
+ [widgetId]: nextList,
1657
+ };
1658
+ panelDisplayRevision += 1;
1659
+ if (!openWidgetPanelIds.includes(widgetId)) {
1660
+ void openWidgetDetailsPanel(widgetId);
1661
+ } else if (focusedPanelWidgetId !== widgetId) {
1662
+ focusWidgetPanel(widgetId);
1663
+ }
1664
+ }
1665
+
1666
+ function handleRemoveWidgetElement(widgetId: string, elementId: string): void {
1667
+ if (!widgetId || !elementId) return;
1668
+ const existing = selectedElementsByWidgetId[widgetId] ?? [];
1669
+ selectedElementsByWidgetId = {
1670
+ ...selectedElementsByWidgetId,
1671
+ [widgetId]: existing.filter((item) => item.id !== elementId),
1672
+ };
1673
+ panelDisplayRevision += 1;
1674
+ }
1675
+
1676
+ function handleClearWidgetSelectedElements(widgetId: string): void {
1677
+ if (!widgetId) return;
1678
+ const { [widgetId]: _cleared, ...rest } = selectedElementsByWidgetId;
1679
+ selectedElementsByWidgetId = rest;
1680
+ panelDisplayRevision += 1;
1681
+ }
1682
+
1630
1683
  /** Bridge: Chat sends message → triggers code generation for the panel that sent it. */
1631
1684
  async function handleChatSendMessage(
1632
1685
  content: string,
@@ -1639,7 +1692,11 @@
1639
1692
  fileSize?: number;
1640
1693
  }>,
1641
1694
  sourceWidgetId?: string,
1642
- sendOptions?: { skipIntentGate?: boolean; chipIntent?: ClarificationSuggestion['intent'] },
1695
+ sendOptions?: {
1696
+ skipIntentGate?: boolean;
1697
+ chipIntent?: ClarificationSuggestion['intent'];
1698
+ selectedElements?: SelectedWidgetElementReference[];
1699
+ },
1643
1700
  ) {
1644
1701
  const widgetId = sourceWidgetId ?? selectedWidgetId;
1645
1702
  if (!widgetId) return;
@@ -1670,13 +1727,31 @@
1670
1727
  }
1671
1728
 
1672
1729
  const panelChat = getChatMethodsForWidget(codegenWidgetId);
1730
+ const isCodegenUploadAttachment = (attachment: {
1731
+ uploadId?: string;
1732
+ fileType: string;
1733
+ fileName: string;
1734
+ }): boolean => {
1735
+ if (!attachment.uploadId) return false;
1736
+ if (attachment.fileType.startsWith('image/')) return true;
1737
+ if (
1738
+ attachment.fileType === 'text/csv' ||
1739
+ attachment.fileName?.toLowerCase().endsWith('.csv')
1740
+ ) {
1741
+ return true;
1742
+ }
1743
+ return false;
1744
+ };
1673
1745
  const cdnUploadIds = (attachments || [])
1674
- .filter((attachment) => attachment.uploadId && attachment.fileType.startsWith('image/'))
1746
+ .filter(isCodegenUploadAttachment)
1675
1747
  .map((attachment) => attachment.uploadId)
1676
1748
  .filter((id): id is string => Boolean(id));
1749
+ const hasImageUploadIds = (attachments || []).some(
1750
+ (attachment) => Boolean(attachment.uploadId) && attachment.fileType.startsWith('image/'),
1751
+ );
1677
1752
 
1678
1753
  let panelPromptImages: string[] = [];
1679
- if (cdnUploadIds.length === 0 && attachments?.length) {
1754
+ if (!hasImageUploadIds && attachments?.length) {
1680
1755
  const capturedImageUrls: string[] = [];
1681
1756
  for (const attachment of attachments) {
1682
1757
  const base64 = await resolvePromptImageForCodegen(attachment.file, attachment.url);
@@ -1687,7 +1762,7 @@
1687
1762
  capturedImageUrls.map((url) => compressImageDataUrlForCodegen(url)),
1688
1763
  );
1689
1764
  }
1690
- } else if (cdnUploadIds.length > 0) {
1765
+ } else if (hasImageUploadIds) {
1691
1766
  panelPromptImages = (attachments || [])
1692
1767
  .filter((attachment) => attachment.url && attachment.fileType.startsWith('image/'))
1693
1768
  .map((attachment) => attachment.url as string);
@@ -1736,7 +1811,14 @@
1736
1811
  // Deterministic design-tweak fast path: explicit values and arithmetic
1737
1812
  // resolve against the loaded design schema in code, so an unambiguous
1738
1813
  // property change never pays for a 30–300s codegen turn.
1739
- if (!attachments?.length && !sendOptions?.skipIntentGate) {
1814
+ // Skip when the user explicitly selected a DOM element via the Selector
1815
+ // so that element-scoped changes ("make this bigger and move it to the left")
1816
+ // are routed to AST-localized codegen on that element.
1817
+ const selectedElementsForTurn =
1818
+ sendOptions?.selectedElements && sendOptions.selectedElements.length > 0
1819
+ ? sendOptions.selectedElements
1820
+ : undefined;
1821
+ if (!attachments?.length && !sendOptions?.skipIntentGate && !selectedElementsForTurn) {
1740
1822
  if (tryApplyDesignIntent(codegenWidgetId, content)) return;
1741
1823
  // Jev takes over ONLY the bounded-set-semantic bucket — the residual
1742
1824
  // where the property or value needs judgment but the value space is
@@ -1798,6 +1880,7 @@
1798
1880
  persistFileAttachments: persistFileAttachments.length > 0 ? persistFileAttachments : undefined,
1799
1881
  skipIntentGate: sendOptions?.skipIntentGate === true,
1800
1882
  chipIntent: sendOptions?.chipIntent,
1883
+ selectedElements: selectedElementsForTurn,
1801
1884
  });
1802
1885
  }
1803
1886
 
@@ -2075,8 +2158,9 @@
2075
2158
  * exist (feedback c: chat looked empty while messages went elsewhere).
2076
2159
  */
2077
2160
  function guessAttachmentFileType(url: string, fileName?: string | null, fallback?: string | null): string {
2078
- if (fallback && String(fallback).includes('/')) return String(fallback);
2079
2161
  const hint = `${url || ''} ${fileName || ''}`;
2162
+ if (/\.csv(\?|\s|$)/i.test(hint)) return 'text/csv';
2163
+ if (fallback && String(fallback).includes('/')) return String(fallback);
2080
2164
  if (/\.pdf(\?|$)/i.test(hint)) return 'application/pdf';
2081
2165
  if (/\.(mp4|webm|mov)(\?|$)/i.test(hint)) return 'video/mp4';
2082
2166
  if (/\.(png|jpe?g|gif|webp|svg)(\?|$)/i.test(hint)) return 'image/png';
@@ -8421,17 +8505,20 @@
8421
8505
  // );
8422
8506
  }
8423
8507
  const storedCommitId = widget?.id ? loadCommitIdForWidget(widget.id) : null;
8424
- const widgetCpgSha = (widget as { lastCpgCommitSha?: string | null }).lastCpgCommitSha || null;
8508
+ const widgetCommitSha =
8509
+ (widget as { lastCommitSha?: string | null }).lastCommitSha
8510
+ ?? (widget as { last_commit_sha?: string | null }).last_commit_sha
8511
+ ?? null;
8425
8512
  const widgetPublishSha =
8426
8513
  (widget as { lastPublishCommitSha?: string | null }).lastPublishCommitSha
8427
8514
  ?? (widget as { last_publish_commit_sha?: string | null }).last_publish_commit_sha
8428
8515
  ?? null;
8429
8516
  // HEAD commit: localStorage or last codegen SHA only — never default to publish SHA (that hides "ahead of live").
8430
- lastCommitId = storedCommitId || widgetCpgSha || null;
8517
+ lastCommitId = storedCommitId || widgetCommitSha || null;
8431
8518
  if (lastCommitId) {
8432
8519
  // console.log(
8433
8520
  // `[Version] Widget "${widget?.name}" commit loaded: ${lastCommitId.substring(0, 7)}`,
8434
- // `(source: ${storedCommitId ? 'localStorage' : 'lastCpgCommitSha'})`
8521
+ // `(source: ${storedCommitId ? 'localStorage' : 'lastCommitSha'})`
8435
8522
  // );
8436
8523
  }
8437
8524
  if (widget?.id) {
@@ -9809,6 +9896,8 @@ Requirements:
9809
9896
  file_size?: number | null;
9810
9897
  display_order?: number;
9811
9898
  }>;
9899
+ /** Widget DOM elements selected via the interactive canvas Selector. */
9900
+ selectedElements?: SelectedWidgetElementReference[];
9812
9901
  } = {}) {
9813
9902
  const targetWidgetId = options.widgetId ?? selectedWidgetId;
9814
9903
  if (!targetWidgetId) return;
@@ -9835,7 +9924,14 @@ Requirements:
9835
9924
  ? codeGenerationPrompt
9836
9925
  : getPanelState(codegenTargetWidgetId).codeGenerationPrompt;
9837
9926
  const promptSource = options.prompt || panelPrompt;
9838
- const trimmedPrompt = promptSource.trim();
9927
+ const rawTrimmedPrompt = promptSource.trim();
9928
+ const trimmedPrompt =
9929
+ rawTrimmedPrompt.length > 0 &&
9930
+ rawTrimmedPrompt.length < 10 &&
9931
+ options.selectedElements &&
9932
+ options.selectedElements.length > 0
9933
+ ? `Update selected element (${options.selectedElements.map((el) => el.label).join(', ')}): ${rawTrimmedPrompt}`
9934
+ : rawTrimmedPrompt;
9839
9935
  if (trimmedPrompt.length < 10) {
9840
9936
  showToast('error', $t('creator.codegen.promptTooShort'), {
9841
9937
  description:
@@ -9891,6 +9987,7 @@ Requirements:
9891
9987
  persistFileAttachments: options.persistFileAttachments,
9892
9988
  skipIntentGate: options.skipIntentGate,
9893
9989
  chipIntent: options.chipIntent,
9990
+ selectedElements: options.selectedElements,
9894
9991
  });
9895
9992
  }
9896
9993
 
@@ -10101,6 +10198,7 @@ Requirements:
10101
10198
  file_size?: number | null;
10102
10199
  display_order?: number;
10103
10200
  }>;
10201
+ selectedElements?: SelectedWidgetElementReference[];
10104
10202
  } = {},
10105
10203
  ) {
10106
10204
  const generationWidgetId = options.widgetId ?? selectedWidgetId;
@@ -10293,7 +10391,13 @@ Requirements:
10293
10391
  }
10294
10392
  }
10295
10393
  let coderModelForRequest = selectedModelId || defaultModelId;
10296
- if (imagesToSend?.length || attachmentIdsToSend?.length) {
10394
+ const hasImageFileAttachment =
10395
+ !Array.isArray(options.persistFileAttachments) ||
10396
+ options.persistFileAttachments.length === 0 ||
10397
+ options.persistFileAttachments.some((att) =>
10398
+ String(att.file_type || '').startsWith('image/'),
10399
+ );
10400
+ if (imagesToSend?.length || (attachmentIdsToSend?.length && hasImageFileAttachment)) {
10297
10401
  // console.log(
10298
10402
  // '[WidgetCreator] Vision context:',
10299
10403
  // imagesToSend?.length || 0,
@@ -10365,6 +10469,22 @@ Requirements:
10365
10469
  chipIntent: options.chipIntent,
10366
10470
  language: languageForGeneration(generationWidgetId),
10367
10471
  brandKit: brandKitForRequest(),
10472
+ ...(options.selectedElements && options.selectedElements.length > 0
10473
+ ? {
10474
+ selectedElements: options.selectedElements.map((el) => ({
10475
+ tagName: el.tagName,
10476
+ selector: el.selector,
10477
+ idAttr: el.idAttr,
10478
+ classList: el.classList,
10479
+ textSnippet: el.textSnippet,
10480
+ dataContent: el.dataContent,
10481
+ parentTag: el.parentTag,
10482
+ outerHtmlSnippet: el.outerHtmlSnippet,
10483
+ attributes: el.attributes,
10484
+ rect: el.rect,
10485
+ })),
10486
+ }
10487
+ : {}),
10368
10488
  } as GenerateCodeRequest
10369
10489
  }, widgetBuilderRequestInit(widgetBuilderPreviewBaseUrl()));
10370
10490
  let response: { data?: Record<string, unknown>; error?: string; message?: string } | null = null;
@@ -15690,9 +15810,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
15690
15810
  isDraft: (newWidget as { isDraft?: boolean }).isDraft
15691
15811
  ?? (sourceWidget as { isDraft?: boolean; is_draft?: boolean }).isDraft
15692
15812
  ?? (sourceWidget as { is_draft?: boolean }).is_draft,
15693
- lastCpgCommitSha:
15694
- (newWidget as { lastCpgCommitSha?: string | null }).lastCpgCommitSha
15695
- ?? (sourceWidget as { lastCpgCommitSha?: string | null }).lastCpgCommitSha,
15813
+ lastCommitSha:
15814
+ (newWidget as { lastCommitSha?: string | null }).lastCommitSha
15815
+ ?? (newWidget as { last_commit_sha?: string | null }).last_commit_sha
15816
+ ?? (sourceWidget as { lastCommitSha?: string | null }).lastCommitSha
15817
+ ?? (sourceWidget as { last_commit_sha?: string | null }).last_commit_sha,
15696
15818
  lastPublishCommitSha:
15697
15819
  (newWidget as { lastPublishCommitSha?: string | null }).lastPublishCommitSha
15698
15820
  ?? (sourceWidget as { lastPublishCommitSha?: string | null; last_publish_commit_sha?: string | null }).lastPublishCommitSha
@@ -17476,6 +17598,11 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
17476
17598
  }}
17477
17599
  onRefresh={handleWidgetShapeRefresh}
17478
17600
  isGenerating={isAnyWidgetGenerating()}
17601
+ resolveSelectorEnabled={(widgetId) => !!selectorEnabledByWidgetId[widgetId]}
17602
+ resolveSelectedElements={(widgetId) => selectedElementsByWidgetId[widgetId] ?? []}
17603
+ onSelectWidgetElement={(widgetId, element) => handleSelectWidgetElement(widgetId, element)}
17604
+ onRemoveWidgetElement={(widgetId, elementId) => handleRemoveWidgetElement(widgetId, elementId)}
17605
+ onCloseWidgetSelector={(widgetId) => handleToggleWidgetSelector(widgetId, false)}
17479
17606
  />
17480
17607
 
17481
17608
  <!-- ═══ PANEL 2: Widgets Panel — debug + showWidgetsList (site passes false) ═══ -->
@@ -18483,7 +18610,13 @@ $: if (codeGenerationPrompt && selectedWidgetId && promptLoadedForWidgetId === s
18483
18610
  versionLabelByPrompt={versionPromptLabelsByWidgetId[panelWidgetId] ?? emptyVersionLabels}
18484
18611
  versionTimeline={versionTimelineByWidgetId[panelWidgetId] ?? emptyVersionTimeline}
18485
18612
  viewingVersion={viewingVersionByWidgetId[panelWidgetId] ?? null}
18486
- onSendMessage={(content, attachments) => handleChatSendMessage(content, attachments, panelWidgetId)}
18613
+ showSelector={!isDraftConvertId(panelWidgetId)}
18614
+ isSelectorActive={!!selectorEnabledByWidgetId[panelWidgetId]}
18615
+ selectedElements={selectedElementsByWidgetId[panelWidgetId] ?? []}
18616
+ onToggleSelector={(active) => handleToggleWidgetSelector(panelWidgetId, active)}
18617
+ onRemoveSelectedElement={(elementId) => handleRemoveWidgetElement(panelWidgetId, elementId)}
18618
+ onClearSelectedElements={() => handleClearWidgetSelectedElements(panelWidgetId)}
18619
+ onSendMessage={(content, attachments, sendOptions) => handleChatSendMessage(content, attachments, panelWidgetId, sendOptions)}
18487
18620
  onRetryMessage={(content) => handleChatRetryMessage(content, panelWidgetId)}
18488
18621
  onUpgradePlans={openUpgradePlans}
18489
18622
  onUploadChatFile={handleChatUploadFile}
@@ -71,7 +71,8 @@
71
71
  repository_id?: string | null;
72
72
  repoId?: string | null;
73
73
  name?: string;
74
- lastCpgCommitSha?: string | null;
74
+ lastCommitSha?: string | null;
75
+ last_commit_sha?: string | null;
75
76
  [extra: string]: unknown;
76
77
  }
77
78
 
@@ -32,7 +32,8 @@ declare const WidgetDetails: $$__sveltets_2_IsomorphicComponent<{
32
32
  repository_id?: string | null;
33
33
  repoId?: string | null;
34
34
  name?: string;
35
- lastCpgCommitSha?: string | null;
35
+ lastCommitSha?: string | null;
36
+ last_commit_sha?: string | null;
36
37
  } | null;
37
38
  isGeneratingCode?: boolean;
38
39
  skipBasePreview?: boolean;