refactor(editor): Refactor code completions mixins to composables (no-changelog) (#9459)

Signed-off-by: Oleg Ivaniv <me@olegivaniv.com>
This commit is contained in:
oleg
2024-05-21 12:07:04 +02:00
committed by GitHub
parent 5ef45e8559
commit 277511a9b5
20 changed files with 1715 additions and 1027 deletions

View File

@@ -14,7 +14,7 @@
}, },
{ {
"parameters": { "parameters": {
"url": "https://random-data-api.com/api/v2/users?size=5", "url": "https://internal.users.n8n.cloud/webhook/random-data-api",
"options": {} "options": {}
}, },
"id": "22511d75-ab54-49e1-b8af-08b8b3372373", "id": "22511d75-ab54-49e1-b8af-08b8b3372373",
@@ -28,7 +28,7 @@
}, },
{ {
"parameters": { "parameters": {
"jsCode": "// Loop over input items and add a new field called 'myNewField' to the JSON of each one\nfor (const item of $input.all()) {\n item.json.first_name_reversed = item.json = {\n firstName: item.json.first_name,\n firstnNameReversed: item.json.first_name_BUG.split(\"\").reverse().join(\"\")\n };\n}\n\nreturn $input.all();" "jsCode": "// Loop over input items and add a new field called 'myNewField' to the JSON of each one\nfor (const item of $input.all()) {\n item.json.first_name_reversed = item.json = {\n firstName: item.json.firstname,\n firstnNameReversed: item.json.firstname.split(\"\").reverse().join(\"\")\n };\n}\n\nreturn $input.all();"
}, },
"id": "4b66b15a-1685-46c1-a5e3-ebf8cdb11d21", "id": "4b66b15a-1685-46c1-a5e3-ebf8cdb11d21",
"name": "do something with them", "name": "do something with them",
@@ -130,4 +130,4 @@
}, },
"id": "PymcwIrbqgNh3O0K", "id": "PymcwIrbqgNh3O0K",
"tags": [] "tags": []
} }

View File

