From 894cfba0e07eebfd2b34878dfa123984a98fc420 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 20 Feb 2025 10:58:03 +0100 Subject: [PATCH 01/91] Type BindingSidePanel --- .../bbui/src/Actions/position_dropdown.ts | 2 +- packages/bbui/src/Popover/Popover.svelte | 3 +- .../common/bindings/BindingPanel.svelte | 2 +- .../common/bindings/BindingSidePanel.svelte | 109 ++++++++++-------- packages/types/src/ui/bindings/binding.ts | 12 ++ packages/types/src/ui/bindings/helper.ts | 1 + 6 files changed, 79 insertions(+), 50 deletions(-) diff --git a/packages/bbui/src/Actions/position_dropdown.ts b/packages/bbui/src/Actions/position_dropdown.ts index 424baf91f3..edfe901921 100644 --- a/packages/bbui/src/Actions/position_dropdown.ts +++ b/packages/bbui/src/Actions/position_dropdown.ts @@ -27,7 +27,7 @@ export type UpdateHandler = ( interface Opts { anchor?: HTMLElement - align: PopoverAlignment + align: PopoverAlignment | `${PopoverAlignment}` maxHeight?: number maxWidth?: number minWidth?: number diff --git a/packages/bbui/src/Popover/Popover.svelte b/packages/bbui/src/Popover/Popover.svelte index 0d16aa4f77..5d0c5b7039 100644 --- a/packages/bbui/src/Popover/Popover.svelte +++ b/packages/bbui/src/Popover/Popover.svelte @@ -19,7 +19,8 @@ import { PopoverAlignment } from "../constants" export let anchor: HTMLElement - export let align: PopoverAlignment = PopoverAlignment.Right + export let align: PopoverAlignment | `${PopoverAlignment}` = + PopoverAlignment.Right export let portalTarget: string | undefined = undefined export let minWidth: number | undefined = undefined export let maxWidth: number | undefined = undefined diff --git a/packages/builder/src/components/common/bindings/BindingPanel.svelte b/packages/builder/src/components/common/bindings/BindingPanel.svelte index 2c35acdf2d..1f61136500 100644 --- a/packages/builder/src/components/common/bindings/BindingPanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingPanel.svelte @@ -421,7 +421,7 @@ {context} addHelper={onSelectHelper} addBinding={onSelectBinding} - mode={editorMode} + {mode} /> {:else if sidePanel === SidePanel.Evaluation} + - -
- {#if hoverTarget.description} -
+{#if popoverAnchor && hoverTarget} + +
+ {#if hoverTarget.description} +
+ + {@html hoverTarget.description} +
+ {/if} + {#if hoverTarget.code} - {@html hoverTarget.description} -
- {/if} - {#if hoverTarget.code} - -
{@html hoverTarget.code}
- {/if} -
- +
{@html hoverTarget.code}
+ {/if} +
+
+{/if} @@ -173,7 +186,7 @@
@@ -230,7 +243,8 @@ {#each category.bindings as binding}
  • showBindingPopover(binding, e.target)} + on:mouseenter={e => + showBindingPopover(binding, e.currentTarget)} on:mouseleave={hidePopover} on:click={() => addBinding(binding)} > @@ -266,7 +280,8 @@ class="binding" on:mouseenter={e => showHelperPopover(helper, e.target)} on:mouseleave={hidePopover} - on:click={() => addHelper(helper, mode.name === "javascript")} + on:click={() => + addHelper(helper, mode === BindingMode.JavaScript)} > {helper.displayText} diff --git a/packages/types/src/ui/bindings/binding.ts b/packages/types/src/ui/bindings/binding.ts index fdeb4a6c13..9e15d9dd13 100644 --- a/packages/types/src/ui/bindings/binding.ts +++ b/packages/types/src/ui/bindings/binding.ts @@ -1,7 +1,19 @@ export interface EnrichedBinding { + value: string + valueHTML: string runtimeBinding: string readableBinding: string type?: null | string + icon?: string + category: string + display?: { name: string; type: string } + fieldSchema?: { + name: string + tableId: string + type: string + subtype?: string + prefixKeys?: string + } } export enum BindingMode { diff --git a/packages/types/src/ui/bindings/helper.ts b/packages/types/src/ui/bindings/helper.ts index e772180264..e25918438f 100644 --- a/packages/types/src/ui/bindings/helper.ts +++ b/packages/types/src/ui/bindings/helper.ts @@ -1,4 +1,5 @@ export interface Helper { + displayText: string example: string description: string args: any[] From 93a65b6289f74f9b1248dc9ab09cb454ed77a4d3 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 20 Feb 2025 11:17:09 +0100 Subject: [PATCH 02/91] Add eslint rule for consistent type imports --- eslint.config.mjs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/eslint.config.mjs b/eslint.config.mjs index c497974612..2f4072a188 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -94,6 +94,15 @@ export default [ allowImportExportEverywhere: true, }, }, + + plugins: { + ...config.plugins, + "@typescript-eslint": tseslint.plugin, + }, + rules: { + ...config.rules, + "@typescript-eslint/consistent-type-imports": "error", + }, })), ...tseslint.configs.strict.map(config => ({ ...config, From a84044e6a1daf862a03f56cefa7e85acd3eb4f28 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 20 Feb 2025 11:18:40 +0100 Subject: [PATCH 03/91] Lint fix --- .../components/common/bindings/BindingSidePanel.svelte | 3 ++- packages/client/src/components/app/DataProvider.svelte | 9 +++++---- .../src/components/app/blocks/form/FormBlock.svelte | 2 +- .../components/error-states/ComponentErrorState.svelte | 2 +- .../error-states/ComponentErrorStateCTA.svelte | 2 +- packages/client/src/components/preview/DNDHandler.svelte | 2 +- 6 files changed, 11 insertions(+), 9 deletions(-) diff --git a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte index 9cd56c7797..120d14252d 100644 --- a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte @@ -3,7 +3,8 @@ import { convertToJS } from "@budibase/string-templates" import { Input, Layout, Icon, Popover } from "@budibase/bbui" import { handlebarsCompletions } from "@/constants/completions" - import { BindingMode, EnrichedBinding, Helper } from "@budibase/types" + import type { EnrichedBinding, Helper } from "@budibase/types"; +import { BindingMode } from "@budibase/types" export let addHelper: (helper: Helper, js?: boolean) => void export let addBinding: (binding: EnrichedBinding) => void diff --git a/packages/client/src/components/app/DataProvider.svelte b/packages/client/src/components/app/DataProvider.svelte index a80b9a5f74..9c79b36c4b 100644 --- a/packages/client/src/components/app/DataProvider.svelte +++ b/packages/client/src/components/app/DataProvider.svelte @@ -2,9 +2,7 @@ import { getContext } from "svelte" import { Pagination, ProgressCircle } from "@budibase/bbui" import { fetchData, QueryUtils } from "@budibase/frontend-core" - import { - LogicalOperator, - EmptyFilterOption, + import type { TableSchema, SortOrder, SearchFilters, @@ -12,7 +10,10 @@ DataFetchDatasource, UserDatasource, GroupUserDatasource, - DataFetchOptions, + DataFetchOptions} from "@budibase/types"; +import { + LogicalOperator, + EmptyFilterOption } from "@budibase/types" type ProviderDatasource = Exclude< diff --git a/packages/client/src/components/app/blocks/form/FormBlock.svelte b/packages/client/src/components/app/blocks/form/FormBlock.svelte index 3f44aee1d7..17804b033a 100644 --- a/packages/client/src/components/app/blocks/form/FormBlock.svelte +++ b/packages/client/src/components/app/blocks/form/FormBlock.svelte @@ -4,7 +4,7 @@ import { Utils } from "@budibase/frontend-core" import FormBlockWrapper from "./FormBlockWrapper.svelte" import { get } from "svelte/store" - import { TableSchema, UIDatasource } from "@budibase/types" + import type { TableSchema, UIDatasource } from "@budibase/types" type Field = { name: string; active: boolean } diff --git a/packages/client/src/components/error-states/ComponentErrorState.svelte b/packages/client/src/components/error-states/ComponentErrorState.svelte index b2e7c92eae..1bcd5f21fa 100644 --- a/packages/client/src/components/error-states/ComponentErrorState.svelte +++ b/packages/client/src/components/error-states/ComponentErrorState.svelte @@ -1,7 +1,7 @@ {#if popoverAnchor && hoverTarget} @@ -366,18 +376,29 @@ {#if selectedCategory === "Snippets" || search} {#if filteredSnippets?.length}
    -
      +
        {#each filteredSnippets as snippet}
      • showSnippetPopover(snippet, e.currentTarget)} + on:mouseleave={hidePopover} on:click={() => addSnippet(snippet)} > {snippet.name} - - snippet - + {#if search} + + snippet + + {:else} + editSnippet(e, snippet)} + /> + {/if}
      • {/each}
      @@ -388,6 +409,8 @@
    + + From ab6907691fad5f023f99809f4e77be5a5b61ed37 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 20 Feb 2025 15:58:23 +0100 Subject: [PATCH 15/91] Extract --- .../common/bindings/BindingSidePanel.svelte | 109 +--------- .../bindings/snippets/SidePanelContent.svelte | 191 ++++++++++++++++++ .../bindings/snippets/SidePanelHeader.svelte | 46 +++++ 3 files changed, 246 insertions(+), 100 deletions(-) create mode 100644 packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte create mode 100644 packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte diff --git a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte index b17eedd294..0b542a413b 100644 --- a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte @@ -7,7 +7,8 @@ import { BindingMode } from "@budibase/types" import { EditorModes } from "../CodeEditor" import CodeEditor from "../CodeEditor/CodeEditor.svelte" - import SnippetDrawer from "./SnippetDrawer.svelte" + import SnippetsSidePanelHeader from "./snippets/SidePanelHeader.svelte" + import SnippetsSidePanelContent from "./snippets/SidePanelContent.svelte" export let addHelper: (_helper: Helper, _js?: boolean) => void export let addBinding: (_binding: EnrichedBinding) => void @@ -24,15 +25,13 @@ let popover: Popover let popoverAnchor: HTMLElement | null let hoverTarget: { - type: "binding" | "helper" | "snippet" + type: "binding" | "helper" code: string description?: string } | null let helpers = handlebarsCompletions() let selectedCategory: string | null let hideTimeout: ReturnType | null - let snippetDrawer: SnippetDrawer - let editableSnippet: Snippet | null $: bindingIcons = bindings?.reduce>((acc, ele) => { if (ele.icon) { @@ -47,13 +46,10 @@ } as Record $: categories = Object.entries(groupBy("category", bindings)) - $: filteredSnippets = getFilteredSnippets( - mode, - allowSnippets, - snippets || [], - search + $: categoryNames = getCategoryNames( + categories, + allowSnippets && mode === BindingMode.JavaScript ) - $: categoryNames = getCategoryNames(categories, filteredSnippets.length > 0) $: searchRgx = new RegExp(search, "ig") $: filteredCategories = categories .map(([name, categoryBindings]) => ({ @@ -82,26 +78,6 @@ } $: onModeChange(mode) - const getFilteredSnippets = ( - mode: BindingMode, - enableSnippets: boolean, - snippets: Snippet[], - search: string - ) => { - if (mode !== BindingMode.JavaScript) { - return [] - } - if (!enableSnippets || !snippets.length) { - return [] - } - if (!search?.length) { - return snippets - } - return snippets.filter(snippet => - snippet.name.toLowerCase().includes(search.toLowerCase()) - ) - } - const getHelperExample = (helper: Helper, js: boolean) => { let example = helper.example || "" if (js) { @@ -157,19 +133,6 @@ popover.show() } - const showSnippetPopover = (snippet: Snippet, target: HTMLElement) => { - stopHidingPopover() - if (!snippet.code) { - return - } - popoverAnchor = target - hoverTarget = { - type: "snippet", - code: snippet.code, - } - popover.show() - } - const hidePopover = () => { hideTimeout = setTimeout(() => { popover.hide() @@ -196,18 +159,6 @@ searching = false search = "" } - - const createSnippet = () => { - editableSnippet = null - snippetDrawer.show() - } - - const editSnippet = (e: Event, snippet: Snippet) => { - e.preventDefault() - e.stopPropagation() - editableSnippet = snippet - snippetDrawer.show() - } {#if popoverAnchor && hoverTarget} @@ -262,15 +213,8 @@ /> {selectedCategory} {#if selectedCategory === "Snippets"} -
    - -
    {/if} + + {/if}
  • {/if} @@ -389,43 +333,12 @@ {/if} {#if selectedCategory === "Snippets" || search} - {#if filteredSnippets?.length} -
    -
      - {#each filteredSnippets as snippet} -
    • - showSnippetPopover(snippet, e.currentTarget)} - on:mouseleave={hidePopover} - on:click={() => addSnippet(snippet)} - > - {snippet.name} - {#if search} - - snippet - - {:else} - editSnippet(e, snippet)} - /> - {/if} -
    • - {/each} -
    -
    - {/if} + {/if} {/if} - - diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte new file mode 100644 index 0000000000..b83d9323b7 --- /dev/null +++ b/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte @@ -0,0 +1,191 @@ + + + + +
    + {#if enableSnippets} + {#each filteredSnippets as snippet} +
    showSnippet(snippet, e.currentTarget)} + on:mouseleave={hidePopover} + on:click={() => addSnippet(snippet)} + > + {snippet.name} + editSnippet(e, snippet)} + /> +
    + {/each} + {:else if !search} +
    + + Snippets let you create reusable JS functions and values that can all be + managed in one place + + {#if enableSnippets} + + {:else} + + {/if} +
    + {/if} +
    + +{#if hoverTarget && popoverAnchor} + +
    + {#key hoverTarget} + + {/key} +
    +
    +{/if} + + + + diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte new file mode 100644 index 0000000000..b62282299b --- /dev/null +++ b/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte @@ -0,0 +1,46 @@ + + +{#if enableSnippets} +
    + +
    +{:else} +
    + + Premium + +
    +{/if} + + + + From af6307a60834317b03b46705a66217642836933c Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 20 Feb 2025 16:01:37 +0100 Subject: [PATCH 16/91] Remove duplicates --- .../common/bindings/BindingPanel.svelte | 22 +- .../common/bindings/SnippetSidePanel.svelte | 278 ------------------ .../src/components/common/bindings/index.js | 2 - .../bindings/snippets/SidePanelContent.svelte | 2 +- .../bindings/snippets/SidePanelHeader.svelte | 2 +- .../{ => snippets}/SnippetDrawer.svelte | 0 6 files changed, 4 insertions(+), 302 deletions(-) delete mode 100644 packages/builder/src/components/common/bindings/SnippetSidePanel.svelte rename packages/builder/src/components/common/bindings/{ => snippets}/SnippetDrawer.svelte (100%) diff --git a/packages/builder/src/components/common/bindings/BindingPanel.svelte b/packages/builder/src/components/common/bindings/BindingPanel.svelte index 8760272043..d4027ee90a 100644 --- a/packages/builder/src/components/common/bindings/BindingPanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingPanel.svelte @@ -27,7 +27,6 @@ } from "../CodeEditor" import BindingSidePanel from "./BindingSidePanel.svelte" import EvaluationSidePanel from "./EvaluationSidePanel.svelte" - import SnippetSidePanel from "./SnippetSidePanel.svelte" import { BindingHelpers } from "./utils" import { capitalise } from "@/helpers" import { Utils, JsonFormatter } from "@budibase/frontend-core" @@ -74,22 +73,15 @@ const enum SidePanel { Bindings = "Bindings", Evaluation = "Evaluation", - Snippets = "Snippets", } const SidePanelIcons: Record = { Bindings: "FlashOn", Evaluation: "Play", - Snippets: "Code", } $: useSnippets = allowSnippets && !$licensing.isFreePlan $: editorModeOptions = getModeOptions(allowHBS, allowJS) - $: sidePanelOptions = getSidePanelOptions( - bindings, - context, - allowSnippets, - mode - ) + $: sidePanelOptions = getSidePanelOptions(bindings, context) $: enrichedBindings = enrichBindings(bindings, context, snippets) $: usingJS = mode === BindingMode.JavaScript $: editorMode = @@ -148,12 +140,7 @@ return options } - const getSidePanelOptions = ( - bindings: EnrichedBinding[], - context: any, - useSnippets: boolean, - mode: BindingMode | null - ) => { + const getSidePanelOptions = (bindings: EnrichedBinding[], context: any) => { let options = [] if (bindings?.length) { options.push(SidePanel.Bindings) @@ -161,9 +148,6 @@ if (context && Object.keys(context).length > 0) { options.push(SidePanel.Evaluation) } - if (useSnippets && mode === BindingMode.JavaScript) { - options.push(SidePanel.Snippets) - } return options } @@ -446,8 +430,6 @@ {evaluating} expression={editorValue ? editorValue : ""} /> - {:else if sidePanel === SidePanel.Snippets} - {/if} diff --git a/packages/builder/src/components/common/bindings/SnippetSidePanel.svelte b/packages/builder/src/components/common/bindings/SnippetSidePanel.svelte deleted file mode 100644 index 95f40005c0..0000000000 --- a/packages/builder/src/components/common/bindings/SnippetSidePanel.svelte +++ /dev/null @@ -1,278 +0,0 @@ - - - - -
    - -
    - {#if enableSnippets} - {#if searching} -
    - -
    - - {:else} -
    Snippets
    - - - {/if} - {:else} -
    - Snippets - - Premium - -
    - {/if} -
    -
    - {#if enableSnippets && filteredSnippets?.length} - {#each filteredSnippets as snippet} -
    showSnippet(snippet, e.target)} - on:mouseleave={hidePopover} - on:click={() => addSnippet(snippet)} - > - {snippet.name} - editSnippet(e, snippet)} - /> -
    - {/each} - {:else} -
    - - Snippets let you create reusable JS functions and values that can - all be managed in one place - - {#if enableSnippets} - - {:else} - - {/if} -
    - {/if} -
    -
    -
    - - -
    - {#key hoveredSnippet} - - {/key} -
    -
    - - - - diff --git a/packages/builder/src/components/common/bindings/index.js b/packages/builder/src/components/common/bindings/index.js index a2d4479959..5a9c6f661b 100644 --- a/packages/builder/src/components/common/bindings/index.js +++ b/packages/builder/src/components/common/bindings/index.js @@ -8,5 +8,3 @@ export { default as DrawerBindableSlot } from "./DrawerBindableSlot.svelte" export { default as EvaluationSidePanel } from "./EvaluationSidePanel.svelte" export { default as ModalBindableInput } from "./ModalBindableInput.svelte" export { default as ServerBindingPanel } from "./ServerBindingPanel.svelte" -export { default as SnippetDrawer } from "./SnippetDrawer.svelte" -export { default as SnippetSidePanel } from "./SnippetSidePanel.svelte" diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte index b83d9323b7..7ddecf23c7 100644 --- a/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte +++ b/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte @@ -2,7 +2,7 @@ import { Icon, Popover, Body, Button } from "@budibase/bbui" import CodeEditor from "@/components/common/CodeEditor/CodeEditor.svelte" import { EditorModes } from "@/components/common/CodeEditor" - import SnippetDrawer from "../SnippetDrawer.svelte" + import SnippetDrawer from "./SnippetDrawer.svelte" import { licensing } from "@/stores/portal" import UpgradeButton from "@/pages/builder/portal/_components/UpgradeButton.svelte" import type { Snippet } from "@budibase/types" diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte index b62282299b..e278e5a72b 100644 --- a/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte +++ b/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte @@ -1,7 +1,7 @@ -{#if popoverAnchor && hoverTarget} - + + {#if hoverTarget}
    - -{/if} + {/if} + @@ -213,7 +275,23 @@ /> {selectedCategory} {#if selectedCategory === "Snippets"} - + {#if enableSnippets} +
    + +
    + {:else} +
    + + Premium + +
    + {/if} {/if}
    {/if} @@ -333,12 +411,46 @@ {/if} {#if selectedCategory === "Snippets" || search} - +
    + {#if enableSnippets} + {#each filteredSnippets as snippet} +
  • showSnippet(snippet, e.currentTarget)} + on:mouseleave={hidePopover} + on:click={() => addSnippet(snippet)} + > + {snippet.name} + editSnippet(e, snippet)} + /> +
  • + {/each} + {:else if !search} +
    + + Snippets let you create reusable JS functions and values that + can all be managed in one place + + {#if enableSnippets} + + {:else} + + {/if} +
    + {/if} +
    {/if} {/if} + + diff --git a/packages/builder/src/components/common/bindings/snippets/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte similarity index 100% rename from packages/builder/src/components/common/bindings/snippets/SnippetDrawer.svelte rename to packages/builder/src/components/common/bindings/SnippetDrawer.svelte diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte deleted file mode 100644 index 7ddecf23c7..0000000000 --- a/packages/builder/src/components/common/bindings/snippets/SidePanelContent.svelte +++ /dev/null @@ -1,191 +0,0 @@ - - - - -
    - {#if enableSnippets} - {#each filteredSnippets as snippet} -
    showSnippet(snippet, e.currentTarget)} - on:mouseleave={hidePopover} - on:click={() => addSnippet(snippet)} - > - {snippet.name} - editSnippet(e, snippet)} - /> -
    - {/each} - {:else if !search} -
    - - Snippets let you create reusable JS functions and values that can all be - managed in one place - - {#if enableSnippets} - - {:else} - - {/if} -
    - {/if} -
    - -{#if hoverTarget && popoverAnchor} - -
    - {#key hoverTarget} - - {/key} -
    -
    -{/if} - - - - diff --git a/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte b/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte deleted file mode 100644 index e278e5a72b..0000000000 --- a/packages/builder/src/components/common/bindings/snippets/SidePanelHeader.svelte +++ /dev/null @@ -1,46 +0,0 @@ - - -{#if enableSnippets} -
    - -
    -{:else} -
    - - Premium - -
    -{/if} - - - - From 25c5f7f70c365831e6bac5bf387e0df52b9414c1 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 21 Feb 2025 10:21:21 +0100 Subject: [PATCH 19/91] Type snippetDrawer --- packages/bbui/src/Drawer/Drawer.svelte | 2 +- .../common/bindings/BindingPanel.svelte | 2 +- .../common/bindings/BindingSidePanel.svelte | 1 - .../common/bindings/SnippetDrawer.svelte | 25 +++++++++++-------- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/packages/bbui/src/Drawer/Drawer.svelte b/packages/bbui/src/Drawer/Drawer.svelte index 1f38389a63..15811daa08 100644 --- a/packages/bbui/src/Drawer/Drawer.svelte +++ b/packages/bbui/src/Drawer/Drawer.svelte @@ -64,7 +64,7 @@ import { setContext, createEventDispatcher, onDestroy } from "svelte" import { generate } from "shortid" - export let title + export let title = null export let forceModal = false const dispatch = createEventDispatcher() diff --git a/packages/builder/src/components/common/bindings/BindingPanel.svelte b/packages/builder/src/components/common/bindings/BindingPanel.svelte index 8d3c27b61b..3730a5466a 100644 --- a/packages/builder/src/components/common/bindings/BindingPanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingPanel.svelte @@ -56,7 +56,7 @@ export let context = null export let snippets: Snippet[] | null = null export let autofocusEditor = false - export let placeholder = null + export let placeholder: string | null = null export let showTabBar = true let mode: BindingMode diff --git a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte index 033eeb7ea9..cabb546138 100644 --- a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte @@ -620,7 +620,6 @@ padding-bottom: var(--spacing-l); display: flex; flex-direction: column; - /* gap: var(--spacing-s); */ } .snippet { font-size: var(--font-size-s); diff --git a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte index 4862217b13..72e919a516 100644 --- a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte +++ b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte @@ -1,4 +1,4 @@ - - + {#if snippet} {snippet.name} @@ -108,7 +109,11 @@ Delete {/if} - @@ -124,9 +129,7 @@ value={code} on:change={e => (code = e.detail)} > -
    - -
    + {/key} From 6266ae7300394223c5d3edce728f2499d6c2dc7e Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 21 Feb 2025 10:32:19 +0100 Subject: [PATCH 20/91] Fix types --- packages/bbui/src/Drawer/Drawer.svelte | 2 +- .../builder/src/components/common/bindings/SnippetDrawer.svelte | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/bbui/src/Drawer/Drawer.svelte b/packages/bbui/src/Drawer/Drawer.svelte index 15811daa08..5650f5a812 100644 --- a/packages/bbui/src/Drawer/Drawer.svelte +++ b/packages/bbui/src/Drawer/Drawer.svelte @@ -64,7 +64,7 @@ import { setContext, createEventDispatcher, onDestroy } from "svelte" import { generate } from "shortid" - export let title = null + export let title = "" export let forceModal = false const dispatch = createEventDispatcher() diff --git a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte index 72e919a516..b8b83f327a 100644 --- a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte +++ b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte @@ -79,7 +79,7 @@ } - + {#if snippet} {snippet.name} From 875623661e02fda21984e7f68384d81d85aecf53 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 21 Feb 2025 10:41:13 +0100 Subject: [PATCH 21/91] Fix type --- .../builder/src/components/common/bindings/SnippetDrawer.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte index b8b83f327a..79ae105925 100644 --- a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte +++ b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte @@ -14,7 +14,7 @@ import { getSequentialName } from "@/helpers/duplicate" import ConfirmDialog from "@/components/common/ConfirmDialog.svelte" import { ValidSnippetNameRegex } from "@budibase/shared-core" - import { Snippet } from "@budibase/types" + import type { Snippet } from "@budibase/types" export let snippet From 694dc78c0ff9bc831db3bc00b2d58e847cf74827 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 21 Feb 2025 11:50:01 +0100 Subject: [PATCH 22/91] Add types --- .../src/components/common/bindings/SnippetDrawer.svelte | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte index 79ae105925..5a19156993 100644 --- a/packages/builder/src/components/common/bindings/SnippetDrawer.svelte +++ b/packages/builder/src/components/common/bindings/SnippetDrawer.svelte @@ -16,7 +16,7 @@ import { ValidSnippetNameRegex } from "@budibase/shared-core" import type { Snippet } from "@budibase/types" - export let snippet + export let snippet: Snippet | null export const show = () => drawer.show() export const hide = () => drawer.hide() @@ -54,7 +54,9 @@ const deleteSnippet = async () => { loading = true try { - await snippets.deleteSnippet(snippet.name) + if (snippet) { + await snippets.deleteSnippet(snippet.name) + } drawer.hide() } catch (error) { notifications.error("Error deleting snippet") From 621066bdc0954cc19447f0711984eec40cdf9e28 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 21 Feb 2025 12:15:56 +0100 Subject: [PATCH 23/91] Clean states --- .../common/bindings/BindingSidePanel.svelte | 13 +++++++++---- .../components/common/bindings/SnippetDrawer.svelte | 10 ++++++---- 2 files changed, 15 insertions(+), 8 deletions(-) diff --git a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte index cabb546138..1767228355 100644 --- a/packages/builder/src/components/common/bindings/BindingSidePanel.svelte +++ b/packages/builder/src/components/common/bindings/BindingSidePanel.svelte @@ -43,8 +43,8 @@ let helpers = handlebarsCompletions() let selectedCategory: string | null let hideTimeout: ReturnType | null - let snippetDrawer: SnippetDrawer let editableSnippet: Snippet | null + let showSnippetDrawer = false $: enableSnippets = !$licensing.isFreePlan $: bindingIcons = bindings?.reduce>((acc, ele) => { @@ -212,14 +212,14 @@ const createSnippet = () => { editableSnippet = null - snippetDrawer.show() + showSnippetDrawer = true } const editSnippet = (e: Event, snippet: Snippet) => { e.preventDefault() e.stopPropagation() editableSnippet = snippet - snippetDrawer.show() + showSnippetDrawer = true } @@ -449,7 +449,12 @@ - +{#if showSnippetDrawer} + (showSnippetDrawer = false)} + /> +{/if} From 84a1ccfc4c8776685da057540b3f77c96d21a9c1 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 24 Feb 2025 14:59:04 +0000 Subject: [PATCH 25/91] Fixing an issue with scrollbar always appearing on end user portal. --- packages/bbui/src/Layout/Page.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/bbui/src/Layout/Page.svelte b/packages/bbui/src/Layout/Page.svelte index e469927e60..e8dad8bc38 100644 --- a/packages/bbui/src/Layout/Page.svelte +++ b/packages/bbui/src/Layout/Page.svelte @@ -47,7 +47,7 @@ overflow-x: hidden; } .main { - overflow-y: scroll; + overflow-y: auto; } .content { display: flex; From f5a7e5bf4951c5c1cc62adfb88f2d51b291fdfb4 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 24 Feb 2025 15:34:30 +0000 Subject: [PATCH 26/91] Fixing app count in user page. --- .../src/pages/builder/portal/users/users/index.svelte | 2 +- packages/shared-core/src/sdk/documents/users.ts | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/packages/builder/src/pages/builder/portal/users/users/index.svelte b/packages/builder/src/pages/builder/portal/users/users/index.svelte index c77e40c964..6a1facfd01 100644 --- a/packages/builder/src/pages/builder/portal/users/users/index.svelte +++ b/packages/builder/src/pages/builder/portal/users/users/index.svelte @@ -128,7 +128,7 @@ $auth.user?.email === user.email ? false : true, - apps: [...new Set(Object.keys(user.roles))], + apps: sdk.users.userAppAccessList(user, $groups), access: role.sortOrder, } }) diff --git a/packages/shared-core/src/sdk/documents/users.ts b/packages/shared-core/src/sdk/documents/users.ts index 17aa8a1e58..c4f1a16025 100644 --- a/packages/shared-core/src/sdk/documents/users.ts +++ b/packages/shared-core/src/sdk/documents/users.ts @@ -4,6 +4,7 @@ import { SEPARATOR, User, InternalTable, + UserGroup, } from "@budibase/types" import { getProdAppID } from "./applications" import * as _ from "lodash/fp" @@ -129,3 +130,13 @@ export function containsUserID(value: string | undefined): boolean { } return value.includes(`${DocumentType.USER}${SEPARATOR}`) } + +export function userAppAccessList(user: User, groups?: UserGroup[]) { + const userGroups = + groups?.filter(group => group.users?.find(u => u._id === user._id)) || [] + const userGroupApps = userGroups.flatMap(userGroup => + Object.keys(userGroup.roles || {}) + ) + const fullList = [...Object.keys(user.roles), ...userGroupApps] + return [...new Set(fullList)] +} From a1589b0dc05af57d65aa9ac6dda7dd81d3ea814f Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 24 Feb 2025 18:07:01 +0000 Subject: [PATCH 27/91] Adding group badges to users. --- packages/bbui/src/Badge/Badge.svelte | 2 ++ .../[application]/_components/BuilderSidePanel.svelte | 5 +++++ packages/shared-core/src/sdk/documents/users.ts | 9 +++++++-- 3 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/bbui/src/Badge/Badge.svelte b/packages/bbui/src/Badge/Badge.svelte index e4ec7d4f33..03aa544dfe 100644 --- a/packages/bbui/src/Badge/Badge.svelte +++ b/packages/bbui/src/Badge/Badge.svelte @@ -11,6 +11,7 @@ export let active = false export let inactive = false export let hoverable = false + export let customColor = null @@ -29,6 +30,7 @@ class:spectrum-Label--seafoam={seafoam} class:spectrum-Label--active={active} class:spectrum-Label--inactive={inactive} + style={customColor ? `background-color: ${customColor};` : ""} > diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 2260892913..5b1bf852aa 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -13,6 +13,7 @@ FancyInput, Button, FancySelect, + Badge, } from "@budibase/bbui" import { builderStore, appStore, roles, appPublished } from "@/stores/builder" import { @@ -741,11 +742,15 @@
    Access
    {#each allUsers as user} + {@const userGroups = sdk.users.getUserGroups(user, $groups)}
    {user.email}
    + {#each userGroups as group} + {group.name} + {/each}
    group.users?.find(u => u._id === user._id)) || [] + ) +} + +export function userAppAccessList(user: User, groups?: UserGroup[]) { + const userGroups = getUserGroups(user, groups) const userGroupApps = userGroups.flatMap(userGroup => Object.keys(userGroup.roles || {}) ) From f7d216c188562cf793673e04d3a17e5face33264 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Mon, 24 Feb 2025 18:08:20 +0000 Subject: [PATCH 28/91] Setting override placeholder. --- .../app/[application]/_components/BuilderSidePanel.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 5b1bf852aa..a9d3bb70ba 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -755,7 +755,7 @@
    Date: Tue, 25 Feb 2025 10:45:50 +0000 Subject: [PATCH 29/91] Changing how badges are displayed. --- .../_components/BuilderSidePanel.svelte | 27 ++++++++++++++----- .../shared-core/src/sdk/documents/users.ts | 12 +++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index a9d3bb70ba..8136dd256c 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -742,15 +742,19 @@
    Access
    {#each allUsers as user} - {@const userGroups = sdk.users.getUserGroups(user, $groups)} + {@const userGroups = sdk.users.getUserAppGroups($appStore.appId, user, $groups)}
    -
    - {user.email} +
    +
    + {user.email} +
    +
    + {#each userGroups as group} + {group.name} + {/each} +
    - {#each userGroups as group} - {group.name} - {/each}
    diff --git a/packages/shared-core/src/sdk/documents/users.ts b/packages/shared-core/src/sdk/documents/users.ts index 8b5abfd822..d2ee2dec00 100644 --- a/packages/shared-core/src/sdk/documents/users.ts +++ b/packages/shared-core/src/sdk/documents/users.ts @@ -137,6 +137,18 @@ export function getUserGroups(user: User, groups?: UserGroup[]) { ) } +export function getUserAppGroups( + appId: string, + user: User, + groups?: UserGroup[] +) { + const prodAppId = getProdAppID(appId) + const userGroups = getUserGroups(user, groups) + return userGroups.filter(group => + Object.keys(group.roles || {}).find(app => app === prodAppId) + ) +} + export function userAppAccessList(user: User, groups?: UserGroup[]) { const userGroups = getUserGroups(user, groups) const userGroupApps = userGroups.flatMap(userGroup => From aaa1603d1b54ce9587727a4930ebc9f0c3545535 Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Tue, 25 Feb 2025 15:55:13 +0000 Subject: [PATCH 30/91] Rewrite relationship field --- .../app/forms/RelationshipField.svelte | 443 +++++++++++------- 1 file changed, 276 insertions(+), 167 deletions(-) diff --git a/packages/client/src/components/app/forms/RelationshipField.svelte b/packages/client/src/components/app/forms/RelationshipField.svelte index 54171309de..5da03eba2b 100644 --- a/packages/client/src/components/app/forms/RelationshipField.svelte +++ b/packages/client/src/components/app/forms/RelationshipField.svelte @@ -1,17 +1,23 @@ {#if fieldState} option.primaryDisplay} getOptionValue={option => option._id} + {options} {placeholder} + {autocomplete} bind:searchTerm - loading={$fetch.loading} bind:open + on:change={handleChange} + on:loadMore={() => fetch?.nextPage()} /> {/if} From bf673bff71231a6c6b5d5307a7ccb401dd1910bf Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Tue, 25 Feb 2025 16:20:58 +0000 Subject: [PATCH 31/91] Fix filtering options --- .../app/forms/RelationshipField.svelte | 33 ++++++++++--------- 1 file changed, 17 insertions(+), 16 deletions(-) diff --git a/packages/client/src/components/app/forms/RelationshipField.svelte b/packages/client/src/components/app/forms/RelationshipField.svelte index 5da03eba2b..914d552e06 100644 --- a/packages/client/src/components/app/forms/RelationshipField.svelte +++ b/packages/client/src/components/app/forms/RelationshipField.svelte @@ -89,8 +89,8 @@ $: updateOptions(optionsMap) $: !open && sortOptions() - // Fetch new options when search term changes - $: debouncedFetchRows(searchTerm, primaryDisplay) + // Search for new options when search term changes + $: debouncedSearchOptions(searchTerm || "", primaryDisplayField) // Ensure backwards compatibility $: enrichedDefaultValue = enrichDefaultValue(defaultValue) @@ -310,28 +310,29 @@ return val.includes(",") ? val.split(",") : val } - async function fetchRows(searchTerm: any, primaryDisplay: string) { - // Don't request until we have the primary display or default value has been fetched + // Searches for new options matching the given term + async function searchOptions(searchTerm: string, primaryDisplay?: string) { if (!primaryDisplay) { return } // Ensure we match all filters, rather than any - // @ts-expect-error this doesn't fit types, but don't want to change it yet - const baseFilter: any = (filter || []).filter(x => x.operator !== "allOr") + let newFilter: any = filter + if (searchTerm) { + // @ts-expect-error this doesn't fit types, but don't want to change it yet + newFilter = (newFilter || []).filter(x => x.operator !== "allOr") + newFilter.push({ + // Use a big numeric prefix to avoid clashing with an existing filter + field: `999:${primaryDisplay}`, + operator: "string", + value: searchTerm, + }) + } await fetch?.update({ - filter: [ - ...baseFilter, - { - // Use a big numeric prefix to avoid clashing with an existing filter - field: `999:${primaryDisplay}`, - operator: "string", - value: searchTerm, - }, - ], + filter: newFilter, }) } - const debouncedFetchRows = Utils.debounce(fetchRows, 250) + const debouncedSearchOptions = Utils.debounce(searchOptions, 250) // Flattens an array of row-like objects into a simple array of row IDs const flatten = (values: any | any[]): string[] => { From 24fd3e5c860d294e04ea3825db70933149cbc88e Mon Sep 17 00:00:00 2001 From: Andrew Kingston Date: Tue, 25 Feb 2025 16:50:28 +0000 Subject: [PATCH 32/91] Use limit of 1 rather than 0 for readonly fields, as 0 seems to be treated as max page size --- .../client/src/components/app/forms/RelationshipField.svelte | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/client/src/components/app/forms/RelationshipField.svelte b/packages/client/src/components/app/forms/RelationshipField.svelte index 914d552e06..0226e7d7f3 100644 --- a/packages/client/src/components/app/forms/RelationshipField.svelte +++ b/packages/client/src/components/app/forms/RelationshipField.svelte @@ -135,7 +135,7 @@ datasource, options: { filter, - limit: writable ? 100 : 0, + limit: writable ? 100 : 1, }, }) } From df102e7b6b6e9e518bfec8907eba79782f06b551 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Tue, 25 Feb 2025 17:18:27 +0000 Subject: [PATCH 33/91] Opacity of group badges. --- packages/bbui/src/Badge/Badge.svelte | 2 +- .../app/[application]/_components/BuilderSidePanel.svelte | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/bbui/src/Badge/Badge.svelte b/packages/bbui/src/Badge/Badge.svelte index 03aa544dfe..15bb6c62c2 100644 --- a/packages/bbui/src/Badge/Badge.svelte +++ b/packages/bbui/src/Badge/Badge.svelte @@ -30,7 +30,7 @@ class:spectrum-Label--seafoam={seafoam} class:spectrum-Label--active={active} class:spectrum-Label--inactive={inactive} - style={customColor ? `background-color: ${customColor};` : ""} + style={customColor ? `background-color: ${customColor}` : ""} > diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 8136dd256c..ff4b872153 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -742,7 +742,7 @@
    Access
    {#each allUsers as user} - {@const userGroups = sdk.users.getUserAppGroups($appStore.appId, user, $groups)} + {@const userGroups = sdk.users.getUserAppGroups($appStore.appId, user, $groups).slice(0, 3)}
    @@ -751,7 +751,7 @@
    {#each userGroups as group} - {group.name} + {group.name} {/each}
    @@ -949,6 +949,8 @@ grid-template-columns: 1fr 220px; align-items: center; gap: var(--spacing-xl); + border-bottom: var(--border-light); + padding-bottom: var(--spacing-s); } .auth-entity .details { From c3de44a6a9270fba6b8184ed379fa4b304ba4efe Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Tue, 25 Feb 2025 18:17:41 +0000 Subject: [PATCH 34/91] Adding a way to limit the groups shown and then display a popover. --- packages/bbui/src/Icon/Icon.svelte | 3 ++ .../_components/BuilderGroupPopover.svelte | 49 +++++++++++++++++++ .../_components/BuilderSidePanel.svelte | 15 ++++-- .../_components/GroupBadge.svelte | 10 ++++ 4 files changed, 74 insertions(+), 3 deletions(-) create mode 100644 packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte create mode 100644 packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte diff --git a/packages/bbui/src/Icon/Icon.svelte b/packages/bbui/src/Icon/Icon.svelte index 2f12935f53..46b3140be8 100644 --- a/packages/bbui/src/Icon/Icon.svelte +++ b/packages/bbui/src/Icon/Icon.svelte @@ -28,6 +28,9 @@ + import { Icon, Popover } from "@budibase/bbui" + import GroupBadge from "./GroupBadge.svelte" + + export let groups = [] + + let anchor, popover + + function show() { + popover.show() + } + + function hide() { + popover.hide() + } + + +
    + +
    + + +
    + {#each groups as group} + + {/each} +
    +
    + + diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index ff4b872153..11a36706cf 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -38,6 +38,8 @@ import { emailValidator } from "@/helpers/validation" import { fly } from "svelte/transition" import InfoDisplay from "../design/[screenId]/[componentId]/_components/Component/InfoDisplay.svelte" + import BuilderGroupPopover from "./BuilderGroupPopover.svelte" + import GroupBadge from "./GroupBadge.svelte" let query = null let loaded = false @@ -742,7 +744,11 @@
    Access
    {#each allUsers as user} - {@const userGroups = sdk.users.getUserAppGroups($appStore.appId, user, $groups).slice(0, 3)} + {@const userGroups = sdk.users.getUserAppGroups( + $appStore.appId, + user, + $groups + )}
    @@ -750,9 +756,12 @@ {user.email}
    - {#each userGroups as group} - {group.name} + {#each userGroups.slice(0, 3) as group} + {/each} + {#if userGroups.length > 3} + + {/if}
    diff --git a/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte b/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte new file mode 100644 index 0000000000..f10e2aa220 --- /dev/null +++ b/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte @@ -0,0 +1,10 @@ + + +{name} From 433c20d80cbd1e48b5bebddf387843a2787c41e1 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Tue, 25 Feb 2025 18:23:29 +0000 Subject: [PATCH 35/91] wip --- .../src/api/routes/public/tests/users.spec.ts | 79 ++++++++++--------- .../src/api/routes/tests/utilities/index.ts | 38 --------- .../src/tests/utilities/TestConfiguration.ts | 32 +++++--- .../server/src/tests/utilities/api/base.ts | 56 +++++++++---- .../server/src/tests/utilities/api/index.ts | 8 ++ .../src/tests/utilities/api/public/user.ts | 19 +++++ 6 files changed, 129 insertions(+), 103 deletions(-) create mode 100644 packages/server/src/tests/utilities/api/public/user.ts diff --git a/packages/server/src/api/routes/public/tests/users.spec.ts b/packages/server/src/api/routes/public/tests/users.spec.ts index 4ca9ff8104..4983761c3a 100644 --- a/packages/server/src/api/routes/public/tests/users.spec.ts +++ b/packages/server/src/api/routes/public/tests/users.spec.ts @@ -1,27 +1,44 @@ import * as setup from "../../tests/utilities" -import { generateMakeRequest, MakeRequestResponse } from "./utils" import { User } from "@budibase/types" import { mocks } from "@budibase/backend-core/tests" +import nock from "nock" +import environment from "../../../../environment" +import TestConfiguration from "../../../../tests/utilities/TestConfiguration" -import * as workerRequests from "../../../../utilities/workerRequests" - -const mockedWorkerReq = jest.mocked(workerRequests) - -let config = setup.getConfig() -let apiKey: string, globalUser: User, makeRequest: MakeRequestResponse +const config = new TestConfiguration() +let globalUser: User beforeAll(async () => { await config.init() - globalUser = await config.globalUser() - apiKey = await config.generateApiKey(globalUser._id) - makeRequest = generateMakeRequest(apiKey) - mockedWorkerReq.readGlobalUser.mockImplementation(() => - Promise.resolve(globalUser) - ) }) afterAll(setup.afterAll) +beforeEach(async () => { + globalUser = await config.globalUser() + + nock.cleanAll() + nock(environment.WORKER_URL!) + .get(`/api/global/users/${globalUser._id}`) + .reply(200, (uri, body) => { + return globalUser + }) + .persist() + + nock(environment.WORKER_URL!) + .post(`/api/global/users`) + .reply(200, (uri, body) => { + const updatedUser = body as User + if (updatedUser._id === globalUser._id) { + globalUser = updatedUser + return globalUser + } else { + throw new Error("User not found") + } + }) + .persist() +}) + function base() { return { tenantId: config.getTenantId(), @@ -30,37 +47,26 @@ function base() { } } -function updateMock() { - mockedWorkerReq.readGlobalUser.mockImplementation(ctx => ctx.request.body) -} - -describe("check user endpoints", () => { +describe.only("check user endpoints", () => { it("should not allow a user to update their own roles", async () => { - const res = await makeRequest("put", `/users/${globalUser._id}`, { - ...globalUser, - roles: { - app_1: "ADMIN", - }, - }) - expect( - mockedWorkerReq.saveGlobalUser.mock.lastCall?.[0].body.data.roles["app_1"] - ).toBeUndefined() - expect(res.status).toBe(200) - expect(res.body.data.roles["app_1"]).toBeUndefined() + await config.withUser(globalUser, () => + config.api.public.user.update({ + ...globalUser, + roles: { app_1: "ADMIN" }, + }) + ) + const updatedUser = await config.api.user.find(globalUser._id!) + expect(updatedUser.roles?.app_1).toBeUndefined() }) it("should not allow a user to delete themselves", async () => { - const res = await makeRequest("delete", `/users/${globalUser._id}`) - expect(res.status).toBe(405) - expect(mockedWorkerReq.deleteGlobalUser.mock.lastCall).toBeUndefined() + await config.withUser(globalUser, () => + config.api.public.user.destroy(globalUser._id!, { status: 405 }) + ) }) }) describe("no user role update in free", () => { - beforeAll(() => { - updateMock() - }) - it("should not allow 'roles' to be updated", async () => { const res = await makeRequest("post", "/users", { ...base(), @@ -94,7 +100,6 @@ describe("no user role update in free", () => { describe("no user role update in business", () => { beforeAll(() => { - updateMock() mocks.licenses.useExpandedPublicApi() }) diff --git a/packages/server/src/api/routes/tests/utilities/index.ts b/packages/server/src/api/routes/tests/utilities/index.ts index dcb8ccd6c0..944a56d7ba 100644 --- a/packages/server/src/api/routes/tests/utilities/index.ts +++ b/packages/server/src/api/routes/tests/utilities/index.ts @@ -3,44 +3,6 @@ import supertest from "supertest" export * as structures from "../../../../tests/utilities/structures" -function user() { - return { - _id: "user", - _rev: "rev", - createdAt: Date.now(), - email: "test@example.com", - roles: {}, - tenantId: "default", - status: "active", - } -} - -jest.mock("../../../../utilities/workerRequests", () => ({ - getGlobalUsers: jest.fn(() => { - return { - _id: "us_uuid1", - } - }), - getGlobalSelf: jest.fn(() => { - return { - _id: "us_uuid1", - } - }), - allGlobalUsers: jest.fn(() => { - return [user()] - }), - readGlobalUser: jest.fn(() => { - return user() - }), - saveGlobalUser: jest.fn(() => { - return { _id: "user", _rev: "rev" } - }), - deleteGlobalUser: jest.fn(() => { - return { message: "deleted user" } - }), - removeAppFromUserRoles: jest.fn(), -})) - export function delay(ms: number) { return new Promise(resolve => setTimeout(resolve, ms)) } diff --git a/packages/server/src/tests/utilities/TestConfiguration.ts b/packages/server/src/tests/utilities/TestConfiguration.ts index edb397169d..219a428f05 100644 --- a/packages/server/src/tests/utilities/TestConfiguration.ts +++ b/packages/server/src/tests/utilities/TestConfiguration.ts @@ -67,6 +67,7 @@ import { View, Webhook, WithRequired, + DevInfo, } from "@budibase/types" import API from "./api" @@ -248,7 +249,7 @@ export default class TestConfiguration { } } - async withUser(user: User, f: () => Promise) { + async withUser(user: User, f: () => Promise): Promise { const oldUser = this.user this.user = user try { @@ -469,7 +470,10 @@ export default class TestConfiguration { } } - defaultHeaders(extras = {}, prodApp = false) { + defaultHeaders( + extras: Record = {}, + prodApp = false + ) { const tenantId = this.getTenantId() const user = this.getUser() const authObj: AuthToken = { @@ -498,10 +502,13 @@ export default class TestConfiguration { } } - publicHeaders({ prodApp = true } = {}) { + publicHeaders({ + prodApp = true, + extras = {}, + }: { prodApp?: boolean; extras?: Record } = {}) { const appId = prodApp ? this.prodAppId : this.appId - const headers: any = { + const headers: Record = { Accept: "application/json", Cookie: "", } @@ -514,6 +521,7 @@ export default class TestConfiguration { return { ...headers, ...this.temporaryHeaders, + ...extras, } } @@ -577,17 +585,17 @@ export default class TestConfiguration { } const db = tenancy.getTenantDB(this.getTenantId()) const id = dbCore.generateDevInfoID(userId) - let devInfo: any - try { - devInfo = await db.get(id) - } catch (err) { - devInfo = { _id: id, userId } + const devInfo = await db.tryGet(id) + if (devInfo && devInfo.apiKey) { + return devInfo.apiKey } - devInfo.apiKey = encryption.encrypt( + + const apiKey = encryption.encrypt( `${this.getTenantId()}${dbCore.SEPARATOR}${newid()}` ) - await db.put(devInfo) - return devInfo.apiKey + const newDevInfo: DevInfo = { _id: id, userId, apiKey } + await db.put(newDevInfo) + return apiKey } // APP diff --git a/packages/server/src/tests/utilities/api/base.ts b/packages/server/src/tests/utilities/api/base.ts index 39ac5cefc0..177c3c3c0b 100644 --- a/packages/server/src/tests/utilities/api/base.ts +++ b/packages/server/src/tests/utilities/api/base.ts @@ -46,6 +46,7 @@ export interface RequestOpts { export abstract class TestAPI { config: TestConfiguration request: SuperTest + prefix = "" constructor(config: TestConfiguration) { this.config = config @@ -53,26 +54,26 @@ export abstract class TestAPI { } protected _get = async (url: string, opts?: RequestOpts): Promise => { - return await this._request("get", url, opts) + return await this._request("get", `${this.prefix}${url}`, opts) } protected _post = async (url: string, opts?: RequestOpts): Promise => { - return await this._request("post", url, opts) + return await this._request("post", `${this.prefix}${url}`, opts) } protected _put = async (url: string, opts?: RequestOpts): Promise => { - return await this._request("put", url, opts) + return await this._request("put", `${this.prefix}${url}`, opts) } protected _patch = async (url: string, opts?: RequestOpts): Promise => { - return await this._request("patch", url, opts) + return await this._request("patch", `${this.prefix}${url}`, opts) } protected _delete = async ( url: string, opts?: RequestOpts ): Promise => { - return await this._request("delete", url, opts) + return await this._request("delete", `${this.prefix}${url}`, opts) } protected _requestRaw = async ( @@ -88,7 +89,6 @@ export abstract class TestAPI { fields = {}, files = {}, expectations, - publicUser = false, } = opts || {} const { status = 200 } = expectations || {} const expectHeaders = expectations?.headers || {} @@ -97,7 +97,7 @@ export abstract class TestAPI { expectHeaders["Content-Type"] = /^application\/json/ } - let queryParams = [] + let queryParams: string[] = [] for (const [key, value] of Object.entries(query)) { if (value) { queryParams.push(`${key}=${value}`) @@ -107,18 +107,10 @@ export abstract class TestAPI { url += `?${queryParams.join("&")}` } - const headersFn = publicUser - ? (_extras = {}) => - this.config.publicHeaders.bind(this.config)({ - prodApp: opts?.useProdApp, - }) - : (extras = {}) => - this.config.defaultHeaders.bind(this.config)(extras, opts?.useProdApp) - const app = getServer() let req = request(app)[method](url) req = req.set( - headersFn({ + await this.getHeaders(opts, { "x-budibase-include-stacktrace": "true", }) ) @@ -167,6 +159,17 @@ export abstract class TestAPI { } } + protected async getHeaders( + opts?: RequestOpts, + extras?: Record + ): Promise> { + if (opts?.publicUser) { + return this.config.publicHeaders({ prodApp: opts?.useProdApp, extras }) + } else { + return this.config.defaultHeaders(extras, opts?.useProdApp) + } + } + protected _checkResponse = ( response: Response, expectations?: Expectations @@ -236,3 +239,24 @@ export abstract class TestAPI { ).body } } + +export abstract class PublicAPI extends TestAPI { + prefix = "/api/public/v1" + + protected async getHeaders( + opts?: RequestOpts, + extras?: Record + ): Promise> { + const apiKey = await this.config.generateApiKey() + + const headers: Record = { + Accept: "application/json", + Host: this.config.tenantHost(), + "x-budibase-api-key": apiKey, + "x-budibase-app-id": this.config.getAppId(), + ...extras, + } + + return headers + } +} diff --git a/packages/server/src/tests/utilities/api/index.ts b/packages/server/src/tests/utilities/api/index.ts index 2fdf726b6c..1252b10e40 100644 --- a/packages/server/src/tests/utilities/api/index.ts +++ b/packages/server/src/tests/utilities/api/index.ts @@ -17,6 +17,7 @@ import { RowActionAPI } from "./rowAction" import { AutomationAPI } from "./automation" import { PluginAPI } from "./plugin" import { WebhookAPI } from "./webhook" +import { UserPublicAPI } from "./public/user" export default class API { application: ApplicationAPI @@ -38,6 +39,10 @@ export default class API { viewV2: ViewV2API webhook: WebhookAPI + public: { + user: UserPublicAPI + } + constructor(config: TestConfiguration) { this.application = new ApplicationAPI(config) this.attachment = new AttachmentAPI(config) @@ -57,5 +62,8 @@ export default class API { this.user = new UserAPI(config) this.viewV2 = new ViewV2API(config) this.webhook = new WebhookAPI(config) + this.public = { + user: new UserPublicAPI(config), + } } } diff --git a/packages/server/src/tests/utilities/api/public/user.ts b/packages/server/src/tests/utilities/api/public/user.ts new file mode 100644 index 0000000000..e33b85ad9a --- /dev/null +++ b/packages/server/src/tests/utilities/api/public/user.ts @@ -0,0 +1,19 @@ +import { User } from "@budibase/types" +import { Expectations, PublicAPI } from "../base" + +export class UserPublicAPI extends PublicAPI { + find = async (id: string, expectations?: Expectations): Promise => { + return await this._get(`/users/${id}`, { expectations }) + } + + update = async (user: User, expectations?: Expectations): Promise => { + return await this._put(`/users/${user._id}`, { + body: user, + expectations, + }) + } + + destroy = async (id: string, expectations?: Expectations): Promise => { + return await this._delete(`/users/${id}`, { expectations }) + } +} From 5b285940f13da0b9fb43f74fcd526eb0acd28a91 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Wed, 26 Feb 2025 12:02:35 +0000 Subject: [PATCH 36/91] Introduce test error propagation to public API endpoints. --- .../src/api/controllers/public/users.ts | 2 +- .../server/src/api/routes/public/index.ts | 5 +++ .../public/middleware/testErrorHandling.ts | 24 ++++++++++++++ .../src/api/routes/public/tests/users.spec.ts | 32 +++++++++---------- .../src/tests/utilities/api/public/user.ts | 13 +++++++- 5 files changed, 58 insertions(+), 18 deletions(-) create mode 100644 packages/server/src/api/routes/public/middleware/testErrorHandling.ts diff --git a/packages/server/src/api/controllers/public/users.ts b/packages/server/src/api/controllers/public/users.ts index 4265c7ac22..c0cd3248a2 100644 --- a/packages/server/src/api/controllers/public/users.ts +++ b/packages/server/src/api/controllers/public/users.ts @@ -48,7 +48,7 @@ function getUser(ctx: UserCtx, userId?: string) { if (userId) { ctx.params = { userId } } else if (!ctx.params?.userId) { - throw "No user ID provided for getting" + throw new Error("No user ID provided for getting") } return readGlobalUser(ctx) } diff --git a/packages/server/src/api/routes/public/index.ts b/packages/server/src/api/routes/public/index.ts index 531192811c..e4fd9d5ea7 100644 --- a/packages/server/src/api/routes/public/index.ts +++ b/packages/server/src/api/routes/public/index.ts @@ -12,6 +12,7 @@ import { paramResource, paramSubResource } from "../../../middleware/resourceId" import { PermissionLevel, PermissionType } from "@budibase/types" import { CtxFn } from "./utils/Endpoint" import mapperMiddleware from "./middleware/mapper" +import testErrorHandling from "./middleware/testErrorHandling" import env from "../../../environment" import { middleware, redis } from "@budibase/backend-core" import { SelectableDatabase } from "@budibase/backend-core/src/redis/utils" @@ -144,6 +145,10 @@ function applyRoutes( // add the output mapper middleware addMiddleware(endpoints.read, mapperMiddleware, { output: true }) addMiddleware(endpoints.write, mapperMiddleware, { output: true }) + if (env.isTest()) { + addMiddleware(endpoints.read, testErrorHandling) + addMiddleware(endpoints.write, testErrorHandling) + } addToRouter(endpoints.read) addToRouter(endpoints.write) } diff --git a/packages/server/src/api/routes/public/middleware/testErrorHandling.ts b/packages/server/src/api/routes/public/middleware/testErrorHandling.ts new file mode 100644 index 0000000000..82519102d2 --- /dev/null +++ b/packages/server/src/api/routes/public/middleware/testErrorHandling.ts @@ -0,0 +1,24 @@ +import { Ctx } from "@budibase/types" +import environment from "../../../../environment" + +export default async (ctx: Ctx, next: any) => { + try { + await next() + } catch (err: any) { + if ( + !(environment.isTest() && ctx.headers["x-budibase-include-stacktrace"]) + ) { + throw err + } + + const status = err.status || err.statusCode || 500 + + let error = err + while (error.cause) { + error = error.cause + } + + ctx.status = status + ctx.body = { status, message: error.message, stack: error.stack } + } +} diff --git a/packages/server/src/api/routes/public/tests/users.spec.ts b/packages/server/src/api/routes/public/tests/users.spec.ts index 4983761c3a..fbfb7bbd61 100644 --- a/packages/server/src/api/routes/public/tests/users.spec.ts +++ b/packages/server/src/api/routes/public/tests/users.spec.ts @@ -1,12 +1,13 @@ import * as setup from "../../tests/utilities" import { User } from "@budibase/types" -import { mocks } from "@budibase/backend-core/tests" +import { generator, mocks } from "@budibase/backend-core/tests" import nock from "nock" import environment from "../../../../environment" import TestConfiguration from "../../../../tests/utilities/TestConfiguration" const config = new TestConfiguration() let globalUser: User +let users: Record = {} beforeAll(async () => { await config.init() @@ -16,25 +17,26 @@ afterAll(setup.afterAll) beforeEach(async () => { globalUser = await config.globalUser() + users[globalUser._id!] = globalUser nock.cleanAll() nock(environment.WORKER_URL!) - .get(`/api/global/users/${globalUser._id}`) + .get(new RegExp(`/api/global/users/.*`)) .reply(200, (uri, body) => { - return globalUser + const id = uri.split("/").pop() + return users[id!] }) .persist() nock(environment.WORKER_URL!) .post(`/api/global/users`) .reply(200, (uri, body) => { - const updatedUser = body as User - if (updatedUser._id === globalUser._id) { - globalUser = updatedUser - return globalUser - } else { - throw new Error("User not found") + const newUser = body as User + if (!newUser._id) { + newUser._id = `us_${generator.guid()}` } + users[newUser._id!] = newUser + return newUser }) .persist() }) @@ -47,7 +49,7 @@ function base() { } } -describe.only("check user endpoints", () => { +describe("check user endpoints", () => { it("should not allow a user to update their own roles", async () => { await config.withUser(globalUser, () => config.api.public.user.update({ @@ -67,14 +69,12 @@ describe.only("check user endpoints", () => { }) describe("no user role update in free", () => { - it("should not allow 'roles' to be updated", async () => { - const res = await makeRequest("post", "/users", { - ...base(), + it.only("should not allow 'roles' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), roles: { app_a: "BASIC" }, }) - expect(res.status).toBe(200) - expect(res.body.data.roles["app_a"]).toBeUndefined() - expect(res.body.message).toBeDefined() + expect(newUser.roles["app_a"]).toBeUndefined() }) it("should not allow 'admin' to be updated", async () => { diff --git a/packages/server/src/tests/utilities/api/public/user.ts b/packages/server/src/tests/utilities/api/public/user.ts index e33b85ad9a..a8a7baed7f 100644 --- a/packages/server/src/tests/utilities/api/public/user.ts +++ b/packages/server/src/tests/utilities/api/public/user.ts @@ -1,4 +1,4 @@ -import { User } from "@budibase/types" +import { UnsavedUser, User } from "@budibase/types" import { Expectations, PublicAPI } from "../base" export class UserPublicAPI extends PublicAPI { @@ -16,4 +16,15 @@ export class UserPublicAPI extends PublicAPI { destroy = async (id: string, expectations?: Expectations): Promise => { return await this._delete(`/users/${id}`, { expectations }) } + + create = async ( + user: UnsavedUser, + expectations?: Expectations + ): Promise => { + const response = await this._post<{ data: User }>("/users", { + body: user, + expectations, + }) + return response.data + } } From 336bc72de27860e8941e3a984929d2b83062de01 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Wed, 26 Feb 2025 12:53:18 +0000 Subject: [PATCH 37/91] Design after discussion with Cheeks and Joe. --- packages/bbui/src/Badge/Badge.svelte | 4 +- .../_components/BuilderGroupPopover.svelte | 41 +++------------- .../_components/BuilderSidePanel.svelte | 48 ++++++++++--------- .../_components/GroupBadge.svelte | 10 ---- packages/shared-core/src/helpers/index.ts | 1 + packages/shared-core/src/helpers/lists.ts | 7 +++ 6 files changed, 43 insertions(+), 68 deletions(-) delete mode 100644 packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte create mode 100644 packages/shared-core/src/helpers/lists.ts diff --git a/packages/bbui/src/Badge/Badge.svelte b/packages/bbui/src/Badge/Badge.svelte index 15bb6c62c2..dadbaa3317 100644 --- a/packages/bbui/src/Badge/Badge.svelte +++ b/packages/bbui/src/Badge/Badge.svelte @@ -11,7 +11,7 @@ export let active = false export let inactive = false export let hoverable = false - export let customColor = null + export let outlineColor = null @@ -30,7 +30,7 @@ class:spectrum-Label--seafoam={seafoam} class:spectrum-Label--active={active} class:spectrum-Label--inactive={inactive} - style={customColor ? `background-color: ${customColor}` : ""} + style={outlineColor ? `border: 2px solid ${outlineColor}` : ""} > diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte index 47811cbcb9..43c662a6d2 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte @@ -1,49 +1,22 @@ -
    - +
    +
    - -
    - {#each groups as group} - - {/each} -
    -
    - diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 11a36706cf..0bf32e4b76 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -13,7 +13,6 @@ FancyInput, Button, FancySelect, - Badge, } from "@budibase/bbui" import { builderStore, appStore, roles, appPublished } from "@/stores/builder" import { @@ -39,7 +38,6 @@ import { fly } from "svelte/transition" import InfoDisplay from "../design/[screenId]/[componentId]/_components/Component/InfoDisplay.svelte" import BuilderGroupPopover from "./BuilderGroupPopover.svelte" - import GroupBadge from "./GroupBadge.svelte" let query = null let loaded = false @@ -542,6 +540,12 @@ creationAccessType = Constants.Roles.CREATOR } } + + const itemCountText = (word, count) => { + return `${count} ${word}${ + count !== 1 ? "s" : "" + }` + } @@ -708,9 +712,7 @@ {group.name}
    - {`${group.users?.length} user${ - group.users?.length != 1 ? "s" : "" - }`} + {itemCountText("user", group.users?.length)}
    @@ -755,20 +757,20 @@
    {user.email}
    -
    - {#each userGroups.slice(0, 3) as group} - - {/each} - {#if userGroups.length > 3} - - {/if} -
    + {#if userGroups.length} +
    +
    + {itemCountText("group", userGroups.length)} +
    + +
    + {/if}
    diff --git a/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte b/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte deleted file mode 100644 index f10e2aa220..0000000000 --- a/packages/builder/src/pages/builder/app/[application]/_components/GroupBadge.svelte +++ /dev/null @@ -1,10 +0,0 @@ - - -{name} diff --git a/packages/shared-core/src/helpers/index.ts b/packages/shared-core/src/helpers/index.ts index 0aa378b46a..b924617a0f 100644 --- a/packages/shared-core/src/helpers/index.ts +++ b/packages/shared-core/src/helpers/index.ts @@ -6,3 +6,4 @@ export * as cron from "./cron" export * as schema from "./schema" export * as views from "./views" export * as roles from "./roles" +export * as lists from "./lists" diff --git a/packages/shared-core/src/helpers/lists.ts b/packages/shared-core/src/helpers/lists.ts new file mode 100644 index 0000000000..64b906fef8 --- /dev/null +++ b/packages/shared-core/src/helpers/lists.ts @@ -0,0 +1,7 @@ +export function punctuateList(list: string[]) { + if (list.length === 0) return "" + if (list.length === 1) return list[0] + if (list.length === 2) return list.join(" and ") + // For more than 2 elements: join all but the last with commas, then add "and" before the last element. + return list.slice(0, -1).join(", ") + " and " + list[list.length - 1] +} From c2841b824d5ad83a12fe777f356ae0ef55548152 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Wed, 26 Feb 2025 13:25:58 +0000 Subject: [PATCH 38/91] Linting. --- .../_components/BuilderGroupPopover.svelte | 13 +++++++++++-- .../_components/BuilderSidePanel.svelte | 8 ++++---- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte index 43c662a6d2..367d84e029 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderGroupPopover.svelte @@ -4,13 +4,22 @@ export let groups = [] function tooltip(groups) { - const sortedNames = groups.sort((a, b) => a.name.localeCompare(b.name)).map(group => group.name) + const sortedNames = groups + .sort((a, b) => a.name.localeCompare(b.name)) + .map(group => group.name) return `Member of ${helpers.lists.punctuateList(sortedNames)}` }
    - +
    From b0c4bc5d3dbb887b0597c63d0293de9cb6845942 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 13:10:09 +0100 Subject: [PATCH 45/91] Remove unnecessary numArgs --- .../scripts/gen-collection-info.ts | 5 - packages/string-templates/src/manifest.json | 138 ------------------ 2 files changed, 143 deletions(-) diff --git a/packages/string-templates/scripts/gen-collection-info.ts b/packages/string-templates/scripts/gen-collection-info.ts index 61edd0d2fb..ffe9f68add 100644 --- a/packages/string-templates/scripts/gen-collection-info.ts +++ b/packages/string-templates/scripts/gen-collection-info.ts @@ -17,7 +17,6 @@ type BudibaseAnnotation = Annotation & { type Helper = { args: string[] - numArgs: number example?: string description: string requiresBlock?: boolean @@ -35,14 +34,12 @@ const ADDED_HELPERS = { date: { date: { args: ["datetime", "format", "options"], - numArgs: 3, example: '{{date now "DD-MM-YYYY" "America/New_York" }} -> 21-01-2021', description: "Format a date using moment.js date formatting - the timezone is optional and uses the tz database.", }, duration: { args: ["time", "durationType"], - numArgs: 2, example: '{{duration 8 "seconds"}} -> a few seconds', description: "Produce a humanized duration left/until given an amount of time and the type of time measurement.", @@ -53,7 +50,6 @@ const ADDED_HELPERS = { function fixSpecialCases(name: string, obj: Helper) { if (name === "ifNth") { obj.args = ["a", "b", "options"] - obj.numArgs = 3 } if (name === "eachIndex") { obj.description = "Iterates the array, listing an item and the index of it." @@ -163,7 +159,6 @@ function run() { .map(tag => tag.description!.replace(/`/g, "").split(" ")[0].trim()) collectionInfo[name] = fixSpecialCases(name, { args, - numArgs: args.length, example: jsDocInfo.example || undefined, description: jsDocInfo.description, requiresBlock: jsDocInfo.acceptsBlock && !jsDocInfo.acceptsInline, diff --git a/packages/string-templates/src/manifest.json b/packages/string-templates/src/manifest.json index f36746f3d0..e47af7d69a 100644 --- a/packages/string-templates/src/manifest.json +++ b/packages/string-templates/src/manifest.json @@ -4,7 +4,6 @@ "args": [ "a" ], - "numArgs": 1, "example": "{{ abs 12012.1000 }} -> 12012.1", "description": "

    Return the magnitude of a.

    \n", "requiresBlock": false @@ -14,7 +13,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ add 1 2 }} -> 3", "description": "

    Return the sum of a plus b.

    \n", "requiresBlock": false @@ -23,7 +21,6 @@ "args": [ "array" ], - "numArgs": 1, "example": "{{ avg 1 2 3 4 5 }} -> 3", "description": "

    Returns the average of all numbers in the given array.

    \n", "requiresBlock": false @@ -32,7 +29,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{ ceil 1.2 }} -> 2", "description": "

    Get the Math.ceil() of the given value.

    \n", "requiresBlock": false @@ -42,7 +38,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ divide 10 5 }} -> 2", "description": "

    Divide a by b

    \n", "requiresBlock": false @@ -51,7 +46,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{ floor 1.2 }} -> 1", "description": "

    Get the Math.floor() of the given value.

    \n", "requiresBlock": false @@ -61,7 +55,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ subtract 10 5 }} -> 5", "description": "

    Return the product of a minus b.

    \n", "requiresBlock": false @@ -71,7 +64,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ modulo 10 5 }} -> 0", "description": "

    Get the remainder of a division operation.

    \n", "requiresBlock": false @@ -81,7 +73,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ multiply 10 5 }} -> 50", "description": "

    Multiply number a by number b.

    \n", "requiresBlock": false @@ -91,7 +82,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ plus 10 5 }} -> 15", "description": "

    Add a by b.

    \n", "requiresBlock": false @@ -101,7 +91,6 @@ "min", "max" ], - "numArgs": 2, "example": "{{ random 0 20 }} -> 10", "description": "

    Generate a random number between two values

    \n", "requiresBlock": false @@ -111,7 +100,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ remainder 10 6 }} -> 4", "description": "

    Get the remainder when a is divided by b.

    \n", "requiresBlock": false @@ -120,7 +108,6 @@ "args": [ "number" ], - "numArgs": 1, "example": "{{ round 10.3 }} -> 10", "description": "

    Round the given number.

    \n", "requiresBlock": false @@ -130,7 +117,6 @@ "a", "b" ], - "numArgs": 2, "example": "{{ subtract 10 5 }} -> 5", "description": "

    Return the product of a minus b.

    \n", "requiresBlock": false @@ -139,7 +125,6 @@ "args": [ "array" ], - "numArgs": 1, "example": "{{ sum [1, 2, 3] }} -> 6", "description": "

    Returns the sum of all numbers in the given array.

    \n", "requiresBlock": false @@ -151,7 +136,6 @@ "array", "n" ], - "numArgs": 2, "example": "{{ after ['a', 'b', 'c', 'd'] 2}} -> ['c', 'd']", "description": "

    Returns all of the items in an array after the specified index. Opposite of before.

    \n", "requiresBlock": false @@ -160,7 +144,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{ arrayify 'foo' }} -> ['foo']", "description": "

    Cast the given value to an array.

    \n", "requiresBlock": false @@ -170,7 +153,6 @@ "array", "n" ], - "numArgs": 2, "example": "{{ before ['a', 'b', 'c', 'd'] 3}} -> ['a', 'b']", "description": "

    Return all of the items in the collection before the specified count. Opposite of after.

    \n", "requiresBlock": false @@ -180,7 +162,6 @@ "array", "options" ], - "numArgs": 2, "example": "{{#eachIndex [1, 2, 3]}} {{item}} is {{index}} {{/eachIndex}} -> ' 1 is 0 2 is 1 3 is 2 '", "description": "

    Iterates the array, listing an item and the index of it.

    \n", "requiresBlock": true @@ -191,7 +172,6 @@ "value", "options" ], - "numArgs": 3, "example": "{{#filter [1, 2, 3] 2}}2 Found{{else}}2 not found{{/filter}} -> 2 Found", "description": "

    Block helper that filters the given array and renders the block for values that evaluate to true, otherwise the inverse block is returned.

    \n", "requiresBlock": true @@ -201,7 +181,6 @@ "array", "n" ], - "numArgs": 2, "example": "{{first [1, 2, 3, 4] 2}} -> 1,2", "description": "

    Returns the first item, or first n items of an array.

    \n", "requiresBlock": false @@ -211,7 +190,6 @@ "array", "options" ], - "numArgs": 2, "example": "{{#forEach [{ 'name': 'John' }] }} {{ name }} {{/forEach}} -> ' John '", "description": "

    Iterates over each item in an array and exposes the current item in the array as context to the inner block. In addition to the current array item, the helper exposes the following variables to the inner block: - index - total - isFirst - isLast Also, @index is exposed as a private variable, and additional private variables may be defined as hash arguments.

    \n", "requiresBlock": true @@ -222,7 +200,6 @@ "value", "options" ], - "numArgs": 3, "example": "{{#inArray [1, 2, 3] 2}} 2 exists {{else}} 2 does not exist {{/inArray}} -> ' 2 exists '", "description": "

    Block helper that renders the block if an array has the given value. Optionally specify an inverse block to render when the array does not have the given value.

    \n", "requiresBlock": true @@ -231,7 +208,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{isArray [1, 2]}} -> true", "description": "

    Returns true if value is an es5 array.

    \n", "requiresBlock": false @@ -241,7 +217,6 @@ "array", "idx" ], - "numArgs": 2, "example": "{{itemAt [1, 2, 3] 1}} -> 2", "description": "

    Returns the item from array at index idx.

    \n", "requiresBlock": false @@ -251,7 +226,6 @@ "array", "separator" ], - "numArgs": 2, "example": "{{join [1, 2, 3]}} -> 1, 2, 3", "description": "

    Join all elements of array into a string, optionally using a given separator.

    \n", "requiresBlock": false @@ -261,7 +235,6 @@ "value", "length" ], - "numArgs": 2, "example": "{{equalsLength [1, 2, 3] 3}} -> true", "description": "

    Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

    \n", "requiresBlock": false @@ -271,7 +244,6 @@ "value", "n" ], - "numArgs": 2, "example": "{{last [1, 2, 3]}} -> 3", "description": "

    Returns the last item, or last n items of an array or string. Opposite of first.

    \n", "requiresBlock": false @@ -280,7 +252,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{length [1, 2, 3]}} -> 3", "description": "

    Returns the length of the given string or array.

    \n", "requiresBlock": false @@ -290,7 +261,6 @@ "value", "length" ], - "numArgs": 2, "example": "{{equalsLength [1, 2, 3] 3}} -> true", "description": "

    Returns true if the the length of the given value is equal to the given length. Can be used as a block or inline helper.

    \n", "requiresBlock": false @@ -300,7 +270,6 @@ "array", "fn" ], - "numArgs": 2, "example": "{{map [1, 2, 3] double}} -> [2, 4, 6]", "description": "

    Returns a new array, created by calling function on each element of the given array. For example,

    \n", "requiresBlock": false @@ -310,7 +279,6 @@ "collection", "prop" ], - "numArgs": 2, "example": "{{pluck [{ 'name': 'Bob' }] 'name' }} -> ['Bob']", "description": "

    Map over the given object or array or objects and create an array of values from the given prop. Dot-notation may be used (as a string) to get nested properties.

    \n", "requiresBlock": false @@ -319,7 +287,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{reverse [1, 2, 3]}} -> [3, 2, 1]", "description": "

    Reverse the elements in an array, or the characters in a string.

    \n", "requiresBlock": false @@ -330,7 +297,6 @@ "iter", "provided" ], - "numArgs": 3, "example": "{{#some [1, \"b\", 3] isString}} string found {{else}} No string found {{/some}} -> ' string found '", "description": "

    Block helper that returns the block if the callback returns true for some value in the given array.

    \n", "requiresBlock": true @@ -340,7 +306,6 @@ "array", "key" ], - "numArgs": 2, "example": "{{ sort ['b', 'a', 'c'] }} -> ['a', 'b', 'c']", "description": "

    Sort the given array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

    \n", "requiresBlock": false @@ -350,7 +315,6 @@ "array", "props" ], - "numArgs": 2, "example": "{{ sortBy [{'a': 'zzz'}, {'a': 'aaa'}] 'a' }} -> [{'a':'aaa'},{'a':'zzz'}]", "description": "

    Sort an array. If an array of objects is passed, you may optionally pass a key to sort on as the second argument. You may alternatively pass a sorting function as the second argument.

    \n", "requiresBlock": false @@ -361,7 +325,6 @@ "idx", "options" ], - "numArgs": 3, "example": "{{#withAfter [1, 2, 3] 1 }} {{this}} {{/withAfter}} -> ' 2 3 '", "description": "

    Use the items in the array after the specified index as context inside a block. Opposite of withBefore.

    \n", "requiresBlock": true @@ -372,7 +335,6 @@ "idx", "options" ], - "numArgs": 3, "example": "{{#withBefore [1, 2, 3] 2 }} {{this}} {{/withBefore}} -> ' 1 '", "description": "

    Use the items in the array before the specified index as context inside a block. Opposite of withAfter.

    \n", "requiresBlock": true @@ -383,7 +345,6 @@ "idx", "options" ], - "numArgs": 3, "example": "{{#withFirst [1, 2, 3] }}{{this}}{{/withFirst}} -> 1", "description": "

    Use the first item in a collection inside a handlebars block expression. Opposite of withLast.

    \n", "requiresBlock": true @@ -394,7 +355,6 @@ "size", "options" ], - "numArgs": 3, "example": "{{#withGroup [1, 2, 3, 4] 2}}{{#each this}}{{.}}{{/each}}
    {{/withGroup}} -> 12
    34
    ", "description": "

    Block helper that groups array elements by given group size.

    \n", "requiresBlock": true @@ -405,7 +365,6 @@ "idx", "options" ], - "numArgs": 3, "example": "{{#withLast [1, 2, 3, 4]}}{{this}}{{/withLast}} -> 4", "description": "

    Use the last item or n items in an array as context inside a block. Opposite of withFirst.

    \n", "requiresBlock": true @@ -416,7 +375,6 @@ "prop", "options" ], - "numArgs": 3, "example": "{{#withSort ['b', 'a', 'c']}}{{this}}{{/withSort}} -> abc", "description": "

    Block helper that sorts a collection and exposes the sorted collection as context inside the block.

    \n", "requiresBlock": true @@ -426,7 +384,6 @@ "array", "options" ], - "numArgs": 2, "example": "{{#each (unique ['a', 'a', 'c', 'b', 'e', 'e']) }}{{.}}{{/each}} -> acbe", "description": "

    Block helper that return an array with all duplicate values removed. Best used along with a each helper.

    \n", "requiresBlock": true @@ -437,7 +394,6 @@ "args": [ "number" ], - "numArgs": 1, "example": "{{ bytes 1386 1 }} -> 1.4 kB", "description": "

    Format a number to it's equivalent in bytes. If a string is passed, it's length will be formatted and returned. Examples: - 'foo' => 3 B - 13661855 => 13.66 MB - 825399 => 825.39 kB - 1396 => 1.4 kB

    \n", "requiresBlock": false @@ -446,7 +402,6 @@ "args": [ "num" ], - "numArgs": 1, "example": "{{ addCommas 1000000 }} -> 1,000,000", "description": "

    Add commas to numbers

    \n", "requiresBlock": false @@ -455,7 +410,6 @@ "args": [ "num" ], - "numArgs": 1, "example": "{{ phoneNumber 8005551212 }} -> (800) 555-1212", "description": "

    Convert a string or number to a formatted phone number.

    \n", "requiresBlock": false @@ -465,7 +419,6 @@ "number", "precision" ], - "numArgs": 2, "example": "{{ toAbbr 10123 2 }} -> 10.12k", "description": "

    Abbreviate numbers to the given number of precision. This for general numbers, not size in bytes.

    \n", "requiresBlock": false @@ -475,7 +428,6 @@ "number", "fractionDigits" ], - "numArgs": 2, "example": "{{ toExponential 10123 2 }} -> 1.01e+4", "description": "

    Returns a string representing the given number in exponential notation.

    \n", "requiresBlock": false @@ -485,7 +437,6 @@ "number", "digits" ], - "numArgs": 2, "example": "{{ toFixed 1.1234 2 }} -> 1.12", "description": "

    Formats the given number using fixed-point notation.

    \n", "requiresBlock": false @@ -494,7 +445,6 @@ "args": [ "number" ], - "numArgs": 1, "description": "

    Convert input to a float.

    \n", "requiresBlock": false }, @@ -502,7 +452,6 @@ "args": [ "number" ], - "numArgs": 1, "description": "

    Convert input to an integer.

    \n", "requiresBlock": false }, @@ -511,7 +460,6 @@ "number", "precision" ], - "numArgs": 2, "example": "{{toPrecision '1.1234' 2}} -> 1.1", "description": "

    Returns a string representing the Number object to the specified precision.

    \n", "requiresBlock": false @@ -522,7 +470,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ encodeURI 'https://myurl?Hello There' }} -> https%3A%2F%2Fmyurl%3FHello%20There", "description": "

    Encodes a Uniform Resource Identifier (URI) component by replacing each instance of certain characters by one, two, three, or four escape sequences representing the UTF-8 encoding of the character.

    \n", "requiresBlock": false @@ -531,7 +478,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ escape 'https://myurl?Hello+There' }} -> https%3A%2F%2Fmyurl%3FHello%2BThere", "description": "

    Escape the given string by replacing characters with escape sequences. Useful for allowing the string to be used in a URL, etc.

    \n", "requiresBlock": false @@ -540,7 +486,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ decodeURI 'https://myurl?Hello%20There' }} -> https://myurl?Hello There", "description": "

    Decode a Uniform Resource Identifier (URI) component.

    \n", "requiresBlock": false @@ -550,7 +495,6 @@ "base", "href" ], - "numArgs": 2, "example": "{{ urlResolve 'https://myurl' '/api/test' }} -> https://myurl/api/test", "description": "

    Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.

    \n", "requiresBlock": false @@ -559,7 +503,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ urlParse 'https://myurl/api/test' }}", "description": "

    Parses a url string into an object.

    \n", "requiresBlock": false @@ -568,7 +511,6 @@ "args": [ "url" ], - "numArgs": 1, "example": "{{ stripQuerystring 'https://myurl/api/test?foo=bar' }} -> 'https://myurl/api/test'", "description": "

    Strip the query string from the given url.

    \n", "requiresBlock": false @@ -577,7 +519,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ stripProtocol 'https://myurl/api/test' }} -> '//myurl/api/test'", "description": "

    Strip protocol from a url. Useful for displaying media that may have an 'http' protocol on secure connections.

    \n", "requiresBlock": false @@ -589,7 +530,6 @@ "str", "suffix" ], - "numArgs": 2, "example": "{{append 'index' '.html'}} -> index.html", "description": "

    Append the specified suffix to the given string.

    \n", "requiresBlock": false @@ -598,7 +538,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{camelcase 'foo bar baz'}} -> fooBarBaz", "description": "

    camelCase the characters in the given string.

    \n", "requiresBlock": false @@ -607,7 +546,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{capitalize 'foo bar baz'}} -> Foo bar baz", "description": "

    Capitalize the first word in a sentence.

    \n", "requiresBlock": false @@ -616,7 +554,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{ capitalizeAll 'foo bar baz'}} -> Foo Bar Baz", "description": "

    Capitalize all words in a string.

    \n", "requiresBlock": false @@ -626,7 +563,6 @@ "str", "spaces" ], - "numArgs": 2, "example": "{{ center 'test' 1}} -> ' test '", "description": "

    Center a string using non-breaking spaces

    \n", "requiresBlock": false @@ -635,7 +571,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{ chop ' ABC '}} -> ABC", "description": "

    Like trim, but removes both extraneous whitespace and non-word characters from the beginning and end of a string.

    \n", "requiresBlock": false @@ -644,7 +579,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{dashcase 'a-b-c d_e'}} -> a-b-c-d-e", "description": "

    dash-case the characters in string. Replaces non-word characters and periods with hyphens.

    \n", "requiresBlock": false @@ -653,7 +587,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{dotcase 'a-b-c d_e'}} -> a.b.c.d.e", "description": "

    dot.case the characters in string.

    \n", "requiresBlock": false @@ -662,7 +595,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{downcase 'aBcDeF'}} -> abcdef", "description": "

    Lowercase all of the characters in the given string. Alias for lowercase.

    \n", "requiresBlock": false @@ -672,7 +604,6 @@ "str", "length" ], - "numArgs": 2, "example": "{{ellipsis 'foo bar baz' 7}} -> foo bar…", "description": "

    Truncates a string to the specified length, and appends it with an elipsis, ….

    \n", "requiresBlock": false @@ -681,7 +612,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{hyphenate 'foo bar baz qux'}} -> foo-bar-baz-qux", "description": "

    Replace spaces in a string with hyphens.

    \n", "requiresBlock": false @@ -690,7 +620,6 @@ "args": [ "value" ], - "numArgs": 1, "example": "{{isString 'foo'}} -> true", "description": "

    Return true if value is a string.

    \n", "requiresBlock": false @@ -699,7 +628,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{lowercase 'Foo BAR baZ'}} -> foo bar baz", "description": "

    Lowercase all characters in the given string.

    \n", "requiresBlock": false @@ -709,7 +637,6 @@ "str", "substring" ], - "numArgs": 2, "example": "{{occurrences 'foo bar foo bar baz' 'foo'}} -> 2", "description": "

    Return the number of occurrences of substring within the given string.

    \n", "requiresBlock": false @@ -718,7 +645,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{pascalcase 'foo bar baz'}} -> FooBarBaz", "description": "

    PascalCase the characters in string.

    \n", "requiresBlock": false @@ -727,7 +653,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{pathcase 'a-b-c d_e'}} -> a/b/c/d/e", "description": "

    path/case the characters in string.

    \n", "requiresBlock": false @@ -736,7 +661,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{plusify 'foo bar baz'}} -> foo+bar+baz", "description": "

    Replace spaces in the given string with pluses.

    \n", "requiresBlock": false @@ -746,7 +670,6 @@ "str", "prefix" ], - "numArgs": 2, "example": "{{prepend 'bar' 'foo-'}} -> foo-bar", "description": "

    Prepends the given string with the specified prefix.

    \n", "requiresBlock": false @@ -756,7 +679,6 @@ "str", "substring" ], - "numArgs": 2, "example": "{{remove 'a b a b a b' 'a '}} -> b b b", "description": "

    Remove all occurrences of substring from the given str.

    \n", "requiresBlock": false @@ -766,7 +688,6 @@ "str", "substring" ], - "numArgs": 2, "example": "{{removeFirst 'a b a b a b' 'a'}} -> ' b a b a b'", "description": "

    Remove the first occurrence of substring from the given str.

    \n", "requiresBlock": false @@ -777,7 +698,6 @@ "a", "b" ], - "numArgs": 3, "example": "{{replace 'a b a b a b' 'a' 'z'}} -> z b z b z b", "description": "

    Replace all occurrences of substring a with substring b.

    \n", "requiresBlock": false @@ -788,7 +708,6 @@ "a", "b" ], - "numArgs": 3, "example": "{{replaceFirst 'a b a b a b' 'a' 'z'}} -> z b a b a b", "description": "

    Replace the first occurrence of substring a with substring b.

    \n", "requiresBlock": false @@ -797,7 +716,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{sentence 'hello world. goodbye world.'}} -> Hello world. Goodbye world.", "description": "

    Sentence case the given string

    \n", "requiresBlock": false @@ -806,7 +724,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{snakecase 'a-b-c d_e'}} -> a_b_c_d_e", "description": "

    snake_case the characters in the given string.

    \n", "requiresBlock": false @@ -815,7 +732,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{split 'a,b,c'}} -> ['a', 'b', 'c']", "description": "

    Split string by the given character.

    \n", "requiresBlock": false @@ -826,7 +742,6 @@ "testString", "options" ], - "numArgs": 3, "example": "{{#startsWith 'Goodbye' 'Hello, world!'}}Yep{{else}}Nope{{/startsWith}} -> Nope", "description": "

    Tests whether a string begins with the given prefix.

    \n", "requiresBlock": true @@ -835,7 +750,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{titleize 'this is title case' }} -> This Is Title Case", "description": "

    Title case the given string.

    \n", "requiresBlock": false @@ -844,7 +758,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{trim ' ABC ' }} -> ABC", "description": "

    Removes extraneous whitespace from the beginning and end of a string.

    \n", "requiresBlock": false @@ -853,7 +766,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{trimLeft ' ABC ' }} -> 'ABC '", "description": "

    Removes extraneous whitespace from the beginning of a string.

    \n", "requiresBlock": false @@ -862,7 +774,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{trimRight ' ABC ' }} -> ' ABC'", "description": "

    Removes extraneous whitespace from the end of a string.

    \n", "requiresBlock": false @@ -873,7 +784,6 @@ "limit", "suffix" ], - "numArgs": 3, "example": "{{truncate 'foo bar baz' 7 }} -> foo bar", "description": "

    Truncate a string to the specified length. Also see ellipsis.

    \n", "requiresBlock": false @@ -884,7 +794,6 @@ "limit", "suffix" ], - "numArgs": 3, "example": "{{truncateWords 'foo bar baz' 1 }} -> foo…", "description": "

    Truncate a string to have the specified number of words. Also see truncate.

    \n", "requiresBlock": false @@ -893,7 +802,6 @@ "args": [ "string" ], - "numArgs": 1, "example": "{{upcase 'aBcDef'}} -> ABCDEF", "description": "

    Uppercase all of the characters in the given string. Alias for uppercase.

    \n", "requiresBlock": false @@ -903,7 +811,6 @@ "str", "options" ], - "numArgs": 2, "example": "{{uppercase 'aBcDef'}} -> ABCDEF", "description": "

    Uppercase all of the characters in the given string. If used as a block helper it will uppercase the entire block. This helper does not support inverse blocks.

    \n", "requiresBlock": false @@ -912,7 +819,6 @@ "args": [ "num" ], - "numArgs": 1, "example": "{{lorem 11}} -> Lorem ipsum", "description": "

    Takes a number and returns that many charaters of Lorem Ipsum

    \n", "requiresBlock": false @@ -925,7 +831,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#and great magnificent}}both{{else}}no{{/and}} -> no", "description": "

    Helper that renders the block if both of the given values are truthy. If an inverse block is specified it will be rendered when falsy. Works as a block helper, inline helper or subexpression.

    \n", "requiresBlock": true @@ -937,7 +842,6 @@ "b", "options" ], - "numArgs": 4, "example": "{{compare 10 '<' 5 }} -> false", "description": "

    Render a block when a comparison of the first and third arguments returns true. The second argument is the [arithemetic operator][operators] to use. You may also optionally specify an inverse block to render when falsy.

    \n", "requiresBlock": false @@ -949,7 +853,6 @@ "[startIndex=0]", "options" ], - "numArgs": 4, "example": "{{#contains ['a', 'b', 'c'] 'd'}} This will not be rendered. {{else}} This will be rendered. {{/contains}} -> ' This will be rendered. '", "description": "

    Block helper that renders the block if collection has the given value, using strict equality (===) for comparison, otherwise the inverse block is rendered (if specified). If a startIndex is specified and is negative, it is used as the offset from the end of the collection.

    \n", "requiresBlock": true @@ -959,7 +862,6 @@ "value", "defaultValue" ], - "numArgs": 2, "example": "{{default null null 'default'}} -> default", "description": "

    Returns the first value that is not undefined, otherwise the 'default' value is returned.

    \n", "requiresBlock": false @@ -970,7 +872,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#eq 3 3}}equal{{else}}not equal{{/eq}} -> equal", "description": "

    Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

    \n", "requiresBlock": true @@ -981,7 +882,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#gt 4 3}} greater than{{else}} not greater than{{/gt}} -> ' greater than'", "description": "

    Block helper that renders a block if a is greater than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

    \n", "requiresBlock": true @@ -992,7 +892,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#gte 4 3}} greater than or equal{{else}} not greater than{{/gte}} -> ' greater than or equal'", "description": "

    Block helper that renders a block if a is greater than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

    \n", "requiresBlock": true @@ -1003,7 +902,6 @@ "pattern", "options" ], - "numArgs": 3, "example": "{{#has 'foobar' 'foo'}}has it{{else}}doesn't{{/has}} -> has it", "description": "

    Block helper that renders a block if value has pattern. If an inverse block is specified it will be rendered when falsy.

    \n", "requiresBlock": true @@ -1013,7 +911,6 @@ "val", "options" ], - "numArgs": 2, "example": "{{isFalsey '' }} -> true", "description": "

    Returns true if the given value is falsey. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

    \n", "requiresBlock": false @@ -1023,7 +920,6 @@ "val", "options" ], - "numArgs": 2, "example": "{{isTruthy '12' }} -> true", "description": "

    Returns true if the given value is truthy. Uses the [falsey][] library for comparisons. Please see that library for more information or to report bugs with this helper.

    \n", "requiresBlock": false @@ -1033,7 +929,6 @@ "number", "options" ], - "numArgs": 2, "example": "{{#ifEven 2}} even {{else}} odd {{/ifEven}} -> ' even '", "description": "

    Return true if the given value is an even number.

    \n", "requiresBlock": true @@ -1044,7 +939,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#ifNth 2 10}}remainder{{else}}no remainder{{/ifNth}} -> remainder", "description": "

    Conditionally renders a block if the remainder is zero when b operand is divided by a. If an inverse block is specified it will be rendered when the remainder is not zero.

    \n", "requiresBlock": true @@ -1054,7 +948,6 @@ "value", "options" ], - "numArgs": 2, "example": "{{#ifOdd 3}}odd{{else}}even{{/ifOdd}} -> odd", "description": "

    Block helper that renders a block if value is an odd number. If an inverse block is specified it will be rendered when falsy.

    \n", "requiresBlock": true @@ -1065,7 +958,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#is 3 3}} is {{else}} is not {{/is}} -> ' is '", "description": "

    Block helper that renders a block if a is equal to b. If an inverse block is specified it will be rendered when falsy. Similar to eq but does not do strict equality.

    \n", "requiresBlock": true @@ -1076,7 +968,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#isnt 3 3}} isnt {{else}} is {{/isnt}} -> ' is '", "description": "

    Block helper that renders a block if a is not equal to b. If an inverse block is specified it will be rendered when falsy. Similar to unlessEq but does not use strict equality for comparisons.

    \n", "requiresBlock": true @@ -1086,7 +977,6 @@ "context", "options" ], - "numArgs": 2, "example": "{{#lt 2 3}} less than {{else}} more than or equal {{/lt}} -> ' less than '", "description": "

    Block helper that renders a block if a is less than b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

    \n", "requiresBlock": true @@ -1097,7 +987,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#lte 2 3}} less than or equal {{else}} more than {{/lte}} -> ' less than or equal '", "description": "

    Block helper that renders a block if a is less than or equal to b. If an inverse block is specified it will be rendered when falsy. You may optionally use the compare='' hash argument for the second value.

    \n", "requiresBlock": true @@ -1108,7 +997,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#neither null null}}both falsey{{else}}both not falsey{{/neither}} -> both falsey", "description": "

    Block helper that renders a block if neither of the given values are truthy. If an inverse block is specified it will be rendered when falsy.

    \n", "requiresBlock": true @@ -1118,7 +1006,6 @@ "val", "options" ], - "numArgs": 2, "example": "{{#not undefined }}falsey{{else}}not falsey{{/not}} -> falsey", "description": "

    Returns true if val is falsey. Works as a block or inline helper.

    \n", "requiresBlock": true @@ -1128,7 +1015,6 @@ "arguments", "options" ], - "numArgs": 2, "example": "{{#or 1 2 undefined }} at least one truthy {{else}} all falsey {{/or}} -> ' at least one truthy '", "description": "

    Block helper that renders a block if any of the given values is truthy. If an inverse block is specified it will be rendered when falsy.

    \n", "requiresBlock": true @@ -1139,7 +1025,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#unlessEq 2 1 }} not equal {{else}} equal {{/unlessEq}} -> ' not equal '", "description": "

    Block helper that always renders the inverse block unless a is equal to b.

    \n", "requiresBlock": true @@ -1150,7 +1035,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#unlessGt 20 1 }} not greater than {{else}} greater than {{/unlessGt}} -> ' greater than '", "description": "

    Block helper that always renders the inverse block unless a is greater than b.

    \n", "requiresBlock": true @@ -1161,7 +1045,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#unlessLt 20 1 }}greater than or equal{{else}}less than{{/unlessLt}} -> greater than or equal", "description": "

    Block helper that always renders the inverse block unless a is less than b.

    \n", "requiresBlock": true @@ -1172,7 +1055,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#unlessGteq 20 1 }} less than {{else}}greater than or equal to{{/unlessGteq}} -> greater than or equal to", "description": "

    Block helper that always renders the inverse block unless a is greater than or equal to b.

    \n", "requiresBlock": true @@ -1183,7 +1065,6 @@ "b", "options" ], - "numArgs": 3, "example": "{{#unlessLteq 20 1 }} greater than {{else}} less than or equal to {{/unlessLteq}} -> ' greater than '", "description": "

    Block helper that always renders the inverse block unless a is less than or equal to b.

    \n", "requiresBlock": true @@ -1194,7 +1075,6 @@ "args": [ "objects" ], - "numArgs": 1, "description": "

    Extend the context with the properties of other objects. A shallow merge is performed to avoid mutating the context.

    \n", "requiresBlock": false }, @@ -1203,7 +1083,6 @@ "context", "options" ], - "numArgs": 2, "description": "

    Block helper that iterates over the properties of an object, exposing each key and value on the context.

    \n", "requiresBlock": true }, @@ -1212,7 +1091,6 @@ "obj", "options" ], - "numArgs": 2, "description": "

    Block helper that iterates over the own properties of an object, exposing each key and value on the context.

    \n", "requiresBlock": true }, @@ -1220,7 +1098,6 @@ "args": [ "prop" ], - "numArgs": 1, "description": "

    Take arguments and, if they are string or number, convert them to a dot-delineated object property path.

    \n", "requiresBlock": false }, @@ -1230,7 +1107,6 @@ "context", "options" ], - "numArgs": 3, "description": "

    Use property paths (a.b.c) to get a value or nested value from the context. Works as a regular helper or block helper.

    \n", "requiresBlock": true }, @@ -1239,7 +1115,6 @@ "prop", "context" ], - "numArgs": 2, "description": "

    Use property paths (a.b.c) to get an object from the context. Differs from the get helper in that this helper will return the actual object, including the given property key. Also, this helper does not work as a block helper.

    \n", "requiresBlock": false }, @@ -1248,7 +1123,6 @@ "key", "context" ], - "numArgs": 2, "description": "

    Return true if key is an own, enumerable property of the given context object.

    \n", "requiresBlock": false }, @@ -1256,7 +1130,6 @@ "args": [ "value" ], - "numArgs": 1, "description": "

    Return true if value is an object.

    \n", "requiresBlock": false }, @@ -1264,7 +1137,6 @@ "args": [ "string" ], - "numArgs": 1, "description": "

    Parses the given string using JSON.parse.

    \n", "requiresBlock": true }, @@ -1272,7 +1144,6 @@ "args": [ "obj" ], - "numArgs": 1, "description": "

    Stringify an object using JSON.stringify.

    \n", "requiresBlock": false }, @@ -1281,7 +1152,6 @@ "object", "objects" ], - "numArgs": 2, "description": "

    Deeply merge the properties of the given objects with the context object.

    \n", "requiresBlock": false }, @@ -1289,7 +1159,6 @@ "args": [ "string" ], - "numArgs": 1, "description": "

    Parses the given string using JSON.parse.

    \n", "requiresBlock": true }, @@ -1299,7 +1168,6 @@ "context", "options" ], - "numArgs": 3, "description": "

    Pick properties from the context object.

    \n", "requiresBlock": true }, @@ -1307,7 +1175,6 @@ "args": [ "obj" ], - "numArgs": 1, "description": "

    Stringify an object using JSON.stringify.

    \n", "requiresBlock": false } @@ -1317,7 +1184,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{toRegex 'foo'}} -> /foo/", "description": "

    Convert the given string to a regular expression.

    \n", "requiresBlock": false @@ -1326,7 +1192,6 @@ "args": [ "str" ], - "numArgs": 1, "example": "{{test 'foobar' (toRegex 'foo')}} -> true", "description": "

    Returns true if the given str matches the given regex. A regex can be passed on the context, or using the toRegex helper as a subexpression.

    \n", "requiresBlock": false @@ -1335,7 +1200,6 @@ "uuid": { "uuid": { "args": [], - "numArgs": 0, "example": "{{ uuid }} -> f34ebc66-93bd-4f7c-b79b-92b5569138bc", "description": "

    Generates a UUID, using the V4 method (identical to the browser crypto.randomUUID function).

    \n", "requiresBlock": false @@ -1348,7 +1212,6 @@ "format", "options" ], - "numArgs": 3, "example": "{{date now \"DD-MM-YYYY\" \"America/New_York\" }} -> 21-01-2021", "description": "

    Format a date using moment.js date formatting - the timezone is optional and uses the tz database.

    \n" }, @@ -1357,7 +1220,6 @@ "time", "durationType" ], - "numArgs": 2, "example": "{{duration 8 \"seconds\"}} -> a few seconds", "description": "

    Produce a humanized duration left/until given an amount of time and the type of time measurement.

    \n" } From 20c956e0d6ec2c66e50d96443252dbec94b69917 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 13:18:39 +0100 Subject: [PATCH 46/91] Validate blocks --- .../src/components/common/CodeEditor/validator/hbs.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts index c2b3b464da..cb55dfa7eb 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts @@ -45,7 +45,10 @@ export function validateHbsTemplate( ) { const ignoreMissing = options?.ignoreMissing || false nodes.forEach(node => { - if (isMustacheStatement(node) && isPathExpression(node.path)) { + if ( + (isMustacheStatement(node) || isBlockStatement(node)) && + isPathExpression(node.path) + ) { const helperName = node.path.original const from = From 6c3382f2ae17fef71cce2a1f802eed98c774c87c Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 13:20:22 +0100 Subject: [PATCH 47/91] Fix body count --- .../components/common/CodeEditor/validator/hbs.ts | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts index cb55dfa7eb..284164a914 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts @@ -80,18 +80,22 @@ export function validateHbsTemplate( return } - const providedParams = node.params + let providedParamsCount = node.params.length + if (isBlockStatement(node)) { + // Block body counts as a parameter + providedParamsCount++ + } - if (providedParams.length !== expectedArguments.length) { + if (providedParamsCount !== expectedArguments.length) { diagnostics.push({ from, to, severity: "error", message: `Helper "${helperName}" expects ${ expectedArguments.length - } parameters (${expectedArguments.join(", ")}), but got ${ - providedParams.length - }.`, + } parameters (${expectedArguments.join( + ", " + )}), but got ${providedParamsCount}.`, }) } } From 56e143625d5b2d30d23d227219e5d861a0509a27 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 13:22:53 +0100 Subject: [PATCH 48/91] Body checks --- .../src/components/common/CodeEditor/validator/hbs.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts index 284164a914..b954bb1e8f 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts @@ -78,6 +78,14 @@ export function validateHbsTemplate( message: `Helper "${helperName}" requires a body:\n{{#${helperName} ...}} [body] {{/${helperName}}}`, }) return + } else if (!requiresBlock && isBlockStatement(node)) { + diagnostics.push({ + from, + to, + severity: "error", + message: `Helper "${helperName}" should not contain a body.`, + }) + return } let providedParamsCount = node.params.length From 33b8751d7817b0f385cd0e9f081aad8177cd7a39 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Thu, 27 Feb 2025 12:36:42 +0000 Subject: [PATCH 49/91] Fixing users meta info for groups. --- .../app/[application]/_components/BuilderSidePanel.svelte | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 16af731e02..4a7af9342e 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -706,7 +706,7 @@ >
    -
    +
    {group.name}
    @@ -935,6 +935,7 @@ color: var(--spectrum-global-color-gray-600); font-size: 12px; white-space: nowrap; + text-align: end; } .auth-entity-access { @@ -970,7 +971,7 @@ width: 100%; } - .auth-entity .user-email { + .auth-entity .user-email, .group-name { flex: 1 1 0; min-width: 0; overflow: hidden; @@ -1073,7 +1074,7 @@ .user-groups { display: flex; flex-direction: row; - justify-content: flex-start; /* or space-between */ + justify-content: flex-start; align-items: center; gap: var(--spacing-m); width: 100%; From 78e558c4aa4baa958062cff08d64038195457529 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 14:16:52 +0100 Subject: [PATCH 50/91] Handle conditional arguments --- .../common/CodeEditor/validator/hbs.ts | 33 +++++++++- .../CodeEditor/validator/tests/hbs.spec.ts | 64 +++++++++++++++++++ 2 files changed, 96 insertions(+), 1 deletion(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts index b954bb1e8f..357cb04a86 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts @@ -94,7 +94,15 @@ export function validateHbsTemplate( providedParamsCount++ } - if (providedParamsCount !== expectedArguments.length) { + const optionalArgMatcher = new RegExp(/^\[(.+)\]$/) + const optionalArgs = expectedArguments.filter(a => + optionalArgMatcher.test(a) + ) + + if ( + !optionalArgs.length && + providedParamsCount !== expectedArguments.length + ) { diagnostics.push({ from, to, @@ -105,6 +113,29 @@ export function validateHbsTemplate( ", " )}), but got ${providedParamsCount}.`, }) + } else if (optionalArgs.length) { + const maxArgs = expectedArguments.length + const minArgs = maxArgs - optionalArgs.length + const parameters = expectedArguments + .map(a => { + const test = optionalArgMatcher.exec(a) + if (!test?.[1]) { + return a + } + return `${test[1]} (optional)` + }) + .join(", ") + if ( + minArgs > providedParamsCount || + maxArgs < providedParamsCount + ) { + diagnostics.push({ + from, + to, + severity: "error", + message: `Helper "${helperName}" expects between ${minArgs} to ${expectedArguments.length} parameters (${parameters}), but got ${providedParamsCount}.`, + }) + } } } diff --git a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts index 9484c7a4a5..95ec2e540e 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts @@ -138,5 +138,69 @@ describe("hbs validator", () => { }, ]) }) + + describe("optional parameters", () => { + it("supports empty parameters", () => { + const validators: CodeValidator = { + helperFunction: { + arguments: ["a", "b", "[c]"], + }, + } + const text = "{{ helperFunction 1 99 }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toHaveLength(0) + }) + + it("supports valid parameters", () => { + const validators: CodeValidator = { + helperFunction: { + arguments: ["a", "b", "[c]"], + }, + } + const text = "{{ helperFunction 1 99 'a' }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toHaveLength(0) + }) + + it("returns a valid message on missing parameters", () => { + const validators: CodeValidator = { + helperFunction: { + arguments: ["a", "b", "[c]"], + }, + } + const text = "{{ helperFunction 1 }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "helperFunction" expects between 2 to 3 parameters (a, b, c (optional)), but got 1.`, + severity: "error", + to: 22, + }, + ]) + }) + + it("returns a valid message on too many parameters", () => { + const validators: CodeValidator = { + helperFunction: { + arguments: ["a", "b", "[c]"], + }, + } + const text = "{{ helperFunction 1 2 3 4 }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "helperFunction" expects between 2 to 3 parameters (a, b, c (optional)), but got 4.`, + severity: "error", + to: 28, + }, + ]) + }) + }) }) }) From 7905df5a4a866857445cf8f8c04cbfd8de93a203 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 14:18:38 +0100 Subject: [PATCH 51/91] Date options as optional --- packages/string-templates/scripts/gen-collection-info.ts | 2 +- packages/string-templates/src/manifest.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/string-templates/scripts/gen-collection-info.ts b/packages/string-templates/scripts/gen-collection-info.ts index ffe9f68add..f34d54b2e1 100644 --- a/packages/string-templates/scripts/gen-collection-info.ts +++ b/packages/string-templates/scripts/gen-collection-info.ts @@ -33,7 +33,7 @@ const outputJSON: Manifest = {} const ADDED_HELPERS = { date: { date: { - args: ["datetime", "format", "options"], + args: ["datetime", "format", "[options]"], example: '{{date now "DD-MM-YYYY" "America/New_York" }} -> 21-01-2021', description: "Format a date using moment.js date formatting - the timezone is optional and uses the tz database.", diff --git a/packages/string-templates/src/manifest.json b/packages/string-templates/src/manifest.json index e47af7d69a..931700bf1d 100644 --- a/packages/string-templates/src/manifest.json +++ b/packages/string-templates/src/manifest.json @@ -1210,7 +1210,7 @@ "args": [ "datetime", "format", - "options" + "[options]" ], "example": "{{date now \"DD-MM-YYYY\" \"America/New_York\" }} -> 21-01-2021", "description": "

    Format a date using moment.js date formatting - the timezone is optional and uses the tz database.

    \n" From e8b6a3c90ee45b3d20bf66e09836df38b32b025c Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 14:39:13 +0100 Subject: [PATCH 52/91] Validate bodies --- .../CodeEditor/validator/tests/hbs.spec.ts | 136 +++++++++++++----- 1 file changed, 103 insertions(+), 33 deletions(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts index 95ec2e540e..4d303e6e27 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts @@ -98,45 +98,115 @@ describe("hbs validator", () => { }) describe("expressions with parameters", () => { - const validators: CodeValidator = { - helperFunction: { - arguments: ["a", "b", "c"], - }, - } + describe("basic expression", () => { + const validators: CodeValidator = { + helperFunction: { + arguments: ["a", "b", "c"], + }, + } - it("validate valid params", () => { - const text = "{{ helperFunction 1 99 'a' }}" + it("validate valid params", () => { + const text = "{{ helperFunction 1 99 'a' }}" - const result = validateHbsTemplate(text, validators) - expect(result).toHaveLength(0) + const result = validateHbsTemplate(text, validators) + expect(result).toHaveLength(0) + }) + + it("throws on too few params", () => { + const text = "{{ helperFunction 100 }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "helperFunction" expects 3 parameters (a, b, c), but got 1.`, + severity: "error", + to: 24, + }, + ]) + }) + + it("throws on too many params", () => { + const text = "{{ helperFunction 1 99 'a' 100 }}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "helperFunction" expects 3 parameters (a, b, c), but got 4.`, + severity: "error", + to: 34, + }, + ]) + }) }) - it("throws on too few params", () => { - const text = "{{ helperFunction 100 }}" - - const result = validateHbsTemplate(text, validators) - expect(result).toEqual([ - { - from: 0, - message: `Helper "helperFunction" expects 3 parameters (a, b, c), but got 1.`, - severity: "error", - to: 24, + describe("body expressions", () => { + const validators: CodeValidator = { + bodyFunction: { + arguments: ["a", "b", "c"], + requiresBlock: true, }, - ]) - }) - - it("throws on too many params", () => { - const text = "{{ helperFunction 1 99 'a' 100 }}" - - const result = validateHbsTemplate(text, validators) - expect(result).toEqual([ - { - from: 0, - message: `Helper "helperFunction" expects 3 parameters (a, b, c), but got 4.`, - severity: "error", - to: 34, + nonBodyFunction: { + arguments: ["a", "b"], }, - ]) + } + + it("validate valid params", () => { + const text = "{{#bodyFunction 1 99 }}body{{/bodyFunction}}" + + const result = validateHbsTemplate(text, validators) + expect(result).toHaveLength(0) + }) + + it("validate empty bodies", () => { + const text = "{{#bodyFunction 1 99 }}{{/bodyFunction}}" + + const result = validateHbsTemplate(text, validators) + expect(result).toHaveLength(0) + }) + + it("validate too little parameters", () => { + const text = "{{#bodyFunction 1 }}{{/bodyFunction}}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "bodyFunction" expects 3 parameters (a, b, c), but got 2.`, + severity: "error", + to: 37, + }, + ]) + }) + + it("validate too many parameters", () => { + const text = "{{#bodyFunction 1 99 'a' 0 }}{{/bodyFunction}}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "bodyFunction" expects 3 parameters (a, b, c), but got 5.`, + severity: "error", + to: 46, + }, + ]) + }) + + it("validate non-supported body usages", () => { + const text = "{{#nonBodyFunction 1 99}}{{/nonBodyFunction}}" + + const result = validateHbsTemplate(text, validators) + expect(result).toEqual([ + { + from: 0, + message: `Helper "nonBodyFunction" should not contain a body.`, + severity: "error", + to: 45, + }, + ]) + }) }) describe("optional parameters", () => { From af74d3df620e9232f2370057cbe5371dc96956c6 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 14:41:37 +0100 Subject: [PATCH 53/91] Add wrong hbs tests --- .../CodeEditor/validator/tests/hbs.spec.ts | 32 +++++++++++++------ 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts index 4d303e6e27..5d2cfa06c2 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/tests/hbs.spec.ts @@ -2,7 +2,7 @@ import { validateHbsTemplate } from "../hbs" import { CodeValidator } from "@/types" describe("hbs validator", () => { - it("validate empty strings", () => { + it("validates empty strings", () => { const text = "" const validators = {} @@ -10,7 +10,7 @@ describe("hbs validator", () => { expect(result).toHaveLength(0) }) - it("validate strings without hbs expressions", () => { + it("validates strings without hbs expressions", () => { const text = "first line\nand another one" const validators = {} @@ -23,7 +23,7 @@ describe("hbs validator", () => { fieldName: {}, } - it("validate valid expressions", () => { + it("validates valid expressions", () => { const text = "{{ fieldName }}" const result = validateHbsTemplate(text, validators) @@ -105,7 +105,7 @@ describe("hbs validator", () => { }, } - it("validate valid params", () => { + it("validates valid params", () => { const text = "{{ helperFunction 1 99 'a' }}" const result = validateHbsTemplate(text, validators) @@ -152,21 +152,21 @@ describe("hbs validator", () => { }, } - it("validate valid params", () => { + it("validates valid params", () => { const text = "{{#bodyFunction 1 99 }}body{{/bodyFunction}}" const result = validateHbsTemplate(text, validators) expect(result).toHaveLength(0) }) - it("validate empty bodies", () => { + it("validates empty bodies", () => { const text = "{{#bodyFunction 1 99 }}{{/bodyFunction}}" const result = validateHbsTemplate(text, validators) expect(result).toHaveLength(0) }) - it("validate too little parameters", () => { + it("validates too little parameters", () => { const text = "{{#bodyFunction 1 }}{{/bodyFunction}}" const result = validateHbsTemplate(text, validators) @@ -180,7 +180,7 @@ describe("hbs validator", () => { ]) }) - it("validate too many parameters", () => { + it("validates too many parameters", () => { const text = "{{#bodyFunction 1 99 'a' 0 }}{{/bodyFunction}}" const result = validateHbsTemplate(text, validators) @@ -194,7 +194,7 @@ describe("hbs validator", () => { ]) }) - it("validate non-supported body usages", () => { + it("validates non-supported body usages", () => { const text = "{{#nonBodyFunction 1 99}}{{/nonBodyFunction}}" const result = validateHbsTemplate(text, validators) @@ -273,4 +273,18 @@ describe("hbs validator", () => { }) }) }) + + it("validates wrong hbs code", () => { + const text = "{{#fieldName}}{{/wrong}}" + + const result = validateHbsTemplate(text, {}) + expect(result).toEqual([ + { + from: 0, + message: `The handlebars code is not valid:\nfieldName doesn't match wrong - 1:3`, + severity: "error", + to: text.length, + }, + ]) + }) }) From d7f3ad8a84787c821d0e298d92d0688dcc5711c0 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Thu, 27 Feb 2025 15:35:09 +0000 Subject: [PATCH 54/91] Fix users.spec.ts. --- .../src/api/routes/public/tests/users.spec.ts | 60 +++++++------------ 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/packages/server/src/api/routes/public/tests/users.spec.ts b/packages/server/src/api/routes/public/tests/users.spec.ts index fbfb7bbd61..13630e443d 100644 --- a/packages/server/src/api/routes/public/tests/users.spec.ts +++ b/packages/server/src/api/routes/public/tests/users.spec.ts @@ -41,14 +41,6 @@ beforeEach(async () => { .persist() }) -function base() { - return { - tenantId: config.getTenantId(), - firstName: "Test", - lastName: "Test", - } -} - describe("check user endpoints", () => { it("should not allow a user to update their own roles", async () => { await config.withUser(globalUser, () => @@ -68,8 +60,8 @@ describe("check user endpoints", () => { }) }) -describe("no user role update in free", () => { - it.only("should not allow 'roles' to be updated", async () => { +describe("role updating on free tier", () => { + it("should not allow 'roles' to be updated", async () => { const newUser = await config.api.public.user.create({ email: generator.email({ domain: "example.com" }), roles: { app_a: "BASIC" }, @@ -78,60 +70,52 @@ describe("no user role update in free", () => { }) it("should not allow 'admin' to be updated", async () => { - const res = await makeRequest("post", "/users", { - ...base(), + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, admin: { global: true }, }) - expect(res.status).toBe(200) - expect(res.body.data.admin).toBeUndefined() - expect(res.body.message).toBeDefined() + expect(newUser.admin).toBeUndefined() }) it("should not allow 'builder' to be updated", async () => { - const res = await makeRequest("post", "/users", { - ...base(), + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, builder: { global: true }, }) - expect(res.status).toBe(200) - expect(res.body.data.builder).toBeUndefined() - expect(res.body.message).toBeDefined() + expect(newUser.builder).toBeUndefined() }) }) -describe("no user role update in business", () => { +describe("role updating on business tier", () => { beforeAll(() => { mocks.licenses.useExpandedPublicApi() }) it("should allow 'roles' to be updated", async () => { - const res = await makeRequest("post", "/users", { - ...base(), + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), roles: { app_a: "BASIC" }, }) - expect(res.status).toBe(200) - expect(res.body.data.roles["app_a"]).toBe("BASIC") - expect(res.body.message).toBeUndefined() + expect(newUser.roles["app_a"]).toBe("BASIC") }) it("should allow 'admin' to be updated", async () => { - mocks.licenses.useExpandedPublicApi() - const res = await makeRequest("post", "/users", { - ...base(), + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, admin: { global: true }, }) - expect(res.status).toBe(200) - expect(res.body.data.admin.global).toBe(true) - expect(res.body.message).toBeUndefined() + expect(newUser.admin?.global).toBe(true) }) it("should allow 'builder' to be updated", async () => { - mocks.licenses.useExpandedPublicApi() - const res = await makeRequest("post", "/users", { - ...base(), + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, builder: { global: true }, }) - expect(res.status).toBe(200) - expect(res.body.data.builder.global).toBe(true) - expect(res.body.message).toBeUndefined() + expect(newUser.builder?.global).toBe(true) }) }) From 6499f7a2706269075e9a4eda6ad32f8c8ed9f55a Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 17:11:47 +0100 Subject: [PATCH 55/91] Support empty {{ date }} --- packages/string-templates/scripts/gen-collection-info.ts | 2 +- packages/string-templates/src/helpers/date.ts | 6 ++++-- packages/string-templates/src/manifest.json | 4 ++-- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/string-templates/scripts/gen-collection-info.ts b/packages/string-templates/scripts/gen-collection-info.ts index f34d54b2e1..d231908a05 100644 --- a/packages/string-templates/scripts/gen-collection-info.ts +++ b/packages/string-templates/scripts/gen-collection-info.ts @@ -33,7 +33,7 @@ const outputJSON: Manifest = {} const ADDED_HELPERS = { date: { date: { - args: ["datetime", "format", "[options]"], + args: ["[datetime]", "[format]", "[options]"], example: '{{date now "DD-MM-YYYY" "America/New_York" }} -> 21-01-2021', description: "Format a date using moment.js date formatting - the timezone is optional and uses the tz database.", diff --git a/packages/string-templates/src/helpers/date.ts b/packages/string-templates/src/helpers/date.ts index 589cb3d978..8b52fb61e2 100644 --- a/packages/string-templates/src/helpers/date.ts +++ b/packages/string-templates/src/helpers/date.ts @@ -71,7 +71,7 @@ function getContext(thisArg: any, locals: any, options: any) { function initialConfig(str: any, pattern: any, options?: any) { if (isOptions(pattern)) { options = pattern - pattern = null + pattern = DEFAULT_FORMAT } if (isOptions(str)) { @@ -93,13 +93,15 @@ function setLocale(this: any, str: any, pattern: any, options?: any) { dayjs.locale(opts.lang || opts.language) } +const DEFAULT_FORMAT = "MMMM DD, YYYY" + export const date = (str: any, pattern: any, options: any) => { const config = initialConfig(str, pattern, options) // if no args are passed, return a formatted date if (config.str == null && config.pattern == null) { dayjs.locale("en") - return dayjs().format("MMMM DD, YYYY") + return dayjs().format(DEFAULT_FORMAT) } setLocale(config.str, config.pattern, config.options) diff --git a/packages/string-templates/src/manifest.json b/packages/string-templates/src/manifest.json index 931700bf1d..e399dbff94 100644 --- a/packages/string-templates/src/manifest.json +++ b/packages/string-templates/src/manifest.json @@ -1208,8 +1208,8 @@ "date": { "date": { "args": [ - "datetime", - "format", + "[datetime]", + "[format]", "[options]" ], "example": "{{date now \"DD-MM-YYYY\" \"America/New_York\" }} -> 21-01-2021", From aa2537c4b2af903e0193c17e3551802622b2ed40 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 17:15:58 +0100 Subject: [PATCH 56/91] Clean --- .../common/CodeEditor/validator/hbs.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts index 357cb04a86..1fca3967fc 100644 --- a/packages/builder/src/components/common/CodeEditor/validator/hbs.ts +++ b/packages/builder/src/components/common/CodeEditor/validator/hbs.ts @@ -116,19 +116,19 @@ export function validateHbsTemplate( } else if (optionalArgs.length) { const maxArgs = expectedArguments.length const minArgs = maxArgs - optionalArgs.length - const parameters = expectedArguments - .map(a => { - const test = optionalArgMatcher.exec(a) - if (!test?.[1]) { - return a - } - return `${test[1]} (optional)` - }) - .join(", ") if ( minArgs > providedParamsCount || maxArgs < providedParamsCount ) { + const parameters = expectedArguments + .map(a => { + const test = optionalArgMatcher.exec(a) + if (!test?.[1]) { + return a + } + return `${test[1]} (optional)` + }) + .join(", ") diagnostics.push({ from, to, From cca955da06530277b4ecc55a5e390a3dfa0ae2ab Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Thu, 27 Feb 2025 17:27:59 +0100 Subject: [PATCH 57/91] Fixing whitespaces on formulas --- .../src/components/backend/DataTable/formula.js | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/builder/src/components/backend/DataTable/formula.js b/packages/builder/src/components/backend/DataTable/formula.js index 9ec75b52c0..c0fdb96a07 100644 --- a/packages/builder/src/components/backend/DataTable/formula.js +++ b/packages/builder/src/components/backend/DataTable/formula.js @@ -26,7 +26,7 @@ export function getBindings({ if (!table) { return bindings } - for (let [column, schema] of Object.entries(table.schema)) { + for (const [column, schema] of Object.entries(table.schema)) { const isRelationship = schema.type === FieldType.LINK // skip relationships after a certain depth and types which // can't bind to @@ -62,6 +62,12 @@ export function getBindings({ const label = path == null ? column : `${path}.0.${column}` const binding = path == null ? `[${column}]` : `[${path}].0.[${column}]` + + let readableBinding = label + if (readableBinding.includes(" ")) { + readableBinding = `[${readableBinding}]` + } + // only supply a description for relationship paths const description = path == null @@ -75,7 +81,7 @@ export function getBindings({ description, // don't include path, it messes things up, relationship path // will be replaced by the main array binding - readableBinding: label, + readableBinding, runtimeBinding: binding, display: { name: label, From 55783e17f179993cc8fd4a37a362ef0ba387b959 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Thu, 27 Feb 2025 17:11:50 +0000 Subject: [PATCH 58/91] Fix compare.spec.ts. --- packages/server/specs/resources/error.ts | 21 ++ .../api/routes/public/tests/compare.spec.ts | 308 +++++++++--------- .../src/api/routes/public/tests/users.spec.ts | 230 +++++++------ .../src/api/routes/public/tests/utils.ts | 44 +++ .../server/src/tests/utilities/api/base.ts | 20 +- .../src/tests/utilities/api/public/user.ts | 8 +- 6 files changed, 362 insertions(+), 269 deletions(-) create mode 100644 packages/server/specs/resources/error.ts diff --git a/packages/server/specs/resources/error.ts b/packages/server/specs/resources/error.ts new file mode 100644 index 0000000000..0d42963b73 --- /dev/null +++ b/packages/server/specs/resources/error.ts @@ -0,0 +1,21 @@ +import { object } from "./utils" +import Resource from "./utils/Resource" + +const errorSchema = object({ + status: { + type: "number", + description: "The HTTP status code of the error.", + }, + message: { + type: "string", + description: "A descriptive message about the error.", + }, +}) + +export default new Resource() + .setExamples({ + error: {}, + }) + .setSchemas({ + error: errorSchema, + }) diff --git a/packages/server/src/api/routes/public/tests/compare.spec.ts b/packages/server/src/api/routes/public/tests/compare.spec.ts index ccf248f360..b4f5f20e2c 100644 --- a/packages/server/src/api/routes/public/tests/compare.spec.ts +++ b/packages/server/src/api/routes/public/tests/compare.spec.ts @@ -2,184 +2,174 @@ import jestOpenAPI from "jest-openapi" import { run as generateSchema } from "../../../../../specs/generate" import * as setup from "../../tests/utilities" import { generateMakeRequest } from "./utils" -import { Table, App, Row, User } from "@budibase/types" +import { Table, App, Row } from "@budibase/types" +import nock from "nock" +import environment from "../../../../environment" const yamlPath = generateSchema() jestOpenAPI(yamlPath!) -let config = setup.getConfig() -let apiKey: string, table: Table, app: App, makeRequest: any +describe("compare", () => { + let config = setup.getConfig() + let apiKey: string, table: Table, app: App, makeRequest: any -beforeAll(async () => { - app = await config.init() - table = await config.upsertTable() - apiKey = await config.generateApiKey() - makeRequest = generateMakeRequest(apiKey) -}) - -afterAll(setup.afterAll) - -describe("check the applications endpoints", () => { - it("should allow retrieving applications through search", async () => { - const res = await makeRequest("post", "/applications/search") - expect(res).toSatisfyApiSpec() - }) - - it("should allow creating an application", async () => { - const res = await makeRequest( - "post", - "/applications", - { - name: "new App", - }, - null - ) - expect(res).toSatisfyApiSpec() - }) - - it("should allow updating an application", async () => { - const app = config.getApp() - const appId = config.getAppId() - const res = await makeRequest( - "put", - `/applications/${appId}`, - { - ...app, - name: "updated app name", - }, - appId - ) - expect(res).toSatisfyApiSpec() - }) - - it("should allow retrieving an application", async () => { - const res = await makeRequest("get", `/applications/${config.getAppId()}`) - expect(res).toSatisfyApiSpec() - }) - - it("should allow deleting an application", async () => { - const res = await makeRequest( - "delete", - `/applications/${config.getAppId()}` - ) - expect(res).toSatisfyApiSpec() - }) -}) - -describe("check the tables endpoints", () => { - it("should allow retrieving tables through search", async () => { - await config.createApp("new app 1") + beforeAll(async () => { + app = await config.init() table = await config.upsertTable() - const res = await makeRequest("post", "/tables/search") - expect(res).toSatisfyApiSpec() + apiKey = await config.generateApiKey() + makeRequest = generateMakeRequest(apiKey) }) - it("should allow creating a table", async () => { - const res = await makeRequest("post", "/tables", { - name: "table name", - primaryDisplay: "column1", - schema: { - column1: { - type: "string", - constraints: {}, + afterAll(setup.afterAll) + + beforeEach(() => { + nock.cleanAll() + }) + + describe("check the applications endpoints", () => { + it("should allow retrieving applications through search", async () => { + const res = await makeRequest("post", "/applications/search") + expect(res).toSatisfyApiSpec() + }) + + it("should allow creating an application", async () => { + const res = await makeRequest( + "post", + "/applications", + { + name: "new App", }, - }, + null + ) + expect(res).toSatisfyApiSpec() }) - expect(res).toSatisfyApiSpec() - }) - it("should allow updating a table", async () => { - const updated = { ...table, _rev: undefined, name: "new name" } - const res = await makeRequest("put", `/tables/${table._id}`, updated) - expect(res).toSatisfyApiSpec() - }) - - it("should allow retrieving a table", async () => { - const res = await makeRequest("get", `/tables/${table._id}`) - expect(res).toSatisfyApiSpec() - }) - - it("should allow deleting a table", async () => { - const res = await makeRequest("delete", `/tables/${table._id}`) - expect(res).toSatisfyApiSpec() - }) -}) - -describe("check the rows endpoints", () => { - let row: Row - it("should allow retrieving rows through search", async () => { - table = await config.upsertTable() - const res = await makeRequest("post", `/tables/${table._id}/rows/search`, { - query: {}, + it("should allow updating an application", async () => { + const app = config.getApp() + const appId = config.getAppId() + const res = await makeRequest( + "put", + `/applications/${appId}`, + { + ...app, + name: "updated app name", + }, + appId + ) + expect(res).toSatisfyApiSpec() }) - expect(res).toSatisfyApiSpec() - }) - it("should allow creating a row", async () => { - const res = await makeRequest("post", `/tables/${table._id}/rows`, { - name: "test row", + it("should allow retrieving an application", async () => { + const res = await makeRequest("get", `/applications/${config.getAppId()}`) + expect(res).toSatisfyApiSpec() + }) + + it("should allow deleting an application", async () => { + nock(environment.WORKER_URL!) + .delete(`/api/global/roles/${config.getProdAppId()}`) + .reply(200, {}) + + const res = await makeRequest( + "delete", + `/applications/${config.getAppId()}` + ) + expect(res).toSatisfyApiSpec() }) - expect(res).toSatisfyApiSpec() - row = res.body.data }) - it("should allow updating a row", async () => { - const res = await makeRequest( - "put", - `/tables/${table._id}/rows/${row._id}`, - { - name: "test row updated", - } - ) - expect(res).toSatisfyApiSpec() + describe("check the tables endpoints", () => { + it("should allow retrieving tables through search", async () => { + await config.createApp("new app 1") + table = await config.upsertTable() + const res = await makeRequest("post", "/tables/search") + expect(res).toSatisfyApiSpec() + }) + + it("should allow creating a table", async () => { + const res = await makeRequest("post", "/tables", { + name: "table name", + primaryDisplay: "column1", + schema: { + column1: { + type: "string", + constraints: {}, + }, + }, + }) + expect(res).toSatisfyApiSpec() + }) + + it("should allow updating a table", async () => { + const updated = { ...table, _rev: undefined, name: "new name" } + const res = await makeRequest("put", `/tables/${table._id}`, updated) + expect(res).toSatisfyApiSpec() + }) + + it("should allow retrieving a table", async () => { + const res = await makeRequest("get", `/tables/${table._id}`) + expect(res).toSatisfyApiSpec() + }) + + it("should allow deleting a table", async () => { + const res = await makeRequest("delete", `/tables/${table._id}`) + expect(res).toSatisfyApiSpec() + }) }) - it("should allow retrieving a row", async () => { - const res = await makeRequest("get", `/tables/${table._id}/rows/${row._id}`) - expect(res).toSatisfyApiSpec() + describe("check the rows endpoints", () => { + let row: Row + it("should allow retrieving rows through search", async () => { + table = await config.upsertTable() + const res = await makeRequest( + "post", + `/tables/${table._id}/rows/search`, + { + query: {}, + } + ) + expect(res).toSatisfyApiSpec() + }) + + it("should allow creating a row", async () => { + const res = await makeRequest("post", `/tables/${table._id}/rows`, { + name: "test row", + }) + expect(res).toSatisfyApiSpec() + row = res.body.data + }) + + it("should allow updating a row", async () => { + const res = await makeRequest( + "put", + `/tables/${table._id}/rows/${row._id}`, + { + name: "test row updated", + } + ) + expect(res).toSatisfyApiSpec() + }) + + it("should allow retrieving a row", async () => { + const res = await makeRequest( + "get", + `/tables/${table._id}/rows/${row._id}` + ) + expect(res).toSatisfyApiSpec() + }) + + it("should allow deleting a row", async () => { + const res = await makeRequest( + "delete", + `/tables/${table._id}/rows/${row._id}` + ) + expect(res).toSatisfyApiSpec() + }) }) - it("should allow deleting a row", async () => { - const res = await makeRequest( - "delete", - `/tables/${table._id}/rows/${row._id}` - ) - expect(res).toSatisfyApiSpec() - }) -}) - -describe("check the users endpoints", () => { - let user: User - it("should allow retrieving users through search", async () => { - user = await config.createUser() - const res = await makeRequest("post", "/users/search") - expect(res).toSatisfyApiSpec() - }) - - it("should allow creating a user", async () => { - const res = await makeRequest("post", "/users") - expect(res).toSatisfyApiSpec() - }) - - it("should allow updating a user", async () => { - const res = await makeRequest("put", `/users/${user._id}`) - expect(res).toSatisfyApiSpec() - }) - - it("should allow retrieving a user", async () => { - const res = await makeRequest("get", `/users/${user._id}`) - expect(res).toSatisfyApiSpec() - }) - - it("should allow deleting a user", async () => { - const res = await makeRequest("delete", `/users/${user._id}`) - expect(res).toSatisfyApiSpec() - }) -}) - -describe("check the queries endpoints", () => { - it("should allow retrieving queries through search", async () => { - const res = await makeRequest("post", "/queries/search") - expect(res).toSatisfyApiSpec() + describe("check the queries endpoints", () => { + it("should allow retrieving queries through search", async () => { + const res = await makeRequest("post", "/queries/search") + expect(res).toSatisfyApiSpec() + }) }) }) diff --git a/packages/server/src/api/routes/public/tests/users.spec.ts b/packages/server/src/api/routes/public/tests/users.spec.ts index 13630e443d..bb3e4b6fba 100644 --- a/packages/server/src/api/routes/public/tests/users.spec.ts +++ b/packages/server/src/api/routes/public/tests/users.spec.ts @@ -2,120 +2,142 @@ import * as setup from "../../tests/utilities" import { User } from "@budibase/types" import { generator, mocks } from "@budibase/backend-core/tests" import nock from "nock" -import environment from "../../../../environment" import TestConfiguration from "../../../../tests/utilities/TestConfiguration" +import { mockWorkerUserAPI } from "./utils" -const config = new TestConfiguration() -let globalUser: User -let users: Record = {} +describe("public users API", () => { + const config = new TestConfiguration() + let globalUser: User -beforeAll(async () => { - await config.init() -}) + beforeAll(async () => { + await config.init() + }) -afterAll(setup.afterAll) + afterAll(setup.afterAll) -beforeEach(async () => { - globalUser = await config.globalUser() - users[globalUser._id!] = globalUser + beforeEach(async () => { + globalUser = await config.globalUser() - nock.cleanAll() - nock(environment.WORKER_URL!) - .get(new RegExp(`/api/global/users/.*`)) - .reply(200, (uri, body) => { - const id = uri.split("/").pop() - return users[id!] + nock.cleanAll() + mockWorkerUserAPI(globalUser) + }) + + describe("read", () => { + it("should allow a user to read themselves", async () => { + const user = await config.api.user.find(globalUser._id!) + expect(user._id).toBe(globalUser._id) }) - .persist() - nock(environment.WORKER_URL!) - .post(`/api/global/users`) - .reply(200, (uri, body) => { - const newUser = body as User - if (!newUser._id) { - newUser._id = `us_${generator.guid()}` - } - users[newUser._id!] = newUser - return newUser - }) - .persist() -}) - -describe("check user endpoints", () => { - it("should not allow a user to update their own roles", async () => { - await config.withUser(globalUser, () => - config.api.public.user.update({ - ...globalUser, - roles: { app_1: "ADMIN" }, + it("should allow a user to read another user", async () => { + const otherUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, }) - ) - const updatedUser = await config.api.user.find(globalUser._id!) - expect(updatedUser.roles?.app_1).toBeUndefined() + const user = await config.withUser(globalUser, () => + config.api.public.user.find(otherUser._id!) + ) + expect(user._id).toBe(otherUser._id) + }) }) - it("should not allow a user to delete themselves", async () => { - await config.withUser(globalUser, () => - config.api.public.user.destroy(globalUser._id!, { status: 405 }) - ) - }) -}) - -describe("role updating on free tier", () => { - it("should not allow 'roles' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: { app_a: "BASIC" }, - }) - expect(newUser.roles["app_a"]).toBeUndefined() - }) - - it("should not allow 'admin' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: {}, - admin: { global: true }, - }) - expect(newUser.admin).toBeUndefined() - }) - - it("should not allow 'builder' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: {}, - builder: { global: true }, - }) - expect(newUser.builder).toBeUndefined() - }) -}) - -describe("role updating on business tier", () => { - beforeAll(() => { - mocks.licenses.useExpandedPublicApi() - }) - - it("should allow 'roles' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: { app_a: "BASIC" }, - }) - expect(newUser.roles["app_a"]).toBe("BASIC") - }) - - it("should allow 'admin' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: {}, - admin: { global: true }, - }) - expect(newUser.admin?.global).toBe(true) - }) - - it("should allow 'builder' to be updated", async () => { - const newUser = await config.api.public.user.create({ - email: generator.email({ domain: "example.com" }), - roles: {}, - builder: { global: true }, - }) - expect(newUser.builder?.global).toBe(true) + describe("create", () => { + it("can successfully create a new user", async () => { + const email = generator.email({ domain: "example.com" }) + const newUser = await config.api.public.user.create({ + email, + roles: {}, + }) + expect(newUser.email).toBe(email) + expect(newUser._id).toBeDefined() + }) + + describe("role creation on free tier", () => { + it("should not allow 'roles' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: { app_a: "BASIC" }, + }) + expect(newUser.roles["app_a"]).toBeUndefined() + }) + + it("should not allow 'admin' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, + admin: { global: true }, + }) + expect(newUser.admin).toBeUndefined() + }) + + it("should not allow 'builder' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, + builder: { global: true }, + }) + expect(newUser.builder).toBeUndefined() + }) + }) + + describe("role creation on business tier", () => { + beforeAll(() => { + mocks.licenses.useExpandedPublicApi() + }) + + it("should allow 'roles' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: { app_a: "BASIC" }, + }) + expect(newUser.roles["app_a"]).toBe("BASIC") + }) + + it("should allow 'admin' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, + admin: { global: true }, + }) + expect(newUser.admin?.global).toBe(true) + }) + + it("should allow 'builder' to be updated", async () => { + const newUser = await config.api.public.user.create({ + email: generator.email({ domain: "example.com" }), + roles: {}, + builder: { global: true }, + }) + expect(newUser.builder?.global).toBe(true) + }) + }) + }) + + describe("update", () => { + it("can update a user", async () => { + const updatedUser = await config.api.public.user.update({ + ...globalUser, + email: `updated-${globalUser.email}`, + }) + expect(updatedUser.email).toBe(`updated-${globalUser.email}`) + }) + + it("should not allow a user to update their own roles", async () => { + await config.withUser(globalUser, () => + config.api.public.user.update({ + ...globalUser, + roles: { app_1: "ADMIN" }, + }) + ) + const updatedUser = await config.api.user.find(globalUser._id!) + expect(updatedUser.roles?.app_1).toBeUndefined() + }) + }) + + describe("delete", () => { + it("should not allow a user to delete themselves", async () => { + await config.withUser(globalUser, () => + config.api.public.user.destroy(globalUser._id!, { status: 405 }) + ) + }) }) }) diff --git a/packages/server/src/api/routes/public/tests/utils.ts b/packages/server/src/api/routes/public/tests/utils.ts index 4fb048a540..4985c0db58 100644 --- a/packages/server/src/api/routes/public/tests/utils.ts +++ b/packages/server/src/api/routes/public/tests/utils.ts @@ -1,6 +1,10 @@ import * as setup from "../../tests/utilities" import { checkSlashesInUrl } from "../../../../utilities" import supertest from "supertest" +import { User } from "@budibase/types" +import environment from "../../../../environment" +import nock from "nock" +import { generator } from "@budibase/backend-core/tests" export type HttpMethod = "post" | "get" | "put" | "delete" | "patch" @@ -91,3 +95,43 @@ export function generateMakeRequestWithFormData( return res } } + +export function mockWorkerUserAPI(...seedUsers: User[]) { + const users: Record = { + ...seedUsers.reduce((acc, user) => { + acc[user._id!] = user + return acc + }, {} as Record), + } + + nock(environment.WORKER_URL!) + .get(new RegExp(`/api/global/users/.*`)) + .reply(200, (uri, body) => { + const id = uri.split("/").pop() + return users[id!] + }) + .persist() + + nock(environment.WORKER_URL!) + .post(`/api/global/users`) + .reply(200, (uri, body) => { + const newUser = body as User + if (!newUser._id) { + newUser._id = `us_${generator.guid()}` + } + users[newUser._id!] = newUser + return newUser + }) + .persist() + + nock(environment.WORKER_URL!) + .put(new RegExp(`/api/global/users/.*`)) + .reply(200, (uri, body) => { + const id = uri.split("/").pop()! + const updatedUser = body as User + const existingUser = users[id] || {} + users[id] = { ...existingUser, ...updatedUser } + return users[id] + }) + .persist() +} diff --git a/packages/server/src/tests/utilities/api/base.ts b/packages/server/src/tests/utilities/api/base.ts index 177c3c3c0b..2b3e3db44c 100644 --- a/packages/server/src/tests/utilities/api/base.ts +++ b/packages/server/src/tests/utilities/api/base.ts @@ -1,8 +1,13 @@ +import jestOpenAPI from "jest-openapi" +import { run as generateSchema } from "../../../../specs/generate" import TestConfiguration from "../TestConfiguration" import request, { SuperTest, Test, Response } from "supertest" import { ReadStream } from "fs" import { getServer } from "../../../app" +const yamlPath = generateSchema() +jestOpenAPI(yamlPath!) + type Headers = Record type Method = "get" | "post" | "put" | "patch" | "delete" @@ -170,10 +175,7 @@ export abstract class TestAPI { } } - protected _checkResponse = ( - response: Response, - expectations?: Expectations - ) => { + protected _checkResponse(response: Response, expectations?: Expectations) { const { status = 200 } = expectations || {} if (response.status !== status) { @@ -259,4 +261,14 @@ export abstract class PublicAPI extends TestAPI { return headers } + + protected _checkResponse(response: Response, expectations?: Expectations) { + const checked = super._checkResponse(response, expectations) + if (checked.status >= 200 && checked.status < 300) { + // We don't seem to have documented our errors yet, so for the time being + // we'll only do the schema check for successful responses. + expect(checked).toSatisfyApiSpec() + } + return checked + } } diff --git a/packages/server/src/tests/utilities/api/public/user.ts b/packages/server/src/tests/utilities/api/public/user.ts index a8a7baed7f..4f5fccc740 100644 --- a/packages/server/src/tests/utilities/api/public/user.ts +++ b/packages/server/src/tests/utilities/api/public/user.ts @@ -3,14 +3,18 @@ import { Expectations, PublicAPI } from "../base" export class UserPublicAPI extends PublicAPI { find = async (id: string, expectations?: Expectations): Promise => { - return await this._get(`/users/${id}`, { expectations }) + const response = await this._get<{ data: User }>(`/users/${id}`, { + expectations, + }) + return response.data } update = async (user: User, expectations?: Expectations): Promise => { - return await this._put(`/users/${user._id}`, { + const response = await this._put<{ data: User }>(`/users/${user._id}`, { body: user, expectations, }) + return response.data } destroy = async (id: string, expectations?: Expectations): Promise => { From 4f697b7731a3e3eca298a69196383bd4f256e987 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Thu, 27 Feb 2025 17:12:20 +0000 Subject: [PATCH 59/91] Adding groups to user app list. --- .../_components/BuilderSidePanel.svelte | 3 +- .../portal/users/users/[userId].svelte | 40 ++++++++++++------- .../_components/AppRoleTableRenderer.svelte | 4 +- packages/frontend-core/src/constants.ts | 1 + 4 files changed, 32 insertions(+), 16 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 4a7af9342e..59d14770ae 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -971,7 +971,8 @@ width: 100%; } - .auth-entity .user-email, .group-name { + .auth-entity .user-email, + .group-name { flex: 1 1 0; min-width: 0; overflow: hidden; diff --git a/packages/builder/src/pages/builder/portal/users/users/[userId].svelte b/packages/builder/src/pages/builder/portal/users/users/[userId].svelte index 6c480d9ef8..f02c2fe058 100644 --- a/packages/builder/src/pages/builder/portal/users/users/[userId].svelte +++ b/packages/builder/src/pages/builder/portal/users/users/[userId].svelte @@ -98,7 +98,9 @@ $: privileged = sdk.users.isAdminOrGlobalBuilder(user) $: nameLabel = getNameLabel(user) $: filteredGroups = getFilteredGroups(internalGroups, searchTerm) - $: availableApps = getAvailableApps($appsStore.apps, privileged, user?.roles) + $: availableApps = user + ? getApps(user, sdk.users.userAppAccessList(user, $groups || [])) + : [] $: userGroups = $groups.filter(x => { return x.users?.find(y => { return y._id === userId @@ -107,23 +109,19 @@ $: globalRole = users.getUserRole(user) $: isTenantOwner = tenantOwner?.email && tenantOwner.email === user?.email - const getAvailableApps = (appList, privileged, roles) => { - let availableApps = appList.slice() - if (!privileged) { - availableApps = availableApps.filter(x => { - let roleKeys = Object.keys(roles || {}) - return roleKeys.concat(user?.builder?.apps).find(y => { - return x.appId === appsStore.extractAppId(y) - }) - }) - } + const getApps = (user, appIds) => { + let availableApps = $appsStore.apps + .slice() + .filter(app => + appIds.find(id => id === appsStore.getProdAppID(app.devId)) + ) return availableApps.map(app => { const prodAppId = appsStore.getProdAppID(app.devId) return { name: app.name, devId: app.devId, icon: app.icon, - role: getRole(prodAppId, roles), + role: getRole(prodAppId, user), } }) } @@ -136,7 +134,7 @@ return groups.filter(group => group.name?.toLowerCase().includes(search)) } - const getRole = (prodAppId, roles) => { + const getRole = (prodAppId, user) => { if (privileged) { return Constants.Roles.ADMIN } @@ -145,7 +143,21 @@ return Constants.Roles.CREATOR } - return roles[prodAppId] + if (user?.roles[prodAppId]) { + return user.roles[prodAppId] + } + + // check if access via group for creator + const foundGroup = $groups?.find( + group => group.roles[prodAppId] || group.builder?.apps[prodAppId] + ) + if (foundGroup.builder?.apps[prodAppId]) { + return Constants.Roles.CREATOR + } + // can't tell how groups will control role + if (foundGroup.roles[prodAppId]) { + return Constants.Roles.GROUP + } } const getNameLabel = user => { diff --git a/packages/builder/src/pages/builder/portal/users/users/_components/AppRoleTableRenderer.svelte b/packages/builder/src/pages/builder/portal/users/users/_components/AppRoleTableRenderer.svelte index 9429cfbc23..5adc38ebc6 100644 --- a/packages/builder/src/pages/builder/portal/users/users/_components/AppRoleTableRenderer.svelte +++ b/packages/builder/src/pages/builder/portal/users/users/_components/AppRoleTableRenderer.svelte @@ -15,7 +15,9 @@ } -{#if value === Constants.Roles.CREATOR} +{#if value === Constants.Roles.GROUP} + Controlled by group +{:else if value === Constants.Roles.CREATOR} Can edit {:else} Date: Fri, 28 Feb 2025 10:12:58 +0100 Subject: [PATCH 60/91] Handle whitespaces on complex keys --- packages/builder/src/dataBinding.js | 25 +++++++++++++++++-------- 1 file changed, 17 insertions(+), 8 deletions(-) diff --git a/packages/builder/src/dataBinding.js b/packages/builder/src/dataBinding.js index 80bcd1984a..1b4c69be71 100644 --- a/packages/builder/src/dataBinding.js +++ b/packages/builder/src/dataBinding.js @@ -373,6 +373,18 @@ const getContextBindings = (asset, componentId) => { .flat() } +const makeReadableKeyPropSafe = key => { + if (!key.includes(" ")) { + return key + } + + if (new RegExp(/^\[(.+)\]$/).test(key.test)) { + return key + } + + return `[${key}]` +} + /** * Generates a set of bindings for a given component context */ @@ -457,15 +469,11 @@ const generateComponentContextBindings = (asset, componentContext) => { const runtimeBinding = `${safeComponentId}.${safeKey}` // Optionally use a prefix with readable bindings - let readableBinding = component._instanceName + let readableBinding = makeReadableKeyPropSafe(component._instanceName) if (readablePrefix) { readableBinding += `.${readablePrefix}` } - readableBinding += `.${fieldSchema.name || key}` - - if (readableBinding.includes(" ")) { - readableBinding = `[${readableBinding}]` - } + readableBinding += `.${makeReadableKeyPropSafe(fieldSchema.name || key)}` // Determine which category this binding belongs in const bindingCategory = getComponentBindingCategory( @@ -477,7 +485,7 @@ const generateComponentContextBindings = (asset, componentContext) => { bindings.push({ type: "context", runtimeBinding, - readableBinding: `${readableBinding}`, + readableBinding, // Field schema and provider are required to construct relationship // datasource options, based on bindable properties fieldSchema, @@ -1358,13 +1366,14 @@ const bindingReplacement = ( } // work from longest to shortest const convertFromProps = bindableProperties + // TODO check whitespaces .map(el => el[convertFrom]) .sort((a, b) => { return b.length - a.length }) const boundValues = textWithBindings.match(regex) || [] let result = textWithBindings - for (let boundValue of boundValues) { + for (const boundValue of boundValues) { let newBoundValue = boundValue // we use a search string, where any time we replace something we blank it out // in the search, working from longest to shortest so always use best match first From d7702810c2236fa5a69915d1ef4d2fc3771f8618 Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Fri, 28 Feb 2025 10:27:36 +0100 Subject: [PATCH 61/91] Handle whitespaces on complex keys in formulas --- .../builder/src/components/backend/DataTable/formula.js | 9 ++++----- packages/builder/src/dataBinding.js | 2 +- 2 files changed, 5 insertions(+), 6 deletions(-) diff --git a/packages/builder/src/components/backend/DataTable/formula.js b/packages/builder/src/components/backend/DataTable/formula.js index c0fdb96a07..8dcda83c27 100644 --- a/packages/builder/src/components/backend/DataTable/formula.js +++ b/packages/builder/src/components/backend/DataTable/formula.js @@ -2,6 +2,7 @@ import { FieldType } from "@budibase/types" import { FIELDS } from "@/constants/backend" import { tables } from "@/stores/builder" import { get as svelteGet } from "svelte/store" +import { makeReadableKeyPropSafe } from "@/dataBinding" // currently supported level of relationship depth (server side) const MAX_DEPTH = 1 @@ -62,11 +63,9 @@ export function getBindings({ const label = path == null ? column : `${path}.0.${column}` const binding = path == null ? `[${column}]` : `[${path}].0.[${column}]` - - let readableBinding = label - if (readableBinding.includes(" ")) { - readableBinding = `[${readableBinding}]` - } + const readableBinding = (path == null ? [column] : [path, "0", column]) + .map(makeReadableKeyPropSafe) + .join(".") // only supply a description for relationship paths const description = diff --git a/packages/builder/src/dataBinding.js b/packages/builder/src/dataBinding.js index 1b4c69be71..c6171c72a4 100644 --- a/packages/builder/src/dataBinding.js +++ b/packages/builder/src/dataBinding.js @@ -373,7 +373,7 @@ const getContextBindings = (asset, componentId) => { .flat() } -const makeReadableKeyPropSafe = key => { +export const makeReadableKeyPropSafe = key => { if (!key.includes(" ")) { return key } From 5cd5a201772b18863176d53d558ee44452be482d Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 15:01:34 +0000 Subject: [PATCH 62/91] Fixing an issue switching back to controlled by group. --- .../_components/BuilderSidePanel.svelte | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte index 59d14770ae..737edd69f7 100644 --- a/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte +++ b/packages/builder/src/pages/builder/app/[application]/_components/BuilderSidePanel.svelte @@ -198,12 +198,19 @@ return } const update = await users.get(user._id) + const newRoles = { + ...update.roles, + [prodAppId]: role, + } + // make sure no undefined/null roles (during removal) + for (let [appId, role] of Object.entries(newRoles)) { + if (!role) { + delete newRoles[appId] + } + } await users.save({ ...update, - roles: { - ...update.roles, - [prodAppId]: role, - }, + roles: newRoles, }) await searchUsers(query, $builderStore.builderSidePanel, loaded) } From 67d31b971a69e3d664606c36672c2758f51df7ab Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 16:56:31 +0000 Subject: [PATCH 63/91] Updating master reference. --- packages/pro | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/pro b/packages/pro index e3843dd4ea..b28dbd5492 160000 --- a/packages/pro +++ b/packages/pro @@ -1 +1 @@ -Subproject commit e3843dd4eaced68ae063355b77df200dbc789c98 +Subproject commit b28dbd549284cf450be7f25ad85aadf614d08f0b From ebfd8eb6c8a75e682ead8fd94d1079e11bd27c1f Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 17:14:19 +0000 Subject: [PATCH 64/91] Fixing readme action. --- .github/workflows/readme-openapi.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/readme-openapi.yml b/.github/workflows/readme-openapi.yml index 9f42f6141b..e6224156b6 100644 --- a/.github/workflows/readme-openapi.yml +++ b/.github/workflows/readme-openapi.yml @@ -20,7 +20,7 @@ jobs: - run: yarn --frozen-lockfile - name: Install OpenAPI pkg - run: yarn global add openapi + run: yarn global add rdme openapi - name: update specs - run: cd packages/server && yarn specs && openapi specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=6728a74f5918b50036c61841 + run: cd packages/server && yarn specs && rdme openapi specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=6728a74f5918b50036c61841 From 415570b802b3eea7aa9e4d2b5a5d0b135d70eb17 Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 17:21:57 +0000 Subject: [PATCH 65/91] Another readme action fix. --- .github/workflows/readme-openapi.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/readme-openapi.yml b/.github/workflows/readme-openapi.yml index e6224156b6..f7a563fc45 100644 --- a/.github/workflows/readme-openapi.yml +++ b/.github/workflows/readme-openapi.yml @@ -23,4 +23,4 @@ jobs: run: yarn global add rdme openapi - name: update specs - run: cd packages/server && yarn specs && rdme openapi specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=6728a74f5918b50036c61841 + run: cd packages/server && yarn specs && rdme openapi upload specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=6728a74f5918b50036c61841 From 4077a6df35c319bfdab9962ea7c2101388e7702c Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 17:48:23 +0000 Subject: [PATCH 66/91] Final fix for rdme. --- .github/workflows/readme-openapi.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/readme-openapi.yml b/.github/workflows/readme-openapi.yml index f7a563fc45..ec04e4001c 100644 --- a/.github/workflows/readme-openapi.yml +++ b/.github/workflows/readme-openapi.yml @@ -20,7 +20,7 @@ jobs: - run: yarn --frozen-lockfile - name: Install OpenAPI pkg - run: yarn global add rdme openapi + run: yarn global add rdme - name: update specs - run: cd packages/server && yarn specs && rdme openapi upload specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=6728a74f5918b50036c61841 + run: cd packages/server && yarn specs && rdme openapi specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=67c16880add6da002352069a From b4ad744261a9cb47fcadf8e25af57909311900ee Mon Sep 17 00:00:00 2001 From: mike12345567 Date: Fri, 28 Feb 2025 17:52:18 +0000 Subject: [PATCH 67/91] Set rdme cli version (hardcoded). --- .github/workflows/readme-openapi.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/readme-openapi.yml b/.github/workflows/readme-openapi.yml index ec04e4001c..27a68e69cf 100644 --- a/.github/workflows/readme-openapi.yml +++ b/.github/workflows/readme-openapi.yml @@ -20,7 +20,7 @@ jobs: - run: yarn --frozen-lockfile - name: Install OpenAPI pkg - run: yarn global add rdme + run: yarn global add rdme@8.6.6 - name: update specs run: cd packages/server && yarn specs && rdme openapi specs/openapi.yaml --key=${{ secrets.README_API_KEY }} --id=67c16880add6da002352069a From e2e1e9d7d2a9080e3af858820a7cfc85b0603017 Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Mon, 3 Mar 2025 09:55:34 +0000 Subject: [PATCH 68/91] De-mock the environment variable tests. --- .../routes/tests/environmentVariables.spec.ts | 237 +++++++----------- .../src/tests/utilities/api/environment.ts | 52 ++++ .../server/src/tests/utilities/api/index.ts | 3 + .../server/src/tests/utilities/structures.ts | 5 +- 4 files changed, 155 insertions(+), 142 deletions(-) create mode 100644 packages/server/src/tests/utilities/api/environment.ts diff --git a/packages/server/src/api/routes/tests/environmentVariables.spec.ts b/packages/server/src/api/routes/tests/environmentVariables.spec.ts index beb6012c9c..e6df353797 100644 --- a/packages/server/src/api/routes/tests/environmentVariables.spec.ts +++ b/packages/server/src/api/routes/tests/environmentVariables.spec.ts @@ -1,153 +1,108 @@ const pg = require("pg") -jest.mock("pg", () => { - return { - Client: jest.fn().mockImplementation(() => ({ - connect: jest.fn(), - query: jest.fn().mockImplementation(() => ({ rows: [] })), - end: jest.fn().mockImplementation((fn: any) => fn()), - })), - queryMock: jest.fn().mockImplementation(() => {}), - on: jest.fn(), - } -}) -import * as setup from "./utilities" +import { structures } from "./utilities" import { mocks } from "@budibase/backend-core/tests" -import { env, events } from "@budibase/backend-core" -import { QueryPreview } from "@budibase/types" +import { setEnv } from "@budibase/backend-core" +import { Datasource } from "@budibase/types" +import TestConfiguration from "../../../tests/utilities/TestConfiguration" +import { + DatabaseName, + datasourceDescribe, +} from "../../../integrations/tests/utils" -const structures = setup.structures +const describes = datasourceDescribe({ only: [DatabaseName.POSTGRES] }) -env._set("ENCRYPTION_KEY", "budibase") -mocks.licenses.useEnvironmentVariables() +if (describes.length > 0) { + describe.each(describes)("/api/env/variables", ({ dsProvider }) => { + const config = new TestConfiguration() -describe("/api/env/variables", () => { - let request = setup.getRequest() - let config = setup.getConfig() + let rawDatasource: Datasource + let restoreEnv: () => void - afterAll(setup.afterAll) + beforeAll(async () => { + await config.init() + restoreEnv = setEnv({ ENCRYPTION_KEY: "budibase" }) + mocks.licenses.useEnvironmentVariables() - beforeAll(async () => { - await config.init() - }) + const ds = await dsProvider() + rawDatasource = ds.rawDatasource! + }) - it("should be able check the status of env var API", async () => { - const res = await request - .get(`/api/env/variables/status`) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) + afterAll(() => { + restoreEnv() + }) - expect(res.body.encryptionKeyAvailable).toEqual(true) - }) - - it("should be able to create an environment variable", async () => { - await request - .post(`/api/env/variables`) - .send(structures.basicEnvironmentVariable("test", "test")) - .set(config.defaultHeaders()) - .expect(200) - }) - - it("should be able to fetch the 'test' variable name", async () => { - const res = await request - .get(`/api/env/variables`) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) - expect(res.body.variables.length).toEqual(1) - expect(res.body.variables[0]).toEqual("test") - }) - - it("should be able to update the environment variable 'test'", async () => { - const varName = "test" - await request - .patch(`/api/env/variables/${varName}`) - .send(structures.basicEnvironmentVariable("test", "test1")) - .set(config.defaultHeaders()) - .expect(200) - }) - - it("should be able to delete the environment variable 'test'", async () => { - const varName = "test" - await request - .delete(`/api/env/variables/${varName}`) - .set(config.defaultHeaders()) - .expect(200) - }) - - it("should create a datasource (using the environment variable) and query", async () => { - const datasourceBase = structures.basicDatasource() - await request - .post(`/api/env/variables`) - .send(structures.basicEnvironmentVariable("test", "test")) - .set(config.defaultHeaders()) - - datasourceBase.datasource.config = { - password: "{{ env.test }}", - } - const response = await request - .post(`/api/datasources`) - .send(datasourceBase) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) - expect(response.body.datasource._id).toBeDefined() - - const response2 = await request - .post(`/api/queries`) - .send(structures.basicQuery(response.body.datasource._id)) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) - expect(response2.body._id).toBeDefined() - }) - - it("should run a query preview and check the mocked results", async () => { - const datasourceBase = structures.basicDatasource() - await request - .post(`/api/env/variables`) - .send(structures.basicEnvironmentVariable("test", "test")) - .set(config.defaultHeaders()) - - datasourceBase.datasource.config = { - password: "{{ env.test }}", - } - const response = await request - .post(`/api/datasources`) - .send(datasourceBase) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) - expect(response.body.datasource._id).toBeDefined() - - const queryPreview: QueryPreview = { - datasourceId: response.body.datasource._id, - parameters: [], - fields: {}, - queryVerb: "read", - name: response.body.datasource.name, - transformer: null, - schema: {}, - readable: true, - } - const res = await request - .post(`/api/queries/preview`) - .send(queryPreview) - .set(config.defaultHeaders()) - .expect("Content-Type", /json/) - .expect(200) - expect(res.body.rows.length).toEqual(0) - expect(events.query.previewed).toHaveBeenCalledTimes(1) - // API doesn't include config in response - delete response.body.datasource.config - expect(events.query.previewed).toHaveBeenCalledWith( - response.body.datasource, - { - ...queryPreview, - nullDefaultSupport: true, + beforeEach(async () => { + const { variables } = await config.api.environment.fetch() + for (const variable of variables) { + await config.api.environment.destroy(variable) } - ) - expect(pg.Client).toHaveBeenCalledWith({ password: "test", ssl: undefined }) + + await config.api.environment.create({ + name: "test", + production: rawDatasource.config!.password, + development: rawDatasource.config!.password, + }) + }) + + it("should be able check the status of env var API", async () => { + const { encryptionKeyAvailable } = await config.api.environment.status() + expect(encryptionKeyAvailable).toEqual(true) + }) + + it("should be able to fetch the 'test' variable name", async () => { + const { variables } = await config.api.environment.fetch() + expect(variables.length).toEqual(1) + expect(variables[0]).toEqual("test") + }) + + it("should be able to update the environment variable 'test'", async () => { + await config.api.environment.update("test", { + production: "test1", + development: "test1", + }) + }) + + it("should be able to delete the environment variable 'test'", async () => { + await config.api.environment.destroy("test") + }) + + it("should create a datasource (using the environment variable) and query", async () => { + const datasource = await config.api.datasource.create({ + ...structures.basicDatasource().datasource, + config: { + ...rawDatasource.config, + password: "{{ env.test }}", + }, + }) + + const query = await config.api.query.save({ + ...structures.basicQuery(datasource._id!), + fields: { sql: "SELECT 1" }, + }) + expect(query._id).toBeDefined() + }) + + it("should run a query preview and check the mocked results", async () => { + const datasource = await config.api.datasource.create({ + ...structures.basicDatasource().datasource, + config: { + ...rawDatasource.config, + password: "{{ env.test }}", + }, + }) + + const query = await config.api.query.save({ + ...structures.basicQuery(datasource._id!), + fields: { sql: "SELECT 1 as id" }, + }) + + const { rows } = await config.api.query.preview({ + ...query, + queryId: query._id!, + }) + + expect(rows).toEqual([{ id: 1 }]) + }) }) -}) +} diff --git a/packages/server/src/tests/utilities/api/environment.ts b/packages/server/src/tests/utilities/api/environment.ts new file mode 100644 index 0000000000..2c4e7a751e --- /dev/null +++ b/packages/server/src/tests/utilities/api/environment.ts @@ -0,0 +1,52 @@ +import { Expectations, TestAPI } from "./base" +import { + CreateEnvironmentVariableRequest, + CreateEnvironmentVariableResponse, + GetEnvironmentVariablesResponse, + Row, + StatusEnvironmentVariableResponse, + UpdateEnvironmentVariableRequest, +} from "@budibase/types" + +export class EnvironmentAPI extends TestAPI { + create = async ( + body: CreateEnvironmentVariableRequest, + expectations?: Expectations + ) => { + return await this._post( + `/api/env/variables`, + { body, expectations } + ) + } + + status = async (expectations?: Expectations) => { + return await this._get( + `/api/env/variables/status`, + { expectations } + ) + } + + fetch = async (expectations?: Expectations) => { + return await this._get( + `/api/env/variables`, + { expectations } + ) + } + + update = async ( + varName: string, + body: UpdateEnvironmentVariableRequest, + expectations?: Expectations + ) => { + return await this._patch(`/api/env/variables/${varName}`, { + body, + expectations, + }) + } + + destroy = async (varName: string, expectations?: Expectations) => { + return await this._delete(`/api/env/variables/${varName}`, { + expectations, + }) + } +} diff --git a/packages/server/src/tests/utilities/api/index.ts b/packages/server/src/tests/utilities/api/index.ts index 2fdf726b6c..42afd10647 100644 --- a/packages/server/src/tests/utilities/api/index.ts +++ b/packages/server/src/tests/utilities/api/index.ts @@ -17,6 +17,7 @@ import { RowActionAPI } from "./rowAction" import { AutomationAPI } from "./automation" import { PluginAPI } from "./plugin" import { WebhookAPI } from "./webhook" +import { EnvironmentAPI } from "./environment" export default class API { application: ApplicationAPI @@ -24,6 +25,7 @@ export default class API { automation: AutomationAPI backup: BackupAPI datasource: DatasourceAPI + environment: EnvironmentAPI legacyView: LegacyViewAPI permission: PermissionAPI plugin: PluginAPI @@ -44,6 +46,7 @@ export default class API { this.automation = new AutomationAPI(config) this.backup = new BackupAPI(config) this.datasource = new DatasourceAPI(config) + this.environment = new EnvironmentAPI(config) this.legacyView = new LegacyViewAPI(config) this.permission = new PermissionAPI(config) this.plugin = new PluginAPI(config) diff --git a/packages/server/src/tests/utilities/structures.ts b/packages/server/src/tests/utilities/structures.ts index 38d60e1c11..bcad085e08 100644 --- a/packages/server/src/tests/utilities/structures.ts +++ b/packages/server/src/tests/utilities/structures.ts @@ -37,6 +37,9 @@ import { DeepPartial, FilterCondition, AutomationTriggerResult, + EnvironmentVariablesDoc, + EnvironmentVariableValue, + CreateEnvironmentVariableRequest, } from "@budibase/types" import { LoopInput } from "../../definitions/automations" import { merge } from "lodash" @@ -574,7 +577,7 @@ export function basicEnvironmentVariable( name: string, prod: string, dev?: string -) { +): CreateEnvironmentVariableRequest { return { name, production: prod, From 81bfd81126ac89ea0824648b553377a0a7b2e34c Mon Sep 17 00:00:00 2001 From: Sam Rose Date: Mon, 3 Mar 2025 10:15:47 +0000 Subject: [PATCH 69/91] Fix lint. --- .../server/src/api/routes/tests/environmentVariables.spec.ts | 2 -- packages/server/src/tests/utilities/api/environment.ts | 1 - packages/server/src/tests/utilities/structures.ts | 2 -- 3 files changed, 5 deletions(-) diff --git a/packages/server/src/api/routes/tests/environmentVariables.spec.ts b/packages/server/src/api/routes/tests/environmentVariables.spec.ts index e6df353797..c663e2e26e 100644 --- a/packages/server/src/api/routes/tests/environmentVariables.spec.ts +++ b/packages/server/src/api/routes/tests/environmentVariables.spec.ts @@ -1,5 +1,3 @@ -const pg = require("pg") - import { structures } from "./utilities" import { mocks } from "@budibase/backend-core/tests" import { setEnv } from "@budibase/backend-core" diff --git a/packages/server/src/tests/utilities/api/environment.ts b/packages/server/src/tests/utilities/api/environment.ts index 2c4e7a751e..152336b316 100644 --- a/packages/server/src/tests/utilities/api/environment.ts +++ b/packages/server/src/tests/utilities/api/environment.ts @@ -3,7 +3,6 @@ import { CreateEnvironmentVariableRequest, CreateEnvironmentVariableResponse, GetEnvironmentVariablesResponse, - Row, StatusEnvironmentVariableResponse, UpdateEnvironmentVariableRequest, } from "@budibase/types" diff --git a/packages/server/src/tests/utilities/structures.ts b/packages/server/src/tests/utilities/structures.ts index bcad085e08..1679334cab 100644 --- a/packages/server/src/tests/utilities/structures.ts +++ b/packages/server/src/tests/utilities/structures.ts @@ -37,8 +37,6 @@ import { DeepPartial, FilterCondition, AutomationTriggerResult, - EnvironmentVariablesDoc, - EnvironmentVariableValue, CreateEnvironmentVariableRequest, } from "@budibase/types" import { LoopInput } from "../../definitions/automations" From a4eb5642a823451fe620b7992dfb23e8fc0ebe73 Mon Sep 17 00:00:00 2001 From: Budibase Staging Release Bot <> Date: Mon, 3 Mar 2025 11:13:29 +0000 Subject: [PATCH 70/91] Bump version to 3.4.22 --- lerna.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lerna.json b/lerna.json index 8972a00565..d20097b6e5 100644 --- a/lerna.json +++ b/lerna.json @@ -1,6 +1,6 @@ { "$schema": "node_modules/lerna/schemas/lerna-schema.json", - "version": "3.4.21", + "version": "3.4.22", "npmClient": "yarn", "concurrency": 20, "command": { From a7e17712a30acca56d54bcabe5dafdd326e5a99a Mon Sep 17 00:00:00 2001 From: Adria Navarro Date: Mon, 3 Mar 2025 12:23:25 +0100 Subject: [PATCH 71/91] Remove types --- .../app/forms/RelationshipField.svelte | 37 +++++++------------ .../frontend-core/src/fetch/GroupUserFetch.ts | 2 +- packages/frontend-core/src/fetch/UserFetch.ts | 4 +- 3 files changed, 16 insertions(+), 27 deletions(-) diff --git a/packages/client/src/components/app/forms/RelationshipField.svelte b/packages/client/src/components/app/forms/RelationshipField.svelte index 0226e7d7f3..c40041c7d6 100644 --- a/packages/client/src/components/app/forms/RelationshipField.svelte +++ b/packages/client/src/components/app/forms/RelationshipField.svelte @@ -1,12 +1,6 @@ @@ -449,12 +449,7 @@
    -{#if showSnippetDrawer} - (showSnippetDrawer = false)} - /> -{/if} +