@@ -1,36 +1,57 @@
import type { PropType } from 'vue';
import { defineComponent } from 'vue'; import { defineComponent } from 'vue';
import { autocompletion } from '@codemirror/autocomplete'; import { autocompletion } from '@codemirror/autocomplete';
import { localCompletionSource } from '@codemirror/lang-javascript'; import { localCompletionSource } from '@codemirror/lang-javascript';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { Extension } from '@codemirror/state'; import type { Extension } from '@codemirror/state';
import { baseCompletions } from './completions/base.completions'; import { useBaseCompletions } from './completions/base.completions';
import { jsSnippets } from './completions/js.snippets'; import { jsSnippets } from './completions/js.snippets';
import { requireCompletions } from './completions/require.completions';
import { executionCompletions } from './completions/execution.completions'; import type { CodeExecutionMode } from 'n8n-workflow';
import { workflowCompletions } from './completions/workflow.completions'; import { CODE_EXECUTION_MODES } from 'n8n-workflow';
import { prevNodeCompletions } from './completions/prevNode.completions'; import { useExecutionCompletions } from './completions/execution.completions';
import { luxonCompletions } from './completions/luxon.completions'; import { useItemFieldCompletions } from './completions/itemField.completions';
import { itemIndexCompletions } from './completions/itemIndex.completions'; import { useItemIndexCompletions } from './completions/itemIndex.completions';
import { itemFieldCompletions } from './completions/itemField.completions'; import { useJsonFieldCompletions } from './completions/jsonField.completions';
import { jsonFieldCompletions } from './completions/jsonField.completions'; import { useLuxonCompletions } from './completions/luxon.completions';
import { variablesCompletions } from './completions/variables.completions'; import { usePrevNodeCompletions } from './completions/prevNode.completions';
import { useRequireCompletions } from './completions/require.completions';
import { useVariablesCompletions } from './completions/variables.completions';
import { useWorkflowCompletions } from './completions/workflow.completions';
import type { EditorView } from '@codemirror/view';
export const completerExtension = defineComponent({ export const completerExtension = defineComponent({
mixins: [ props: {
baseCompletions, mode: {
requireCompletions, type: String as PropType<CodeExecutionMode>,
executionCompletions, validator: (value: CodeExecutionMode): boolean => CODE_EXECUTION_MODES.includes(value),
workflowCompletions, required: true,
variablesCompletions, },
prevNodeCompletions, },
luxonCompletions, data() {
itemIndexCompletions, return {
itemFieldCompletions, editor: null as EditorView | null,
jsonFieldCompletions, };
], },
methods: { methods: {
autocompletionExtension(language: 'javaScript' | 'python'): Extension { autocompletionExtension(language: 'javaScript' | 'python'): Extension {
// Base completions
const { baseCompletions, itemCompletions, nodeSelectorCompletions } = useBaseCompletions(
this.mode,
language,
);
const { executionCompletions } = useExecutionCompletions();
const { inputMethodCompletions, selectorMethodCompletions } =
useItemFieldCompletions(language);
const { inputCompletions, selectorCompletions } = useItemIndexCompletions(this.mode);
const { inputJsonFieldCompletions, selectorJsonFieldCompletions } = useJsonFieldCompletions();
const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
const { prevNodeCompletions } = usePrevNodeCompletions();
const { requireCompletions } = useRequireCompletions();
const { variablesCompletions } = useVariablesCompletions();
const { workflowCompletions } = useWorkflowCompletions();
const completions = []; const completions = [];
if (language === 'javaScript') { if (language === 'javaScript') {
completions.push(jsSnippets, localCompletionSource); completions.push(jsSnippets, localCompletionSource);
@@ -47,31 +68,31 @@ export const completerExtension = defineComponent({
...completions, ...completions,
// core // core
this.itemCompletions, itemCompletions,
this.baseCompletions, baseCompletions,
this.requireCompletions, requireCompletions,
this.nodeSelectorCompletions, nodeSelectorCompletions,
this.prevNodeCompletions, prevNodeCompletions,
this.workflowCompletions, workflowCompletions,
this.variablesCompletions, variablesCompletions,
this.executionCompletions, executionCompletions,
// luxon // luxon
this.todayCompletions, todayCompletions,
this.nowCompletions, nowCompletions,
this.dateTimeCompletions, dateTimeCompletions,
// item index // item index
this.inputCompletions, inputCompletions,
this.selectorCompletions, selectorCompletions,
// item field // item field
this.inputMethodCompletions, inputMethodCompletions,
this.selectorMethodCompletions, selectorMethodCompletions,
// item json field // item json field
this.inputJsonFieldCompletions, inputJsonFieldCompletions,
this.selectorJsonFieldCompletions, selectorJsonFieldCompletions,
// multiline // multiline
this.multilineCompletions, this.multilineCompletions,
@@ -109,17 +130,17 @@ export const completerExtension = defineComponent({
const varNames = Object.keys(variablesToValues); const varNames = Object.keys(variablesToValues);
const uses = this.extendedUses(docLines, varNames); const uses = this.extendedUses(docLines, varNames);
const { matcherItemFieldCompletions } = useItemFieldCompletions('javaScript');
for (const use of uses.itemField) { for (const use of uses.itemField) {
const matcher = use.replace(/\.$/, ''); const matcher = use.replace(/\.$/, '');
const completions = this.matcherItemFieldCompletions(context, matcher, variablesToValues); const completions = matcherItemFieldCompletions(context, matcher, variablesToValues);
if (completions) return completions; if (completions) return completions;
} }
for (const use of uses.jsonField) { for (const use of uses.jsonField) {
const matcher = use.replace(/(\.|\[)$/, ''); const matcher = use.replace(/(\.|\[)$/, '');
const completions = this.matcherJsonFieldCompletions(context, matcher, variablesToValues); const completions = matcherItemFieldCompletions(context, matcher, variablesToValues);
if (completions) return completions; if (completions) return completions;
} }
@@ -168,25 +189,32 @@ export const completerExtension = defineComponent({
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json$/, all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json$/,
}); });
const { executionCompletions } = useExecutionCompletions();
const { inputCompletions, selectorCompletions } = useItemIndexCompletions(this.mode);
const { matcherJsonFieldCompletions } = useJsonFieldCompletions();
const { dateTimeCompletions, nowCompletions, todayCompletions } = useLuxonCompletions();
const { variablesCompletions } = useVariablesCompletions();
const { workflowCompletions } = useWorkflowCompletions();
for (const [variable, value] of Object.entries(variablesToValues)) { for (const [variable, value] of Object.entries(variablesToValues)) {
// core const { prevNodeCompletions } = usePrevNodeCompletions(variable);
if (value === '$execution') return this.executionCompletions(context, variable); if (value === '$execution') return executionCompletions(context, variable);
if (value === '$vars') return this.variablesCompletions(context, variable); if (value === '$vars') return variablesCompletions(context, variable);
if (value === '$workflow') return this.workflowCompletions(context, variable); if (value === '$workflow') return workflowCompletions(context, variable);
if (value === '$prevNode') return this.prevNodeCompletions(context, variable); if (value === '$prevNode') return prevNodeCompletions(context);
// luxon // luxon
if (value === '$now') return this.nowCompletions(context, variable); if (value === '$now') return nowCompletions(context, variable);
if (value === '$today') return this.todayCompletions(context, variable); if (value === '$today') return todayCompletions(context, variable);
if (value === 'DateTime') return this.dateTimeCompletions(context, variable); if (value === 'DateTime') return dateTimeCompletions(context, variable);
// item index // item index
if (value === '$input') return this.inputCompletions(context, variable); if (value === '$input') return inputCompletions(context, variable);
if (SELECTOR_REGEX.test(value)) return this.selectorCompletions(context, variable); if (SELECTOR_REGEX.test(value)) return selectorCompletions(context, variable);
// json field // json field
@@ -194,7 +222,7 @@ export const completerExtension = defineComponent({
const selectorJsonMatched = SELECTOR_JSON_REGEXES.some((regex) => regex.test(value)); const selectorJsonMatched = SELECTOR_JSON_REGEXES.some((regex) => regex.test(value));
if (inputJsonMatched || selectorJsonMatched) { if (inputJsonMatched || selectorJsonMatched) {
return this.matcherJsonFieldCompletions(context, variable, variablesToValues); return matcherJsonFieldCompletions(context, variable, variablesToValues);
} }
// item field // item field
@@ -203,7 +231,7 @@ export const completerExtension = defineComponent({
const selectorMethodMatched = SELECTOR_METHOD_REGEXES.some((regex) => regex.test(value)); const selectorMethodMatched = SELECTOR_METHOD_REGEXES.some((regex) => regex.test(value));
if (inputMethodMatched || selectorMethodMatched) { if (inputMethodMatched || selectorMethodMatched) {
return this.matcherItemFieldCompletions(context, variable, variablesToValues); return matcherItemFieldCompletions(context, variable, variablesToValues);
} }
} }

View File

@@ -1,11 +1,10 @@
import { defineComponent } from 'vue';
import { NODE_TYPES_EXCLUDED_FROM_AUTOCOMPLETION } from '../constants'; import { NODE_TYPES_EXCLUDED_FROM_AUTOCOMPLETION } from '../constants';
import { addVarType } from '../utils'; import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { INodeUi } from '@/Interface'; import type { INodeUi } from '@/Interface';
import { mapStores } from 'pinia';
import { useWorkflowsStore } from '@/stores/workflows.store'; import { useWorkflowsStore } from '@/stores/workflows.store';
import { escapeMappingString } from '@/utils/mappingUtils'; import { escapeMappingString } from '@/utils/mappingUtils';
import { useI18n } from '@/composables/useI18n';
function getAutoCompletableNodeNames(nodes: INodeUi[]) { function getAutoCompletableNodeNames(nodes: INodeUi[]) {
return nodes return nodes
@@ -13,149 +12,156 @@ function getAutoCompletableNodeNames(nodes: INodeUi[]) {
.map((node: INodeUi) => node.name); .map((node: INodeUi) => node.name);
} }
export const baseCompletions = defineComponent({ export function useBaseCompletions(
computed: { mode: 'runOnceForEachItem' | 'runOnceForAllItems',
...mapStores(useWorkflowsStore), language: string,
}, ) {
methods: { const i18n = useI18n();
itemCompletions(context: CompletionContext): CompletionResult | null { const workflowsStore = useWorkflowsStore();
const preCursor = context.matchBefore(/i\w*/);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const itemCompletions = (context: CompletionContext): CompletionResult | null => {
const preCursor = context.matchBefore(/i\w*/);
const options: Completion[] = []; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
if (this.mode === 'runOnceForEachItem') { const options: Completion[] = [];
options.push({
label: 'item',
info: this.$locale.baseText('codeNodeEditor.completer.$input.item'),
});
} else if (this.mode === 'runOnceForAllItems') {
options.push({
label: 'items',
info: this.$locale.baseText('codeNodeEditor.completer.$input.all'),
});
}
return { if (mode === 'runOnceForEachItem') {
from: preCursor.from, options.push({
options, label: 'item',
}; info: i18n.baseText('codeNodeEditor.completer.$input.item'),
}, });
} else if (mode === 'runOnceForAllItems') {
options.push({
label: 'items',
info: i18n.baseText('codeNodeEditor.completer.$input.all'),
});
}
/** return {
* - Complete `$` to `$execution $input $prevNode $runIndex $workflow $now $today from: preCursor.from,
* $jmespath $ifEmpt $('nodeName')` in both modes. options,
* - Complete `$` to `$json $binary $itemIndex` in single-item mode. };
*/ };
baseCompletions(context: CompletionContext): CompletionResult | null {
const prefix = this.language === 'python' ? '_' : '$';
const preCursor = context.matchBefore(new RegExp(`\\${prefix}\\w*`));
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; /**
* - Complete `$` to `$execution $input $prevNode $runIndex $workflow $now $today
* $jmespath $ifEmpt $('nodeName')` in both modes.
* - Complete `$` to `$json $binary $itemIndex` in single-item mode.
*/
const baseCompletions = (context: CompletionContext): CompletionResult | null => {
const prefix = language === 'python' ? '_' : '$';
const preCursor = context.matchBefore(new RegExp(`\\${prefix}\\w*`));
const TOP_LEVEL_COMPLETIONS_IN_BOTH_MODES: Completion[] = [ if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const TOP_LEVEL_COMPLETIONS_IN_BOTH_MODES: Completion[] = [
{
label: `${prefix}execution`,
info: i18n.baseText('codeNodeEditor.completer.$execution'),
},
{
label: `${prefix}ifEmpty()`,
info: i18n.baseText('codeNodeEditor.completer.$ifEmpty'),
},
{ label: `${prefix}input`, info: i18n.baseText('codeNodeEditor.completer.$input') },
{
label: `${prefix}prevNode`,
info: i18n.baseText('codeNodeEditor.completer.$prevNode'),
},
{
label: `${prefix}workflow`,
info: i18n.baseText('codeNodeEditor.completer.$workflow'),
},
{
label: `${prefix}vars`,
info: i18n.baseText('codeNodeEditor.completer.$vars'),
},
{
label: `${prefix}now`,
info: i18n.baseText('codeNodeEditor.completer.$now'),
},
{
label: `${prefix}today`,
info: i18n.baseText('codeNodeEditor.completer.$today'),
},
{
label: `${prefix}jmespath()`,
info: i18n.baseText('codeNodeEditor.completer.$jmespath'),
},
{
label: `${prefix}runIndex`,
info: i18n.baseText('codeNodeEditor.completer.$runIndex'),
},
{
label: `${prefix}nodeVersion`,
info: i18n.baseText('codeNodeEditor.completer.$nodeVersion'),
},
];
const options: Completion[] = TOP_LEVEL_COMPLETIONS_IN_BOTH_MODES.map(addVarType);
options.push(
...getAutoCompletableNodeNames(workflowsStore.allNodes).map((nodeName) => {
return {
label: `${prefix}('${escapeMappingString(nodeName)}')`,
type: 'variable',
info: i18n.baseText('codeNodeEditor.completer.$()', {
interpolate: { nodeName },
}),
};
}),
);
if (mode === 'runOnceForEachItem') {
const TOP_LEVEL_COMPLETIONS_IN_SINGLE_ITEM_MODE = [
{ label: `${prefix}json` },
{ label: `${prefix}binary` },
{ {
label: `${prefix}execution`, label: `${prefix}itemIndex`,
info: this.$locale.baseText('codeNodeEditor.completer.$execution'), info: i18n.baseText('codeNodeEditor.completer.$itemIndex'),
},
{
label: `${prefix}ifEmpty()`,
info: this.$locale.baseText('codeNodeEditor.completer.$ifEmpty'),
},
{ label: `${prefix}input`, info: this.$locale.baseText('codeNodeEditor.completer.$input') },
{
label: `${prefix}prevNode`,
info: this.$locale.baseText('codeNodeEditor.completer.$prevNode'),
},
{
label: `${prefix}workflow`,
info: this.$locale.baseText('codeNodeEditor.completer.$workflow'),
},
{
label: `${prefix}vars`,
info: this.$locale.baseText('codeNodeEditor.completer.$vars'),
},
{
label: `${prefix}now`,
info: this.$locale.baseText('codeNodeEditor.completer.$now'),
},
{
label: `${prefix}today`,
info: this.$locale.baseText('codeNodeEditor.completer.$today'),
},
{
label: `${prefix}jmespath()`,
info: this.$locale.baseText('codeNodeEditor.completer.$jmespath'),
},
{
label: `${prefix}runIndex`,
info: this.$locale.baseText('codeNodeEditor.completer.$runIndex'),
},
{
label: `${prefix}nodeVersion`,
info: this.$locale.baseText('codeNodeEditor.completer.$nodeVersion'),
}, },
]; ];
const options: Completion[] = TOP_LEVEL_COMPLETIONS_IN_BOTH_MODES.map(addVarType); options.push(...TOP_LEVEL_COMPLETIONS_IN_SINGLE_ITEM_MODE.map(addVarType));
}
options.push( return {
...getAutoCompletableNodeNames(this.workflowsStore.allNodes).map((nodeName) => { from: preCursor.from,
return { options,
label: `${prefix}('${escapeMappingString(nodeName)}')`, };
type: 'variable', };
info: this.$locale.baseText('codeNodeEditor.completer.$()', {
interpolate: { nodeName },
}),
};
}),
);
if (this.mode === 'runOnceForEachItem') { /**
const TOP_LEVEL_COMPLETIONS_IN_SINGLE_ITEM_MODE = [ * Complete `$(` to `$('nodeName')`.
{ label: `${prefix}json` }, */
{ label: `${prefix}binary` }, const nodeSelectorCompletions = (context: CompletionContext): CompletionResult | null => {
{ const prefix = language === 'python' ? '_' : '$';
label: `${prefix}itemIndex`, const preCursor = context.matchBefore(new RegExp(`\\${prefix}\\(.*`));
info: this.$locale.baseText('codeNodeEditor.completer.$itemIndex'),
},
];
options.push(...TOP_LEVEL_COMPLETIONS_IN_SINGLE_ITEM_MODE.map(addVarType)); if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
}
return { const options: Completion[] = getAutoCompletableNodeNames(workflowsStore.allNodes).map(
from: preCursor.from, (nodeName) => {
options, return {
}; label: `${prefix}('${escapeMappingString(nodeName)}')`,
}, type: 'variable',
info: i18n.baseText('codeNodeEditor.completer.$()', {
interpolate: { nodeName },
}),
};
},
);
/** return {
* Complete `$(` to `$('nodeName')`. from: preCursor.from,
*/ options,
nodeSelectorCompletions(context: CompletionContext): CompletionResult | null { };
const prefix = this.language === 'python' ? '_' : '$'; };
const preCursor = context.matchBefore(new RegExp(`\\${prefix}\\(.*`));
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; return {
itemCompletions,
const options: Completion[] = getAutoCompletableNodeNames(this.workflowsStore.allNodes).map( baseCompletions,
(nodeName) => { nodeSelectorCompletions,
return { };
label: `${prefix}('${escapeMappingString(nodeName)}')`, }
type: 'variable',
info: this.$locale.baseText('codeNodeEditor.completer.$()', {
interpolate: { nodeName },
}),
};
},
);
return {
from: preCursor.from,
options,
};
},
},
});

View File

@@ -1,78 +1,76 @@
import { defineComponent } from 'vue';
import { addVarType, escape } from '../utils'; import { addVarType, escape } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useI18n } from '@/composables/useI18n';
export const executionCompletions = defineComponent({ export function useExecutionCompletions() {
methods: { const i18n = useI18n();
/**
* Complete `$execution.` to `.id .mode .resumeUrl .resumeFormUrl`
*/
executionCompletions(
context: CompletionContext,
matcher = '$execution',
): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); /**
* Complete `$execution.` to `.id .mode .resumeUrl .resumeFormUrl`
*/
const executionCompletions = (
context: CompletionContext,
matcher = '$execution',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const preCursor = context.matchBefore(pattern);
const buildLinkNode = (text: string) => { if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const wrapper = document.createElement('span');
// This is being loaded from the locales file. This could
// cause an XSS of some kind but multiple other locales strings
// do the same thing.
wrapper.innerHTML = text;
return () => wrapper;
};
const options: Completion[] = [ const buildLinkNode = (text: string) => {
{ const wrapper = document.createElement('span');
label: `${matcher}.id`, // This is being loaded from the locales file. This could
info: this.$locale.baseText('codeNodeEditor.completer.$execution.id'), // cause an XSS of some kind but multiple other locales strings
}, // do the same thing.
{ wrapper.innerHTML = text;
label: `${matcher}.mode`, return () => wrapper;
info: this.$locale.baseText('codeNodeEditor.completer.$execution.mode'), };
},
{
label: `${matcher}.resumeUrl`,
info: this.$locale.baseText('codeNodeEditor.completer.$execution.resumeUrl'),
},
{
label: `${matcher}.resumeFormUrl`,
info: this.$locale.baseText('codeNodeEditor.completer.$execution.resumeFormUrl'),
},
{
label: `${matcher}.customData.set("key", "value")`,
info: buildLinkNode(
this.$locale.baseText('codeNodeEditor.completer.$execution.customData.set()'),
),
},
{
label: `${matcher}.customData.get("key")`,
info: buildLinkNode(
this.$locale.baseText('codeNodeEditor.completer.$execution.customData.get()'),
),
},
{
label: `${matcher}.customData.setAll({})`,
info: buildLinkNode(
this.$locale.baseText('codeNodeEditor.completer.$execution.customData.setAll()'),
),
},
{
label: `${matcher}.customData.getAll()`,
info: buildLinkNode(
this.$locale.baseText('codeNodeEditor.completer.$execution.customData.getAll()'),
),
},
];
return { const options: Completion[] = [
from: preCursor.from, {
options: options.map(addVarType), label: `${matcher}.id`,
}; info: i18n.baseText('codeNodeEditor.completer.$execution.id'),
}, },
}, {
}); label: `${matcher}.mode`,
info: i18n.baseText('codeNodeEditor.completer.$execution.mode'),
},
{
label: `${matcher}.resumeUrl`,
info: i18n.baseText('codeNodeEditor.completer.$execution.resumeUrl'),
},
{
label: `${matcher}.resumeFormUrl`,
info: i18n.baseText('codeNodeEditor.completer.$execution.resumeFormUrl'),
},
{
label: `${matcher}.customData.set("key", "value")`,
info: buildLinkNode(i18n.baseText('codeNodeEditor.completer.$execution.customData.set()')),
},
{
label: `${matcher}.customData.get("key")`,
info: buildLinkNode(i18n.baseText('codeNodeEditor.completer.$execution.customData.get()')),
},
{
label: `${matcher}.customData.setAll({})`,
info: buildLinkNode(
i18n.baseText('codeNodeEditor.completer.$execution.customData.setAll()'),
),
},
{
label: `${matcher}.customData.getAll()`,
info: buildLinkNode(
i18n.baseText('codeNodeEditor.completer.$execution.customData.getAll()'),
),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
};
return { executionCompletions };
}

View File

@@ -1,38 +1,94 @@
import { defineComponent } from 'vue';
import { addVarType, escape } from '../utils'; import { addVarType, escape } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useI18n } from '@/composables/useI18n';
export const itemFieldCompletions = defineComponent({ export function useItemFieldCompletions(language: 'python' | 'javaScript') {
methods: { const i18n = useI18n();
/**
* - Complete `x.first().` to `.json .binary`
* - Complete `x.last().` to `.json .binary`
* - Complete `x.all()[index].` to `.json .binary`
* - Complete `x.item.` to `.json .binary`.
*/
matcherItemFieldCompletions(
context: CompletionContext,
matcher: string,
variablesToValues: Record<string, string>,
) {
const preCursor = context.matchBefore(new RegExp(`${escape(matcher)}\..*`));
if (!preCursor) return null; /**
* - Complete `x.first().` to `.json .binary`
* - Complete `x.last().` to `.json .binary`
* - Complete `x.all()[index].` to `.json .binary`
* - Complete `x.item.` to `.json .binary`.
*/
const matcherItemFieldCompletions = (
context: CompletionContext,
matcher: string,
variablesToValues: Record<string, string>,
): CompletionResult | null => {
const preCursor = context.matchBefore(new RegExp(`${escape(matcher)}\..*`));
const [varName] = preCursor.text.split('.'); if (!preCursor) return null;
const originalValue = variablesToValues[varName]; const [varName] = preCursor.text.split('.');
if (!originalValue) return null; const originalValue = variablesToValues[varName];
if (!originalValue) return null;
const options: Completion[] = [
{
label: `${matcher}.json`,
info: i18n.baseText('codeNodeEditor.completer.json'),
},
{
label: `${matcher}.binary`,
info: i18n.baseText('codeNodeEditor.completer.binary'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
};
/**
* - Complete `$input.first().` to `.json .binary`.
* - Complete `$input.last().` to `.json .binary`.
* - Complete `$input.all()[index].` to `.json .binary`.
* - Complete `$input.item.` to `.json .binary`.
*/
const inputMethodCompletions = (context: CompletionContext): CompletionResult | null => {
const prefix = language === 'python' ? '_' : '$';
const patterns = {
first: new RegExp(`\\${prefix}input\\.first\\(\\)\\..*`),
last: new RegExp(`\\${prefix}input\\.last\\(\\)\\..*`),
item: new RegExp(`\\${prefix}item\\.first\\(\\)\\..*`),
all: /\$input\.all\(\)\[(?<index>\w+)\]\..*/,
};
for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
let replacementBase = '';
if (name === 'item') replacementBase = `${prefix}input.item`;
if (name === 'first') replacementBase = `${prefix}input.first()`;
if (name === 'last') replacementBase = `${prefix}input.last()`;
if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
const { index } = match.groups;
replacementBase = `${prefix}input.all()[${index}]`;
}
const options: Completion[] = [ const options: Completion[] = [
{ {
label: `${matcher}.json`, label: `${replacementBase}.json`,
info: this.$locale.baseText('codeNodeEditor.completer.json'), info: i18n.baseText('codeNodeEditor.completer.json'),
}, },
{ {
label: `${matcher}.binary`, label: `${replacementBase}.binary`,
info: this.$locale.baseText('codeNodeEditor.completer.binary'), info: i18n.baseText('codeNodeEditor.completer.binary'),
}, },
]; ];
@@ -40,130 +96,80 @@ export const itemFieldCompletions = defineComponent({
from: preCursor.from, from: preCursor.from,
options: options.map(addVarType), options: options.map(addVarType),
}; };
}, }
/** return null;
* - Complete `$input.first().` to `.json .binary`. };
* - Complete `$input.last().` to `.json .binary`.
* - Complete `$input.all()[index].` to `.json .binary`.
* - Complete `$input.item.` to `.json .binary`.
*/
inputMethodCompletions(context: CompletionContext): CompletionResult | null {
const prefix = this.language === 'python' ? '_' : '$';
const patterns = {
first: new RegExp(`\\${prefix}input\\.first\\(\\)\\..*`),
last: new RegExp(`\\${prefix}input\\.last\\(\\)\\..*`),
item: new RegExp(`\\${prefix}item\\.first\\(\\)\\..*`),
all: /\$input\.all\(\)\[(?<index>\w+)\]\..*/,
};
for (const [name, regex] of Object.entries(patterns)) { /**
const preCursor = context.matchBefore(regex); * - Complete `$('nodeName').first().` to `.json .binary`.
* - Complete `$('nodeName').last().` to `.json .binary`.
* - Complete `$('nodeName').all()[index].` to `.json .binary`.
* - Complete `$('nodeName').item.` to `.json .binary`.
*/
const selectorMethodCompletions = (
context: CompletionContext,
matcher: string | null = null,
): CompletionResult | null => {
const patterns = {
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\..*/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\..*/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\..*/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\..*/,
};
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue; for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
let replacementBase = ''; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
if (name === 'item') replacementBase = `${prefix}input.item`; const match = preCursor.text.match(regex);
if (name === 'first') replacementBase = `${prefix}input.first()`; let start = '';
if (name === 'last') replacementBase = `${prefix}input.last()`; if (!matcher && match?.groups?.quotedNodeName) {
start = `$(${match.groups.quotedNodeName})`;
if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
const { index } = match.groups;
replacementBase = `${prefix}input.all()[${index}]`;
}
const options: Completion[] = [
{
label: `${replacementBase}.json`,
info: this.$locale.baseText('codeNodeEditor.completer.json'),
},
{
label: `${replacementBase}.binary`,
info: this.$locale.baseText('codeNodeEditor.completer.binary'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
} }
return null; let replacementBase = '';
},
/** if (name === 'item') replacementBase = `${start}.item`;
* - Complete `$('nodeName').first().` to `.json .binary`.
* - Complete `$('nodeName').last().` to `.json .binary`.
* - Complete `$('nodeName').all()[index].` to `.json .binary`.
* - Complete `$('nodeName').item.` to `.json .binary`.
*/
selectorMethodCompletions(
context: CompletionContext,
matcher: string | null = null,
): CompletionResult | null {
const patterns = {
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\..*/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\..*/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\..*/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\..*/,
};
for (const [name, regex] of Object.entries(patterns)) { if (name === 'first') replacementBase = `${start}.first()`;
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue; if (name === 'last') replacementBase = `${start}.last()`;
if (name === 'all') {
const match = preCursor.text.match(regex); const match = preCursor.text.match(regex);
let start = ''; if (!match?.groups?.index) continue;
if (!matcher && match?.groups?.quotedNodeName) { replacementBase = `${start}.all()[${match.groups.index}]`;
start = `$(${match.groups.quotedNodeName})`;
}
let replacementBase = '';
if (name === 'item') replacementBase = `${start}.item`;
if (name === 'first') replacementBase = `${start}.first()`;
if (name === 'last') replacementBase = `${start}.last()`;
if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
replacementBase = `${start}.all()[${match.groups.index}]`;
}
const options: Completion[] = [
{
label: `${replacementBase}.json`,
info: this.$locale.baseText('codeNodeEditor.completer.json'),
},
{
label: `${replacementBase}.binary`,
info: this.$locale.baseText('codeNodeEditor.completer.binary'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
} }
return null; const options: Completion[] = [
}, {
}, label: `${replacementBase}.json`,
}); info: i18n.baseText('codeNodeEditor.completer.json'),
},
{
label: `${replacementBase}.binary`,
info: i18n.baseText('codeNodeEditor.completer.binary'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
}
return null;
};
return {
matcherItemFieldCompletions,
inputMethodCompletions,
selectorMethodCompletions,
};
}

View File

@@ -1,136 +1,143 @@
import { escape } from '../utils'; import { escape } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { defineComponent } from 'vue'; import { useI18n } from '@/composables/useI18n';
export const itemIndexCompletions = defineComponent({ export function useItemIndexCompletions(mode: 'runOnceForEachItem' | 'runOnceForAllItems') {
methods: { const i18n = useI18n();
/** /**
* - Complete `$input.` to `.first() .last() .all() .itemMatching()` in all-items mode. * - Complete `$input.` to `.first() .last() .all() .itemMatching()` in all-items mode.
* - Complete `$input.` to `.item` in single-item mode. * - Complete `$input.` to `.item` in single-item mode.
*/ */
inputCompletions(context: CompletionContext, matcher = '$input'): CompletionResult | null { const inputCompletions = (
const pattern = new RegExp(`${escape(matcher)}\..*`); context: CompletionContext,
matcher = '$input',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const options: Completion[] = []; const options: Completion[] = [];
if (this.mode === 'runOnceForAllItems') { if (mode === 'runOnceForAllItems') {
options.push( options.push(
{
label: `${matcher}.first()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.first'),
},
{
label: `${matcher}.last()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.last'),
},
{
label: `${matcher}.all()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.all'),
},
{
label: `${matcher}.itemMatching()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.itemMatching'),
},
);
}
if (this.mode === 'runOnceForEachItem') {
options.push({
label: `${matcher}.item`,
type: 'variable',
info: this.$locale.baseText('codeNodeEditor.completer.$input.item'),
});
}
return {
from: preCursor.from,
options,
};
},
/**
* - Complete `$('nodeName').` to `.params .context` in both modes.
* - Complete `$('nodeName').` to `.first() .last() .all() .itemMatching()` in all-items mode.
* - Complete `$('nodeName').` to `.item` in single-item mode.
*/
selectorCompletions(context: CompletionContext, matcher: string | null = null) {
const pattern =
matcher === null
? /\$\((?<quotedNodeName>['"][\S\s]+['"])\)\..*/ // $('nodeName').
: new RegExp(`${matcher}\..*`);
const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const match = preCursor.text.match(pattern);
let replacementBase = '';
if (matcher === null && match?.groups?.quotedNodeName) {
replacementBase = `$(${match.groups.quotedNodeName})`;
} else if (matcher) {
replacementBase = matcher;
}
const options: Completion[] = [
{ {
label: `${replacementBase}.params`, label: `${matcher}.first()`,
type: 'variable', type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.selector.params'), info: i18n.baseText('codeNodeEditor.completer.$input.first'),
}, },
{ {
label: `${replacementBase}.context`, label: `${matcher}.last()`,
type: 'variable', type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.selector.context'), info: i18n.baseText('codeNodeEditor.completer.$input.last'),
}, },
]; {
label: `${matcher}.all()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.$input.all'),
},
{
label: `${matcher}.itemMatching()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.$input.itemMatching'),
},
);
}
if (this.mode === 'runOnceForAllItems') { if (mode === 'runOnceForEachItem') {
options.push( options.push({
{ label: `${matcher}.item`,
label: `${replacementBase}.first()`, type: 'variable',
type: 'function', info: i18n.baseText('codeNodeEditor.completer.$input.item'),
info: this.$locale.baseText('codeNodeEditor.completer.$input.first'), });
}, }
{
label: `${replacementBase}.last()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.last'),
},
{
label: `${replacementBase}.all()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.$input.all'),
},
{
label: `${replacementBase}.itemMatching()`,
type: 'function',
info: this.$locale.baseText('codeNodeEditor.completer.selector.itemMatching'),
},
);
}
if (this.mode === 'runOnceForEachItem') { return {
options.push({ from: preCursor.from,
label: `${replacementBase}.item`, options,
type: 'variable', };
info: this.$locale.baseText('codeNodeEditor.completer.selector.item'), };
});
}
return { /**
from: preCursor.from, * - Complete `$('nodeName').` to `.params .context` in both modes.
options, * - Complete `$('nodeName').` to `.first() .last() .all() .itemMatching()` in all-items mode.
}; * - Complete `$('nodeName').` to `.item` in single-item mode.
}, */
}, const selectorCompletions = (context: CompletionContext, matcher: string | null = null) => {
}); const pattern =
matcher === null
? /\$\((?<quotedNodeName>['"][\S\s]+['"])\)\..*/ // $('nodeName').
: new RegExp(`${matcher}\..*`);
const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const match = preCursor.text.match(pattern);
let replacementBase = '';
if (matcher === null && match?.groups?.quotedNodeName) {
replacementBase = `$(${match.groups.quotedNodeName})`;
} else if (matcher) {
replacementBase = matcher;
}
const options: Completion[] = [
{
label: `${replacementBase}.params`,
type: 'variable',
info: i18n.baseText('codeNodeEditor.completer.selector.params'),
},
{
label: `${replacementBase}.context`,
type: 'variable',
info: i18n.baseText('codeNodeEditor.completer.selector.context'),
},
];
if (mode === 'runOnceForAllItems') {
options.push(
{
label: `${replacementBase}.first()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.$input.first'),
},
{
label: `${replacementBase}.last()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.$input.last'),
},
{
label: `${replacementBase}.all()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.$input.all'),
},
{
label: `${replacementBase}.itemMatching()`,
type: 'function',
info: i18n.baseText('codeNodeEditor.completer.selector.itemMatching'),
},
);
}
if (mode === 'runOnceForEachItem') {
options.push({
label: `${replacementBase}.item`,
type: 'variable',
info: i18n.baseText('codeNodeEditor.completer.selector.item'),
});
}
return {
from: preCursor.from,
options,
};
};
return {
inputCompletions,
selectorCompletions,
};
}

View File

@@ -1,325 +1,301 @@
import { defineComponent } from 'vue'; import { escape } from '../utils';
import { escape, toVariableOption } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import type { IDataObject, IPinData, IRunData } from 'n8n-workflow';
import { mapStores } from 'pinia';
import { useWorkflowsStore } from '@/stores/workflows.store'; import { useWorkflowsStore } from '@/stores/workflows.store';
import { useNDVStore } from '@/stores/ndv.store'; import { useNDVStore } from '@/stores/ndv.store';
import { isAllowedInDotNotation } from '@/plugins/codemirror/completions/utils'; import { isAllowedInDotNotation } from '@/plugins/codemirror/completions/utils';
import { useI18n } from '@/composables/useI18n';
import type { IPinData, IRunData, IDataObject } from 'n8n-workflow';
export const jsonFieldCompletions = defineComponent({ function useJsonFieldCompletions() {
computed: { const i18n = useI18n();
...mapStores(useNDVStore, useWorkflowsStore), const ndvStore = useNDVStore();
}, const workflowsStore = useWorkflowsStore();
methods: {
/**
* - Complete `x.first().json.` to `.field`.
* - Complete `x.last().json.` to `.field`.
* - Complete `x.all()[index].json.` to `.field`.
* - Complete `x.item.json.` to `.field`.
*
* - Complete `x.first().json[` to `['field']`.
* - Complete `x.last().json[` to `['field']`.
* - Complete `x.all()[index].json[` to `['field']`.
* - Complete `x.item.json[` to `['field']`.
*/
matcherJsonFieldCompletions(
context: CompletionContext,
matcher: string,
variablesToValues: Record<string, string>,
): CompletionResult | null {
const pattern = new RegExp(`(${escape(matcher)})\..*`);
const preCursor = context.matchBefore(pattern); /**
* - Complete `x.first().json.` to `.field`.
* - Complete `x.last().json.` to `.field`.
* - Complete `x.all()[index].json.` to `.field`.
* - Complete `x.item.json.` to `.field`.
*
* - Complete `x.first().json[` to `['field']`.
* - Complete `x.last().json[` to `['field']`.
* - Complete `x.all()[index].json[` to `['field']`.
* - Complete `x.item.json[` to `['field']`.
*/
const matcherJsonFieldCompletions = (
context: CompletionContext,
matcher: string,
variablesToValues: Record<string, string>,
): CompletionResult | null => {
const pattern = new RegExp(`(${escape(matcher)})\..*`);
const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const inputNodeName = this.getInputNodeName(); const inputNodeName = getInputNodeName();
if (!inputNodeName) return null;
if (!inputNodeName) return null; const [varName] = preCursor.text.split('.');
const originalValue = variablesToValues[varName];
if (!originalValue) return null;
const [varName] = preCursor.text.split('.'); for (const accessor of ['first', 'last', 'item']) {
if (originalValue.includes(accessor) || preCursor.text.includes(accessor)) {
const jsonOutput = getJsonOutput(inputNodeName, { accessor });
if (!jsonOutput) return null;
return toJsonFieldCompletions(preCursor, jsonOutput, matcher);
}
}
const originalValue = variablesToValues[varName]; if (originalValue.includes('all')) {
const match = originalValue.match(/\$(input|\(.*\))\.all\(\)\[(?<index>.+)\]$/);
if (!match?.groups?.index) return null;
if (!originalValue) return null; const { index } = match.groups;
const jsonOutput = getJsonOutput(inputNodeName, { index: Number(index) });
if (!jsonOutput) return null;
for (const accessor of ['first', 'last', 'item']) { return toJsonFieldCompletions(preCursor, jsonOutput, matcher);
/** }
* const x = $input.first(); // accessor in original value
* x.json
*
* const x = $input;
* x.first().json // accessor in preCursor.text
*/
if (originalValue.includes(accessor) || preCursor.text.includes(accessor)) {
const jsonOutput = this.getJsonOutput(inputNodeName, { accessor });
if (!jsonOutput) return null; return null;
};
return this.toJsonFieldCompletions(preCursor, jsonOutput, matcher); /**
} * - Complete `$input.first().json.` to `.field`.
* - Complete `$input.last().json.` to `.field`.
* - Complete `$input.all()[index].json.` to `.field`.
* - Complete `$input.item.json.` to `.field`.
*
* - Complete `$input.first().json[` to `['field']`.
* - Complete `$input.last().json[` to `['field']`.
* - Complete `$input.all()[index].json[` to `['field']`.
* - Complete `$input.item.json[` to `['field']`.
*/
const inputJsonFieldCompletions = (context: CompletionContext): CompletionResult | null => {
console.log('🚀 ~ inputJsonFieldCompletions ~ context:', context);
const patterns = {
first: /\$input\.first\(\)\.json(\[|\.).*/,
last: /\$input\.last\(\)\.json(\[|\.).*/,
item: /\$input\.item\.json(\[|\.).*/,
all: /\$input\.all\(\)\[(?<index>\w+)\]\.json(\[|\.).*/,
};
for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
const inputNodeName = getInputNodeName();
if (!inputNodeName) continue;
if (name === 'first' || name === 'last') {
const jsonOutput = getJsonOutput(inputNodeName, { accessor: name });
if (!jsonOutput) continue;
return toJsonFieldCompletions(preCursor, jsonOutput, `$input.${name}().json`);
} }
if (originalValue.includes('all')) { if (name === 'item') {
const match = originalValue.match(/\$(input|\(.*\))\.all\(\)\[(?<index>.+)\]$/); const jsonOutput = getJsonOutput(inputNodeName, { accessor: 'item' });
if (!jsonOutput) continue;
return toJsonFieldCompletions(preCursor, jsonOutput, '$input.item.json');
}
if (!match?.groups?.index) return null; if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
const { index } = match.groups; const { index } = match.groups;
const jsonOutput = getJsonOutput(inputNodeName, { index: Number(index) });
if (!jsonOutput) continue;
const jsonOutput = this.getJsonOutput(inputNodeName, { index: Number(index) }); return toJsonFieldCompletions(preCursor, jsonOutput, `$input.all()[${index}].json`);
}
}
if (!jsonOutput) return null; return null;
};
return this.toJsonFieldCompletions(preCursor, jsonOutput, matcher); /**
* Complete `$('nodeName').first().json.` to `.field`.
* Complete `$('nodeName').last().json.` to `.field`.
* Complete `$('nodeName').all()[index].json.` to `.field`.
* Complete `$('nodeName').item.json.` to `.field`.
*
* Complete `$('nodeName').first().json[` to `['field']`.
* Complete `$('nodeName').last().json[` to `['field']`.
* Complete `$('nodeName').all()[index].json[` to `['field']`.
* Complete `$('nodeName').item.json[` to `['field']`.
*/
const selectorJsonFieldCompletions = (context: CompletionContext): CompletionResult | null => {
const patterns = {
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\.json(\[|\.).*/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\.json(\[|\.).*/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\.json(\[|\.).*/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json(\[|\.).*/,
};
for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
const match = preCursor.text.match(regex);
if (!match?.groups?.quotedNodeName) continue;
const { quotedNodeName } = match.groups;
const selector = `$(${match.groups.quotedNodeName})`;
if (name === 'first' || name === 'last') {
const jsonOutput = getJsonOutput(quotedNodeName, { accessor: name });
if (!jsonOutput) continue;
return toJsonFieldCompletions(preCursor, jsonOutput, `${selector}.${name}().json`);
} }
if (name === 'item') {
const jsonOutput = getJsonOutput(quotedNodeName, { accessor: 'item' });
if (!jsonOutput) continue;
return toJsonFieldCompletions(preCursor, jsonOutput, `${selector}.item.json`);
}
if (name === 'all') {
const regexMatch = preCursor.text.match(regex);
console.log('🚀 ~ selectorJsonFieldCompletions ~ regexMatch:', regexMatch);
if (!regexMatch?.groups?.index) continue;
const { index } = regexMatch.groups;
const jsonOutput = getJsonOutput(quotedNodeName, { index: Number(index) });
if (!jsonOutput) continue;
return toJsonFieldCompletions(preCursor, jsonOutput, `${selector}.all()[${index}].json`);
}
}
return null;
};
const getInputNodeName = (): string | null => {
try {
const activeNode = ndvStore.activeNode;
if (activeNode) {
const workflow = workflowsStore.getCurrentWorkflow();
const input = workflow.connectionsByDestinationNode[activeNode.name];
return input.main[0][0].node;
}
} catch (e) {
console.error(e);
return null; return null;
}, }
return null;
};
/** /**
* - Complete `$input.first().json.` to `.field`. * .json -> .json['field']
* - Complete `$input.last().json.` to `.field`. * .json -> .json.field
* - Complete `$input.all()[index].json.` to `.field`. */
* - Complete `$input.item.json.` to `.field`. const toJsonFieldCompletions = (
* preCursor: NonNullable<ReturnType<CompletionContext['matchBefore']>>,
* - Complete `$input.first().json[` to `['field']`. jsonOutput: IDataObject,
* - Complete `$input.last().json[` to `['field']`. matcher: string,
* - Complete `$input.all()[index].json[` to `['field']`. ): CompletionResult | null => {
* - Complete `$input.item.json[` to `['field']`. if (
*/ /\.json\[/.test(preCursor.text) ||
inputJsonFieldCompletions(context: CompletionContext): CompletionResult | null { new RegExp(`(${escape(matcher)})\\[`).test(preCursor.text)
const patterns = {
first: /\$input\.first\(\)\.json(\[|\.).*/,
last: /\$input\.last\(\)\.json(\[|\.).*/,
item: /\$input\.item\.json(\[|\.).*/,
all: /\$input\.all\(\)\[(?<index>\w+)\]\.json(\[|\.).*/,
};
for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
const inputNodeName = this.getInputNodeName();
if (!inputNodeName) continue;
if (name === 'first' || name === 'last') {
const jsonOutput = this.getJsonOutput(inputNodeName, { accessor: name });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(preCursor, jsonOutput, `$input.${name}().json`);
}
if (name === 'item') {
const jsonOutput = this.getJsonOutput(inputNodeName, { accessor: 'item' });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(preCursor, jsonOutput, '$input.item.json');
}
if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
const { index } = match.groups;
const jsonOutput = this.getJsonOutput(inputNodeName, { index: Number(index) });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(preCursor, jsonOutput, `$input.all()[${index}].json`);
}
}
return null;
},
/**
* Complete `$('nodeName').first().json.` to `.field`.
* Complete `$('nodeName').last().json.` to `.field`.
* Complete `$('nodeName').all()[index].json.` to `.field`.
* Complete `$('nodeName').item.json.` to `.field`.
*
* Complete `$('nodeName').first().json[` to `['field']`.
* Complete `$('nodeName').last().json[` to `['field']`.
* Complete `$('nodeName').all()[index].json[` to `['field']`.
* Complete `$('nodeName').item.json[` to `['field']`.
*/
selectorJsonFieldCompletions(context: CompletionContext): CompletionResult | null {
const patterns = {
first: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.first\(\)\.json(\[|\.).*/,
last: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.last\(\)\.json(\[|\.).*/,
item: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.item\.json(\[|\.).*/,
all: /\$\((?<quotedNodeName>['"][\w\s]+['"])\)\.all\(\)\[(?<index>\w+)\]\.json(\[|\.).*/,
};
for (const [name, regex] of Object.entries(patterns)) {
const preCursor = context.matchBefore(regex);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) continue;
const match = preCursor.text.match(regex);
if (!match?.groups?.quotedNodeName) continue;
const { quotedNodeName } = match.groups;
const selector = `$(${match.groups.quotedNodeName})`;
if (name === 'first' || name === 'last') {
const jsonOutput = this.getJsonOutput(quotedNodeName, { accessor: name });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(preCursor, jsonOutput, `${selector}.${name}().json`);
}
if (name === 'item') {
const jsonOutput = this.getJsonOutput(quotedNodeName, { accessor: 'item' });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(preCursor, jsonOutput, `${selector}.item.json`);
}
if (name === 'all') {
const match = preCursor.text.match(regex);
if (!match?.groups?.index) continue;
const { index } = match.groups;
const jsonOutput = this.getJsonOutput(quotedNodeName, { index: Number(index) });
if (!jsonOutput) continue;
return this.toJsonFieldCompletions(
preCursor,
jsonOutput,
`${selector}.all()[${index}].json`,
);
}
}
return null;
},
getInputNodeName() {
try {
const activeNode = this.ndvStore.activeNode;
if (activeNode) {
const workflow = this.getCurrentWorkflow();
const input = workflow.connectionsByDestinationNode[activeNode.name];
return input.main[0][0].node;
}
} catch {
return null;
}
},
/**
* .json -> .json['field']
* .json -> .json.field
*/
toJsonFieldCompletions(
preCursor: NonNullable<ReturnType<CompletionContext['matchBefore']>>,
jsonOutput: IDataObject,
matcher: string, // e.g. `$input.first().json` or `x` (user-defined variable)
) { ) {
if ( const options: Completion[] = Object.keys(jsonOutput)
/\.json\[/.test(preCursor.text) || .map((field) => `${matcher}['${field}']`)
new RegExp(`(${escape(matcher)})\\[`).test(preCursor.text) .map((label) => ({
) { label,
const options: Completion[] = Object.keys(jsonOutput) info: i18n.baseText('codeNodeEditor.completer.json'),
.map((field) => `${matcher}['${field}']`) }));
.map((label) => ({
label,
info: this.$locale.baseText('codeNodeEditor.completer.json'),
}));
return { return {
from: preCursor.from, from: preCursor.from,
options, options,
}; };
} }
if ( if (
/\.json\./.test(preCursor.text) || /\.json\./.test(preCursor.text) ||
new RegExp(`(${escape(matcher)})\.`).test(preCursor.text) new RegExp(`(${escape(matcher)})\.`).test(preCursor.text)
) { ) {
const options: Completion[] = Object.keys(jsonOutput) const options: Completion[] = Object.keys(jsonOutput)
.filter(isAllowedInDotNotation) .filter(isAllowedInDotNotation)
.map((field) => `${matcher}.${field}`) .map((field) => `${matcher}.${field}`)
.map(toVariableOption); .map((label) => ({
label,
info: i18n.baseText('codeNodeEditor.completer.json'),
}));
return { return {
from: preCursor.from, from: preCursor.from,
options, options,
}; };
} }
return null; return null;
}, };
/** /**
* Get the `json` output of a node from `runData` or `pinData`. * Get the `json` output of a node from `runData` or `pinData`.
* *
* `accessor` is the method or property used to find the item index. * `accessor` is the method or property used to find the item index.
* `index` is only passed for `all()`. * `index` is only passed for `all()`.
*/ */
getJsonOutput(quotedNodeName: string, options?: { accessor?: string; index?: number }) { const getJsonOutput = (
let nodeName = quotedNodeName; quotedNodeName: string,
options?: { accessor?: string; index?: number },
) => {
let nodeName = quotedNodeName;
const isSingleQuoteWrapped = quotedNodeName.startsWith("'") && quotedNodeName.endsWith("'"); const isSingleQuoteWrapped = quotedNodeName.startsWith("'") && quotedNodeName.endsWith("'");
const isDoubleQuoteWrapped = quotedNodeName.startsWith('"') && quotedNodeName.endsWith('"'); const isDoubleQuoteWrapped = quotedNodeName.startsWith('"') && quotedNodeName.endsWith('"');
if (isSingleQuoteWrapped) { if (isSingleQuoteWrapped) {
nodeName = quotedNodeName.replace(/^'/, '').replace(/'$/, ''); nodeName = quotedNodeName.replace(/^'/, '').replace(/'$/, '');
} else if (isDoubleQuoteWrapped) { } else if (isDoubleQuoteWrapped) {
nodeName = quotedNodeName.replace(/^"/, '').replace(/"$/, ''); nodeName = quotedNodeName.replace(/^"/, '').replace(/"$/, '');
} }
const pinData: IPinData | undefined = this.workflowsStore.pinnedWorkflowData; const pinData: IPinData | undefined = useWorkflowsStore().pinnedWorkflowData;
const nodePinData = pinData?.[nodeName]; const nodePinData = pinData?.[nodeName];
if (nodePinData) {
try {
let itemIndex = options?.index ?? 0;
if (options?.accessor === 'last') {
itemIndex = nodePinData.length - 1;
}
return nodePinData[itemIndex].json;
} catch {}
}
const runData: IRunData | null = this.workflowsStore.getWorkflowRunData;
const nodeRunData = runData && runData[nodeName];
if (!nodeRunData) return null;
if (nodePinData) {
try { try {
let itemIndex = options?.index ?? 0; let itemIndex = options?.index ?? 0;
if (options?.accessor === 'last') { if (options?.accessor === 'last') {
const inputItems = nodeRunData[0].data!.main[0]!; itemIndex = nodePinData.length - 1;
itemIndex = inputItems.length - 1;
} }
return nodeRunData[0].data!.main[0]![itemIndex].json; return nodePinData[itemIndex].json;
} catch { } catch {}
return null; }
const runData: IRunData | null = useWorkflowsStore().getWorkflowRunData;
const nodeRunData = runData?.[nodeName];
if (!nodeRunData) return null;
try {
let itemIndex = options?.index ?? 0;
if (options?.accessor === 'last') {
const inputItems = nodeRunData[0].data?.main[0] ?? [];
itemIndex = inputItems.length - 1;
} }
},
}, return nodeRunData[0].data?.main[0]?.[itemIndex].json;
}); } catch {
return null;
}
};
return {
matcherJsonFieldCompletions,
inputJsonFieldCompletions,
selectorJsonFieldCompletions,
};
}
export { useJsonFieldCompletions };

View File

@@ -1,88 +1,101 @@
import { escape } from '../utils'; import { escape } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { defineComponent } from 'vue';
import { createInfoBoxRenderer } from '@/plugins/codemirror/completions/infoBoxRenderer'; import { createInfoBoxRenderer } from '@/plugins/codemirror/completions/infoBoxRenderer';
import { luxonStaticDocs } from '@/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.static.docs'; import { luxonStaticDocs } from '@/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.static.docs';
import { luxonInstanceDocs } from '@/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.instance.docs'; import { luxonInstanceDocs } from '@/plugins/codemirror/completions/nativesAutocompleteDocs/luxon.instance.docs';
export const luxonCompletions = defineComponent({ export function useLuxonCompletions() {
methods: { /**
/** * Complete `$today.` with luxon `DateTime` instance methods.
* Complete `$today.` with luxon `DateTime` instance methods. */
*/ const todayCompletions = (
todayCompletions(context: CompletionContext, matcher = '$today'): CompletionResult | null { context: CompletionContext,
const pattern = new RegExp(`${escape(matcher)}\..*`); matcher = '$today',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
return { return {
from: preCursor.from, from: preCursor.from,
options: this.instanceCompletions(matcher), options: instanceCompletions(matcher),
}; };
}, };
/** /**
* Complete `$now.` with luxon `DateTime` instance methods. * Complete `$now.` with luxon `DateTime` instance methods.
*/ */
nowCompletions(context: CompletionContext, matcher = '$now'): CompletionResult | null { const nowCompletions = (
const pattern = new RegExp(`${escape(matcher)}\..*`); context: CompletionContext,
matcher = '$now',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
return { return {
from: preCursor.from, from: preCursor.from,
options: this.instanceCompletions(matcher), options: instanceCompletions(matcher),
}; };
}, };
/** /**
* Complete `DateTime` with luxon `DateTime` static methods. * Complete `DateTime` with luxon `DateTime` static methods.
*/ */
dateTimeCompletions(context: CompletionContext, matcher = 'DateTime'): CompletionResult | null { const dateTimeCompletions = (
const pattern = new RegExp(`${escape(matcher)}\..*`); context: CompletionContext,
matcher = 'DateTime',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const options: Completion[] = Object.entries(luxonStaticDocs.functions) const options: Completion[] = Object.entries(luxonStaticDocs.functions)
.filter(([_, { doc }]) => doc && !doc.hidden) .filter(([_, { doc }]) => doc && !doc.hidden)
.map(([method, { doc }]) => { .map(([method, { doc }]) => {
return { return {
label: `DateTime.${method}()`, label: `DateTime.${method}()`,
type: 'function', type: 'function',
info: createInfoBoxRenderer(doc, true), info: createInfoBoxRenderer(doc, true),
}; };
}); });
return { return {
from: preCursor.from, from: preCursor.from,
options, options,
}; };
}, };
instanceCompletions(matcher: string): Completion[] {
return Object.entries(luxonInstanceDocs.properties) const instanceCompletions = (matcher: string): Completion[] => {
.filter(([_, { doc }]) => doc && !doc.hidden) return Object.entries(luxonInstanceDocs.properties)
.map(([getter, { doc }]) => { .filter(([_, { doc }]) => doc && !doc.hidden)
return { .map(([getter, { doc }]) => {
label: `${matcher}.${getter}`, return {
info: createInfoBoxRenderer(doc), label: `${matcher}.${getter}`,
}; info: createInfoBoxRenderer(doc),
}) };
.concat( })
Object.entries(luxonInstanceDocs.functions) .concat(
.filter(([_, { doc }]) => doc && !doc.hidden) Object.entries(luxonInstanceDocs.functions)
.map(([method, { doc }]) => { .filter(([_, { doc }]) => doc && !doc.hidden)
return { .map(([method, { doc }]) => {
label: `${matcher}.${method}()`, return {
info: createInfoBoxRenderer(doc, true), label: `${matcher}.${method}()`,
}; info: createInfoBoxRenderer(doc, true),
}), };
); }),
}, );
}, };
});
return {
todayCompletions,
nowCompletions,
dateTimeCompletions,
};
}

View File

@@ -1,45 +1,44 @@
import { addVarType } from '../utils'; import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { defineComponent } from 'vue'; import { useI18n } from '@/composables/useI18n';
const DEFAULT_MATCHER = '$prevNode'; const DEFAULT_MATCHER = '$prevNode';
const escape = (str: string) => str.replace('$', '\\$'); const escape = (str: string) => str.replace('$', '\\$');
export const prevNodeCompletions = defineComponent({ export function usePrevNodeCompletions(matcher = DEFAULT_MATCHER) {
methods: { const i18n = useI18n();
/**
* Complete `$prevNode.` to `.name .outputIndex .runIndex`.
*/
prevNodeCompletions(
context: CompletionContext,
matcher = DEFAULT_MATCHER,
): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); /**
* Complete `$prevNode.` to `.name .outputIndex .runIndex`.
*/
const prevNodeCompletions = (context: CompletionContext): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const preCursor = context.matchBefore(pattern);
const options: Completion[] = [ if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
{
label: `${matcher}.name`,
info: this.$locale.baseText('codeNodeEditor.completer.$prevNode.name'),
},
{
label: `${matcher}.outputIndex`,
info: this.$locale.baseText('codeNodeEditor.completer.$prevNode.outputIndex'),
},
{
label: `${matcher}.runIndex`,
info: this.$locale.baseText('codeNodeEditor.completer.$prevNode.runIndex'),
},
];
return { const options: Completion[] = [
from: preCursor.from, {
options: options.map(addVarType), label: `${matcher}.name`,
}; info: i18n.baseText('codeNodeEditor.completer.$prevNode.name'),
}, },
}, {
}); label: `${matcher}.outputIndex`,
info: i18n.baseText('codeNodeEditor.completer.$prevNode.outputIndex'),
},
{
label: `${matcher}.runIndex`,
info: i18n.baseText('codeNodeEditor.completer.$prevNode.runIndex'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
};
return { prevNodeCompletions };
}

View File

@@ -1,45 +1,44 @@
import { defineComponent } from 'vue';
import { AUTOCOMPLETABLE_BUILT_IN_MODULES_JS } from '../constants'; import { AUTOCOMPLETABLE_BUILT_IN_MODULES_JS } from '../constants';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useSettingsStore } from '@/stores/settings.store'; import { useSettingsStore } from '@/stores/settings.store';
export const requireCompletions = defineComponent({ export function useRequireCompletions() {
methods: { const settingsStore = useSettingsStore();
/** const allowedModules = settingsStore.allowedModules;
* Complete `req` to `require('moduleName')` based on modules available in context.
*/
requireCompletions(context: CompletionContext): CompletionResult | null {
const preCursor = context.matchBefore(/req.*/);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const toOption = (moduleName: string): Completion => ({
label: `require('${moduleName}');`,
type: 'variable',
});
/**
* Complete `req` to `require('moduleName')` based on modules available in context.
*/
const requireCompletions = (context: CompletionContext): CompletionResult | null => {
const preCursor = context.matchBefore(/req.*/);
const options: Completion[] = []; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const settingsStore = useSettingsStore();
const allowedModules = settingsStore.allowedModules;
const toOption = (moduleName: string) => ({ const options: Completion[] = [];
label: `require('${moduleName}');`,
type: 'variable',
});
if (allowedModules.builtIn) { if (allowedModules.builtIn) {
if (allowedModules.builtIn.includes('*')) { if (allowedModules.builtIn.includes('*')) {
options.push(...AUTOCOMPLETABLE_BUILT_IN_MODULES_JS.map(toOption)); options.push(...AUTOCOMPLETABLE_BUILT_IN_MODULES_JS.map(toOption));
} else if (allowedModules?.builtIn?.length > 0) { } else if (allowedModules?.builtIn?.length > 0) {
options.push(...allowedModules.builtIn.map(toOption)); options.push(...allowedModules.builtIn.map(toOption));
}
} }
}
if (allowedModules.external) { if (allowedModules.external) {
if (allowedModules?.external?.length > 0) { if (allowedModules?.external?.length > 0) {
options.push(...allowedModules.external.map(toOption)); options.push(...allowedModules.external.map(toOption));
}
} }
}
return { return {
from: preCursor.from, from: preCursor.from,
options, options,
}; };
}, };
},
}); return { requireCompletions };
}

View File

@@ -1,53 +1,58 @@
import { addVarType } from '../utils'; import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useExternalSecretsStore } from '@/stores/externalSecrets.ee.store'; import { useExternalSecretsStore } from '@/stores/externalSecrets.ee.store';
import { defineComponent } from 'vue';
const escape = (str: string) => str.replace('$', '\\$'); const escape = (str: string) => str.replace('$', '\\$');
export const secretsCompletions = defineComponent({ export function useSecretsCompletions() {
methods: { const externalSecretsStore = useExternalSecretsStore();
/**
* Complete `$secrets.` to `$secrets.providerName` and `$secrets.providerName.secretName`.
*/
secretsCompletions(context: CompletionContext, matcher = '$secrets'): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; /**
* Complete `$secrets.` to `$secrets.providerName` and `$secrets.providerName.secretName`.
*/
const secretsCompletions = (
context: CompletionContext,
matcher = '$secrets',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern);
const provider = preCursor.text.split('.')[1]; if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const externalSecretsStore = useExternalSecretsStore();
let options: Completion[];
const optionsForObject = (leftSide: string, object: object): Completion[] => { const provider = preCursor.text.split('.')[1];
return Object.entries(object).flatMap(([key, value]) => { let options: Completion[];
if (typeof value === 'object' && value !== null) {
return optionsForObject(`${leftSide}.${key}`, value);
}
return {
label: `${leftSide}.${key}`,
info: '*******',
};
});
};
if (provider) { const optionsForObject = (leftSide: string, object: Record<string, unknown>): Completion[] => {
options = optionsForObject( return Object.entries(object).flatMap(([key, value]) => {
`${matcher}.${provider}`, if (typeof value === 'object' && value !== null) {
externalSecretsStore.secretsAsObject[provider], return optionsForObject(`${leftSide}.${key}`, value as Record<string, unknown>);
); }
} else { return {
options = Object.keys(externalSecretsStore.secretsAsObject).map((provider) => ({ label: `${leftSide}.${key}`,
label: `${matcher}.${provider}`, info: '*******',
info: JSON.stringify(externalSecretsStore.secretsAsObject[provider]), };
})); });
} };
return { if (provider) {
from: preCursor.from, options = optionsForObject(
options: options.map(addVarType), `${matcher}.${provider}`,
}; externalSecretsStore.secretsAsObject[provider] as Record<string, unknown>,
}, );
}, } else {
}); options = Object.keys(externalSecretsStore.secretsAsObject).map((providerB) => ({
label: `${matcher}.${providerB}`,
info: JSON.stringify(externalSecretsStore.secretsAsObject[providerB]),
}));
}
return {
from: preCursor.from,
options: options.map(addVarType),
};
};
return {
secretsCompletions,
};
}

View File

@@ -1,32 +1,37 @@
import { addVarType } from '../utils'; import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useEnvironmentsStore } from '@/stores/environments.ee.store'; import { useEnvironmentsStore } from '@/stores/environments.ee.store';
import { defineComponent } from 'vue';
const escape = (str: string) => str.replace('$', '\\$'); const escape = (str: string) => str.replace('$', '\\$');
export const variablesCompletions = defineComponent({ export function useVariablesCompletions() {
methods: { const environmentsStore = useEnvironmentsStore();
/**
* Complete `$vars.` to `$vars.VAR_NAME`.
*/
variablesCompletions(context: CompletionContext, matcher = '$vars'): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); /**
* Complete `$vars.` to `$vars.VAR_NAME`.
*/
const variablesCompletions = (
context: CompletionContext,
matcher = '$vars',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const preCursor = context.matchBefore(pattern);
const environmentsStore = useEnvironmentsStore(); if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
const options: Completion[] = environmentsStore.variables.map((variable) => ({
label: `${matcher}.${variable.key}`,
info: variable.value,
}));
return { const options: Completion[] = environmentsStore.variables.map((variable) => ({
from: preCursor.from, label: `${matcher}.${variable.key}`,
options: options.map(addVarType), info: variable.value,
}; }));
},
}, return {
}); from: preCursor.from,
options: options.map(addVarType),
};
};
return {
variablesCompletions,
};
}

View File

@@ -1,43 +1,45 @@
import { defineComponent } from 'vue';
import { addVarType } from '../utils'; import { addVarType } from '../utils';
import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete'; import type { Completion, CompletionContext, CompletionResult } from '@codemirror/autocomplete';
import { useI18n } from '@/composables/useI18n';
const escape = (str: string) => str.replace('$', '\\$'); const escape = (str: string) => str.replace('$', '\\$');
export const workflowCompletions = defineComponent({ export function useWorkflowCompletions() {
methods: { const i18n = useI18n();
/**
* Complete `$workflow.` to `.id .name .active`.
*/
workflowCompletions(
context: CompletionContext,
matcher = '$workflow',
): CompletionResult | null {
const pattern = new RegExp(`${escape(matcher)}\..*`);
const preCursor = context.matchBefore(pattern); /**
* Complete `$workflow.` to `.id .name .active`.
*/
const workflowCompletions = (
context: CompletionContext,
matcher = '$workflow',
): CompletionResult | null => {
const pattern = new RegExp(`${escape(matcher)}\..*`);
if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null; const preCursor = context.matchBefore(pattern);
const options: Completion[] = [ if (!preCursor || (preCursor.from === preCursor.to && !context.explicit)) return null;
{
label: `${matcher}.id`,
info: this.$locale.baseText('codeNodeEditor.completer.$workflow.id'),
},
{
label: `${matcher}.name`,
info: this.$locale.baseText('codeNodeEditor.completer.$workflow.name'),
},
{
label: `${matcher}.active`,
info: this.$locale.baseText('codeNodeEditor.completer.$workflow.active'),
},
];
return { const options: Completion[] = [
from: preCursor.from, {
options: options.map(addVarType), label: `${matcher}.id`,
}; info: i18n.baseText('codeNodeEditor.completer.$workflow.id'),
}, },
}, {
}); label: `${matcher}.name`,
info: i18n.baseText('codeNodeEditor.completer.$workflow.name'),
},
{
label: `${matcher}.active`,
info: i18n.baseText('codeNodeEditor.completer.$workflow.active'),
},
];
return {
from: preCursor.from,
options: options.map(addVarType),
};
};
return { workflowCompletions };
}

View File

@@ -0,0 +1,130 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { DateTime } from 'luxon';
import * as workflowHelpers from '@/composables/useWorkflowHelpers';
import * as utils from '@/plugins/codemirror/completions/utils';
import {
extensions,
luxonInstanceOptions,
natives,
} from '@/plugins/codemirror/completions/datatype.completions';
import type { CompletionSource, CompletionResult } from '@codemirror/autocomplete';
import { CompletionContext } from '@codemirror/autocomplete';
import { EditorState } from '@codemirror/state';
import { n8nLang } from '@/plugins/codemirror/n8nLang';
import { LUXON_RECOMMENDED_OPTIONS, STRING_RECOMMENDED_OPTIONS } from '../constants';
import { uniqBy } from 'lodash-es';
beforeEach(async () => {
setActivePinia(createTestingPinia());
vi.spyOn(utils, 'receivesNoBinaryData').mockReturnValue(true); // hide $binary
vi.spyOn(utils, 'isSplitInBatchesAbsent').mockReturnValue(false); // show context
vi.spyOn(utils, 'hasActiveNode').mockReturnValue(true);
});
describe('Additional Tests', () => {
describe('Edge Case Completions', () => {
test('should return no completions for empty string: {{ ""| }}', () => {
expect(completions('{{ ""| }}')).toBeNull();
});
test('should return no completions for null value: {{ null.| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(null);
expect(completions('{{ null.| }}')).toBeNull();
});
test('should return no completions for undefined value: {{ undefined.| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(undefined);
expect(completions('{{ undefined.| }}')).toBeNull();
});
test('should return completions for deeply nested object: {{ $json.deep.nested.value.| }}', () => {
const nestedObject = { deep: { nested: { value: 'test' } } };
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(
nestedObject.deep.nested.value,
);
expect(completions('{{ $json.deep.nested.value.| }}')).toHaveLength(
natives({ typeName: 'string' }).length +
extensions({ typeName: 'string' }).length +
STRING_RECOMMENDED_OPTIONS.length,
);
});
});
describe('Special Characters', () => {
test('should handle completions for strings with special characters: {{ "special@char!".| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce('special@char!');
expect(completions('{{ "special@char!".| }}')).toHaveLength(
natives({ typeName: 'string' }).length +
extensions({ typeName: 'string' }).length +
STRING_RECOMMENDED_OPTIONS.length,
);
});
test('should handle completions for strings with escape sequences: {{ "escape\\nsequence".| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce('escape\nsequence');
expect(completions('{{ "escape\\nsequence".| }}')).toHaveLength(
natives({ typeName: 'string' }).length +
extensions({ typeName: 'string' }).length +
STRING_RECOMMENDED_OPTIONS.length,
);
});
});
describe('Function Calls', () => {
test('should return completions for function call results: {{ Math.abs(-5).| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(5);
expect(completions('{{ Math.abs(-5).| }}')).toHaveLength(
natives({ typeName: 'number' }).length +
extensions({ typeName: 'number' }).length +
['isEven()', 'isOdd()'].length,
);
});
test('should return completions for chained function calls: {{ $now.plus({ days: 1 }).| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(
DateTime.now().plus({ days: 1 }),
);
expect(completions('{{ $now.plus({ days: 1 }).| }}')).toHaveLength(
uniqBy(
luxonInstanceOptions().concat(extensions({ typeName: 'date' })),
(option) => option.label,
).length + LUXON_RECOMMENDED_OPTIONS.length,
);
});
});
});
export function completions(docWithCursor: string, explicit = false) {
const cursorPosition = docWithCursor.indexOf('|');
const doc = docWithCursor.slice(0, cursorPosition) + docWithCursor.slice(cursorPosition + 1);
const state = EditorState.create({
doc,
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
const context = new CompletionContext(state, cursorPosition, explicit);
for (const completionSource of state.languageDataAt<CompletionSource>(
'autocomplete',
cursorPosition,
)) {
const result = completionSource(context);
if (isCompletionResult(result)) return result.options;
}
return null;
}
function isCompletionResult(
candidate: ReturnType<CompletionSource>,
): candidate is CompletionResult {
return candidate !== null && 'from' in candidate && 'options' in candidate;
}

View File

@@ -0,0 +1,105 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { CompletionContext } from '@codemirror/autocomplete';
import { EditorState } from '@codemirror/state';
import { n8nLang } from '@/plugins/codemirror/n8nLang';
import { useItemFieldCompletions } from '@/components/CodeNodeEditor/completions/itemField.completions';
describe('itemFieldCompletions', () => {
let context: CompletionContext;
beforeEach(() => {
setActivePinia(createTestingPinia());
});
describe('matcherItemFieldCompletions', () => {
test('should return null if no match found', () => {
const doc = '{{ $input.noMatch.| }}';
const cursorPosition = doc.indexOf('|');
const state = EditorState.create({
doc: doc.replace('|', ''),
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
context = new CompletionContext(state, cursorPosition, true);
const result = useItemFieldCompletions('javaScript').matcherItemFieldCompletions(
context,
'$input.noMatch',
{ '$input.item': 'item' },
);
expect(result).toBeNull();
});
});
describe('inputMethodCompletions', () => {
test('should return completions for $input.first().', () => {
const doc = '{{ $input.first().| }}';
const cursorPosition = doc.indexOf('|');
const state = EditorState.create({
doc: doc.replace('|', ''),
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
context = new CompletionContext(state, cursorPosition, true);
const result = useItemFieldCompletions('javaScript').inputMethodCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(2);
expect(result?.options[0].label).toBe('$input.first().json');
expect(result?.options[1].label).toBe('$input.first().binary');
});
test('should return null if no match found', () => {
const doc = '{{ $input.noMatch().| }}';
const cursorPosition = doc.indexOf('|');
const state = EditorState.create({
doc: doc.replace('|', ''),
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
context = new CompletionContext(state, cursorPosition, true);
const result = useItemFieldCompletions('javaScript').inputMethodCompletions(context);
expect(result).toBeNull();
});
});
describe('selectorMethodCompletions', () => {
test("should return completions for $('nodeName').first().", () => {
const doc = "{{ $('nodeName').first().| }}";
const cursorPosition = doc.indexOf('|');
const state = EditorState.create({
doc: doc.replace('|', ''),
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
context = new CompletionContext(state, cursorPosition, true);
const result = useItemFieldCompletions('javaScript').selectorMethodCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(2);
expect(result?.options[0].label).toBe("$('nodeName').first().json");
expect(result?.options[1].label).toBe("$('nodeName').first().binary");
});
test('should return null if no match found', () => {
const doc = "{{ $('noMatch').noMatch().| }}";
const cursorPosition = doc.indexOf('|');
const state = EditorState.create({
doc: doc.replace('|', ''),
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
context = new CompletionContext(state, cursorPosition, true);
const result = useItemFieldCompletions('javaScript').selectorMethodCompletions(context);
expect(result).toBeNull();
});
});
});

View File

@@ -0,0 +1,55 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { EditorState } from '@codemirror/state';
import { CompletionContext } from '@codemirror/autocomplete';
import { describe, test, expect, beforeEach } from 'vitest';
import { useItemIndexCompletions } from '@/components/CodeNodeEditor/completions/itemIndex.completions';
let mode: 'runOnceForEachItem' | 'runOnceForAllItems';
beforeEach(() => {
setActivePinia(createTestingPinia());
mode = 'runOnceForAllItems';
});
describe('itemIndexCompletions', () => {
test('should return completions for $input. in all-items mode', () => {
const state = EditorState.create({ doc: '$input.', selection: { anchor: 7 } });
const context = new CompletionContext(state, 7, true);
const result = useItemIndexCompletions(mode).inputCompletions.call({ mode }, context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(4);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: '$input.first()' }),
expect.objectContaining({ label: '$input.last()' }),
expect.objectContaining({ label: '$input.all()' }),
expect.objectContaining({ label: '$input.itemMatching()' }),
]),
);
});
test('should return completions for $input. in single-item mode', () => {
mode = 'runOnceForEachItem';
const state = EditorState.create({ doc: '$input.', selection: { anchor: 7 } });
const context = new CompletionContext(state, 7, true);
const result = useItemIndexCompletions(mode).inputCompletions.call({ mode }, context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(1);
expect(result?.options).toEqual(
expect.arrayContaining([expect.objectContaining({ label: '$input.item' })]),
);
});
test('should return null for non-matching context', () => {
const state = EditorState.create({ doc: 'randomText', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
expect(useItemIndexCompletions(mode).inputCompletions.call({ mode }, context)).toBeNull();
});
test('should return null for non-matching selector context', () => {
const state = EditorState.create({ doc: 'randomText', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
expect(useItemIndexCompletions(mode).selectorCompletions.call({ mode }, context)).toBeNull();
});
});

View File

@@ -0,0 +1,108 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import * as workflowHelpers from '@/composables/useWorkflowHelpers';
import * as utils from '@/plugins/codemirror/completions/utils';
import { extensions, natives } from '@/plugins/codemirror/completions/datatype.completions';
import type { CompletionSource, CompletionResult } from '@codemirror/autocomplete';
import { CompletionContext } from '@codemirror/autocomplete';
import { EditorState } from '@codemirror/state';
import { n8nLang } from '@/plugins/codemirror/n8nLang';
import { useExternalSecretsStore } from '@/stores/externalSecrets.ee.store';
import { useUIStore } from '@/stores/ui.store';
import { useSettingsStore } from '@/stores/settings.store';
let externalSecretsStore: ReturnType<typeof useExternalSecretsStore>;
let uiStore: ReturnType<typeof useUIStore>;
let settingsStore: ReturnType<typeof useSettingsStore>;
beforeEach(async () => {
setActivePinia(createTestingPinia());
externalSecretsStore = useExternalSecretsStore();
uiStore = useUIStore();
settingsStore = useSettingsStore();
vi.spyOn(utils, 'receivesNoBinaryData').mockReturnValue(true); // hide $binary
vi.spyOn(utils, 'isSplitInBatchesAbsent').mockReturnValue(false); // show context
vi.spyOn(utils, 'hasActiveNode').mockReturnValue(true);
});
export function completions(docWithCursor: string, explicit = false) {
const cursorPosition = docWithCursor.indexOf('|');
const doc = docWithCursor.slice(0, cursorPosition) + docWithCursor.slice(cursorPosition + 1);
const state = EditorState.create({
doc,
selection: { anchor: cursorPosition },
extensions: [n8nLang()],
});
const context = new CompletionContext(state, cursorPosition, explicit);
for (const completionSource of state.languageDataAt<CompletionSource>(
'autocomplete',
cursorPosition,
)) {
const result = completionSource(context);
if (isCompletionResult(result)) return result.options;
}
return null;
}
function isCompletionResult(
candidate: ReturnType<CompletionSource>,
): candidate is CompletionResult {
return candidate !== null && 'from' in candidate && 'options' in candidate;
}
describe('jsonField.completions', () => {
test('should return null for invalid syntax: {{ $input.item.json..| }}', () => {
expect(completions('{{ $input.item.json..| }}')).toBeNull();
});
test('should return null for non-existent node: {{ $("NonExistentNode").item.json.| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(null);
expect(completions('{{ $("NonExistentNode").item.json.| }}')).toBeNull();
});
test('should return completions for complex expressions: {{ Math.max($input.item.json.num1, $input.item.json.num2).| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(123);
const result = completions('{{ Math.max($input.item.json.num1, $input.item.json.num2).| }}');
expect(result).toHaveLength(
extensions({ typeName: 'number' }).length +
natives({ typeName: 'number' }).length +
['isEven()', 'isOdd()'].length,
);
});
test('should return completions for boolean expressions: {{ $input.item.json.flag && $input.item.json.| }}', () => {
const json = { flag: true, key1: 'value1', key2: 'value2' };
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(json);
const result = completions('{{ $input.item.json.flag && $input.item.json.| }}');
expect(result).toHaveLength(
Object.keys(json).length + extensions({ typeName: 'object' }).length,
);
});
test('should return null for undefined values: {{ $input.item.json.undefinedValue.| }}', () => {
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(undefined);
expect(completions('{{ $input.item.json.undefinedValue.| }}')).toBeNull();
});
test('should return completions for large JSON objects: {{ $input.item.json.largeObject.| }}', () => {
const largeObject: { [key: string]: string } = {};
for (let i = 0; i < 1000; i++) {
largeObject[`key${i}`] = `value${i}`;
}
vi.spyOn(workflowHelpers, 'resolveParameter').mockReturnValueOnce(largeObject);
const result = completions('{{ $input.item.json.largeObject.| }}');
expect(result).toHaveLength(
Object.keys(largeObject).length + extensions({ typeName: 'object' }).length,
);
});
});

View File

@@ -0,0 +1,56 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { CompletionContext } from '@codemirror/autocomplete';
import { EditorState } from '@codemirror/state';
import { usePrevNodeCompletions } from '@/components/CodeNodeEditor/completions/prevNode.completions';
describe('prevNodeCompletions', () => {
const { prevNodeCompletions } = usePrevNodeCompletions();
beforeEach(() => {
setActivePinia(createTestingPinia());
});
test('should return completions for explicit empty context', () => {
const state = EditorState.create({ doc: '$prevNode.', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
const result = prevNodeCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(3);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: '$prevNode.name' }),
expect.objectContaining({ label: '$prevNode.outputIndex' }),
expect.objectContaining({ label: '$prevNode.runIndex' }),
]),
);
});
test('should return null for non-matching context', () => {
const state = EditorState.create({ doc: 'randomText', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
expect(prevNodeCompletions(context)).toBeNull();
});
test('should return completions for partial match', () => {
const state = EditorState.create({ doc: '$prevNode.n', selection: { anchor: 11 } });
const context = new CompletionContext(state, 11, true);
const result = prevNodeCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(3);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: '$prevNode.name' }),
expect.objectContaining({ label: '$prevNode.outputIndex' }),
expect.objectContaining({ label: '$prevNode.runIndex' }),
]),
);
});
test('should return null for empty matcher', () => {
const state = EditorState.create({ doc: '.', selection: { anchor: 1 } });
const context = new CompletionContext(state, 1, true);
expect(prevNodeCompletions(context)).toBeNull();
});
});

View File

@@ -0,0 +1,126 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { CompletionContext } from '@codemirror/autocomplete';
import { EditorState } from '@codemirror/state';
import { useSettingsStore } from '@/stores/settings.store';
import { useRequireCompletions } from '@/components/CodeNodeEditor/completions/require.completions';
import { AUTOCOMPLETABLE_BUILT_IN_MODULES_JS } from '@/components/CodeNodeEditor/constants';
import * as utils from '@/plugins/codemirror/completions/utils';
let settingsStore: ReturnType<typeof useSettingsStore>;
describe('requireCompletions', () => {
beforeEach(() => {
setActivePinia(createTestingPinia());
settingsStore = useSettingsStore();
vi.spyOn(utils, 'receivesNoBinaryData').mockReturnValue(true); // hide $binary
vi.spyOn(utils, 'isSplitInBatchesAbsent').mockReturnValue(false); // show context
vi.spyOn(utils, 'hasActiveNode').mockReturnValue(true);
});
it('should return completions for explicit empty context', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: ['fs', 'path'],
external: ['lodash'],
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(3);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "require('fs');" }),
expect.objectContaining({ label: "require('path');" }),
expect.objectContaining({ label: "require('lodash');" }),
]),
);
});
it('should return completions for partial match', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: ['fs', 'path'],
external: ['lodash'],
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(3);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "require('fs');" }),
expect.objectContaining({ label: "require('path');" }),
expect.objectContaining({ label: "require('lodash');" }),
]),
);
});
it('should handle built-in wildcard', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: ['*'],
external: [],
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(AUTOCOMPLETABLE_BUILT_IN_MODULES_JS.length);
expect(result?.options).toEqual(
expect.arrayContaining(
AUTOCOMPLETABLE_BUILT_IN_MODULES_JS.map((module) =>
expect.objectContaining({ label: `require('${module}');` }),
),
),
);
});
it('should return null for non-matching context', () => {
const state = EditorState.create({ doc: 'randomText', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
expect(useRequireCompletions().requireCompletions(context)).toBeNull();
});
it('should return completions for mixed built-in and external modules', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: ['fs'],
external: ['lodash', 'axios'],
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(3);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: "require('fs');" }),
expect.objectContaining({ label: "require('lodash');" }),
expect.objectContaining({ label: "require('axios');" }),
]),
);
});
it('should handle empty allowedModules gracefully', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: [],
external: [],
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(0);
});
it('should handle missing allowedModules gracefully', () => {
vi.spyOn(settingsStore, 'allowedModules', 'get').mockReturnValue({
builtIn: undefined,
external: undefined,
});
const state = EditorState.create({ doc: 'req', selection: { anchor: 3 } });
const context = new CompletionContext(state, 3, true);
const result = useRequireCompletions().requireCompletions(context);
expect(result?.options).toHaveLength(0);
});
});

View File

@@ -0,0 +1,64 @@
import { createTestingPinia } from '@pinia/testing';
import { setActivePinia } from 'pinia';
import { EditorState } from '@codemirror/state';
import { CompletionContext } from '@codemirror/autocomplete';
import { useEnvironmentsStore } from '@/stores/environments.ee.store';
import { useVariablesCompletions } from '@/components/CodeNodeEditor/completions/variables.completions';
let environmentsStore: ReturnType<typeof useEnvironmentsStore>;
beforeEach(() => {
setActivePinia(createTestingPinia());
environmentsStore = useEnvironmentsStore();
});
describe('variablesCompletions', () => {
test('should return completions for $vars prefix', () => {
environmentsStore.variables = [
{ key: 'VAR1', value: 'Value1', id: 1 },
{ key: 'VAR2', value: 'Value2', id: 2 },
];
const state = EditorState.create({ doc: '$vars.', selection: { anchor: 6 } });
const context = new CompletionContext(state, 6, true);
const result = useVariablesCompletions().variablesCompletions(context);
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(2);
expect(result?.options).toEqual(
expect.arrayContaining([
expect.objectContaining({ label: '$vars.VAR1', info: 'Value1' }),
expect.objectContaining({ label: '$vars.VAR2', info: 'Value2' }),
]),
);
});
test('should return null for non-matching context', () => {
const state = EditorState.create({ doc: 'randomText', selection: { anchor: 10 } });
const context = new CompletionContext(state, 10, true);
expect(useVariablesCompletions().variablesCompletions(context)).toBeNull();
});
test('should escape special characters in matcher', () => {
environmentsStore.variables = [{ key: 'VAR1', value: 'Value1', id: 1 }];
const state = EditorState.create({ doc: '$vars.', selection: { anchor: 6 } });
const context = new CompletionContext(state, 6, true);
const result = useVariablesCompletions().variablesCompletions(context, '$var$');
expect(result).toBeNull();
});
test('should return completions for custom matcher', () => {
environmentsStore.variables = [{ key: 'VAR1', value: 'Value1', id: 1 }];
const state = EditorState.create({ doc: '$custom.', selection: { anchor: 8 } });
const context = new CompletionContext(state, 8, true);
const result = useVariablesCompletions().variablesCompletions(context, '$custom');
expect(result).not.toBeNull();
expect(result?.options).toHaveLength(1);
expect(result?.options).toEqual(
expect.arrayContaining([expect.objectContaining({ label: '$custom.VAR1', info: 'Value1' })]),
);
});
});