@nocobase/flow-engine 3.0.0-alpha.7 → 3.0.0-alpha.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/FlowContextSelector.js +7 -1
- package/lib/flowContext.d.ts +5 -1
- package/lib/flowContext.js +13 -2
- package/lib/utils/dateVariable.d.ts +22 -0
- package/lib/utils/dateVariable.js +123 -16
- package/lib/utils/index.d.ts +1 -1
- package/lib/utils/index.js +4 -0
- package/lib/utils/params-resolvers.d.ts +1 -0
- package/lib/utils/params-resolvers.js +1 -0
- package/lib/views/createViewMeta.d.ts +1 -0
- package/lib/views/createViewMeta.js +35 -6
- package/package.json +4 -4
- package/src/__tests__/createViewMeta.popup.test.ts +84 -1
- package/src/__tests__/flowContext.test.ts +8 -0
- package/src/__tests__/objectVariable.test.ts +6 -1
- package/src/__tests__/runjsFormSubmit.test.ts +45 -0
- package/src/components/FlowContextSelector.tsx +7 -1
- package/src/components/variables/__tests__/FlowContextSelector.test.tsx +35 -0
- package/src/flowContext.ts +23 -3
- package/src/utils/__tests__/dateVariable.test.ts +57 -4
- package/src/utils/dateVariable.ts +145 -18
- package/src/utils/index.ts +6 -0
- package/src/utils/params-resolvers.ts +2 -0
- package/src/views/createViewMeta.ts +33 -0
|
@@ -16,6 +16,7 @@ import { RunJSContextRegistry } from '../runjs-context/registry';
|
|
|
16
16
|
import { setupRunJSContexts } from '../runjs-context/setup';
|
|
17
17
|
import { createViewScopedEngine } from '../ViewScopedFlowEngine';
|
|
18
18
|
import { DATA_SOURCE_DIRTY_EVENT } from '../views/viewEvents';
|
|
19
|
+
import { serializeCtxDateExpressionConfig } from '../utils/dateVariable';
|
|
19
20
|
|
|
20
21
|
describe('FlowContext properties and methods', () => {
|
|
21
22
|
it('should return static property value', () => {
|
|
@@ -2068,10 +2069,16 @@ describe('getPropertyMetaTree with deep delegate meta', () => {
|
|
|
2068
2069
|
describe('FlowContext resolveOnServer selective server resolution', () => {
|
|
2069
2070
|
it('resolves ctx.date expressions on client context', async () => {
|
|
2070
2071
|
const engine = new FlowEngine();
|
|
2072
|
+
const formattedToday = serializeCtxDateExpressionConfig({
|
|
2073
|
+
kind: 'preset',
|
|
2074
|
+
preset: 'today',
|
|
2075
|
+
format: 'YYYY/MM/DD',
|
|
2076
|
+
});
|
|
2071
2077
|
const out = await (engine.context as any).resolveJsonTemplate({
|
|
2072
2078
|
today: '{{ ctx.date.preset.today }}',
|
|
2073
2079
|
next12: '{{ ctx.date.relative.next.day.n12 }}',
|
|
2074
2080
|
now: '{{ ctx.date.preset.now }}',
|
|
2081
|
+
formattedToday,
|
|
2075
2082
|
});
|
|
2076
2083
|
|
|
2077
2084
|
expect(typeof out.today).toBe('string');
|
|
@@ -2080,6 +2087,7 @@ describe('FlowContext resolveOnServer selective server resolution', () => {
|
|
|
2080
2087
|
expect(out.next12).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
2081
2088
|
expect(typeof out.now).toBe('string');
|
|
2082
2089
|
expect(out.now.length).toBeGreaterThan(0);
|
|
2090
|
+
expect(out.formattedToday).toMatch(/^\d{4}\/\d{2}\/\d{2}$/);
|
|
2083
2091
|
});
|
|
2084
2092
|
|
|
2085
2093
|
it('does not call server by default (no resolveOnServer set)', async () => {
|
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
import { describe, expect, it, vi } from 'vitest';
|
|
11
|
+
import { generateFlowModelRdFromToken } from '@nocobase/utils/client';
|
|
11
12
|
import { FlowContext } from '../flowContext';
|
|
12
13
|
import { FlowEngine } from '../flowEngine';
|
|
13
14
|
import {
|
|
@@ -122,7 +123,10 @@ describe('objectVariable utilities', () => {
|
|
|
122
123
|
|
|
123
124
|
// Provide API stub to intercept variables:resolve
|
|
124
125
|
const calls: any[] = [];
|
|
126
|
+
const payload = Buffer.from(JSON.stringify({ userId: 1, signInTime: 'contract-owner-test' })).toString('base64url');
|
|
127
|
+
const token = `test.${payload}.sig`;
|
|
125
128
|
(ctx as any).api = {
|
|
129
|
+
auth: { token },
|
|
126
130
|
request: vi.fn(async ({ url, data, method }) => {
|
|
127
131
|
calls.push({ url, data, method });
|
|
128
132
|
const batch = (data?.values?.batch as any[]) || [];
|
|
@@ -146,13 +150,14 @@ describe('objectVariable utilities', () => {
|
|
|
146
150
|
});
|
|
147
151
|
|
|
148
152
|
const template = { x: '{{ ctx.obj.author.name }}' } as any;
|
|
149
|
-
await (ctx as any).resolveJsonTemplate(template);
|
|
153
|
+
await (ctx as any).resolveJsonTemplate(template, { contractModelUid: 'form-grid' });
|
|
150
154
|
|
|
151
155
|
// Assert variables:resolve was called with proper flattened contextParams
|
|
152
156
|
expect((ctx as any).api.request).toHaveBeenCalled();
|
|
153
157
|
const call = calls.find((c) => c.url === 'variables:resolve');
|
|
154
158
|
expect(call).toBeTruthy();
|
|
155
159
|
const batch0 = call.data?.values?.batch?.[0];
|
|
160
|
+
expect(batch0?.contractRd).toBe(generateFlowModelRdFromToken('form-grid', token));
|
|
156
161
|
expect(batch0?.contextParams).toBeTruthy();
|
|
157
162
|
// Flattened key should be 'obj.author'
|
|
158
163
|
const cp = batch0.contextParams as Record<string, any>;
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* This file is part of the NocoBase (R) project.
|
|
3
|
+
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
|
|
4
|
+
* Authors: NocoBase Team.
|
|
5
|
+
*
|
|
6
|
+
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
|
|
7
|
+
* For more information, please refer to: https://www.nocobase.com/agreement.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
11
|
+
import { FlowContext, FlowRunJSContext } from '../flowContext';
|
|
12
|
+
import { JSItemRunJSContext } from '../runjs-context/contexts/JSItemRunJSContext';
|
|
13
|
+
|
|
14
|
+
describe('FlowRunJSContext form submission', () => {
|
|
15
|
+
it('uses the form block RunJS submit capability without changing the native form', () => {
|
|
16
|
+
const nativeSubmit = vi.fn();
|
|
17
|
+
const getFieldsValue = vi.fn(() => ({ name: 'Alice' }));
|
|
18
|
+
const form = { submit: nativeSubmit, getFieldsValue };
|
|
19
|
+
const submitFromRunJs = vi.fn();
|
|
20
|
+
const delegate = new FlowContext();
|
|
21
|
+
delegate.defineProperty('form', { value: form });
|
|
22
|
+
delegate.defineProperty('blockModel', { value: { submitFromRunJs } });
|
|
23
|
+
|
|
24
|
+
const ctx = new JSItemRunJSContext(delegate);
|
|
25
|
+
|
|
26
|
+
expect(ctx.form.getFieldsValue()).toEqual({ name: 'Alice' });
|
|
27
|
+
ctx.form.submit();
|
|
28
|
+
expect(submitFromRunJs).toHaveBeenCalledOnce();
|
|
29
|
+
expect(nativeSubmit).not.toHaveBeenCalled();
|
|
30
|
+
expect(form.submit).toBe(nativeSubmit);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
it('keeps the native submit method when the block has no RunJS submit capability', () => {
|
|
34
|
+
const nativeSubmit = vi.fn();
|
|
35
|
+
const form = { submit: nativeSubmit };
|
|
36
|
+
const delegate = new FlowContext();
|
|
37
|
+
delegate.defineProperty('form', { value: form });
|
|
38
|
+
delegate.defineProperty('blockModel', { value: {} });
|
|
39
|
+
|
|
40
|
+
const ctx = new FlowRunJSContext(delegate);
|
|
41
|
+
|
|
42
|
+
ctx.form.submit();
|
|
43
|
+
expect(nativeSubmit).toHaveBeenCalledOnce();
|
|
44
|
+
});
|
|
45
|
+
});
|
|
@@ -311,6 +311,7 @@ const FlowContextSelectorComponent: React.FC<FlowContextSelectorProps> = ({
|
|
|
311
311
|
const path = selectedValues.map(String);
|
|
312
312
|
const pathString = path.join('.');
|
|
313
313
|
const isLeaf = lastOption?.isLeaf;
|
|
314
|
+
const isSelectable = lastOption?.meta?.selectable !== false;
|
|
314
315
|
const now = Date.now();
|
|
315
316
|
|
|
316
317
|
// 使用自定义格式化函数或默认函数
|
|
@@ -325,6 +326,10 @@ const FlowContextSelectorComponent: React.FC<FlowContextSelectorProps> = ({
|
|
|
325
326
|
}
|
|
326
327
|
|
|
327
328
|
if (isLeaf) {
|
|
329
|
+
if (!isSelectable) {
|
|
330
|
+
setTempSelectedPath(path);
|
|
331
|
+
return;
|
|
332
|
+
}
|
|
328
333
|
onChange?.(formattedValue, lastOption?.meta);
|
|
329
334
|
// 选中叶子节点后,可清空内部临时路径(外部 value 将驱动级联)
|
|
330
335
|
setTempSelectedPath([]);
|
|
@@ -333,7 +338,8 @@ const FlowContextSelectorComponent: React.FC<FlowContextSelectorProps> = ({
|
|
|
333
338
|
|
|
334
339
|
// 非叶子节点:检查双击
|
|
335
340
|
const lastSelected = lastSelectedRef.current;
|
|
336
|
-
const isDoubleClick =
|
|
341
|
+
const isDoubleClick =
|
|
342
|
+
isSelectable && !onlyLeafSelectable && lastSelected?.path === pathString && now - lastSelected.time < 300;
|
|
337
343
|
|
|
338
344
|
if (isDoubleClick) {
|
|
339
345
|
// 双击:选中非叶子节点
|
|
@@ -864,4 +864,39 @@ describe('FlowContextSelector', () => {
|
|
|
864
864
|
// It should only expand the node, not select it
|
|
865
865
|
expect(onChange).not.toHaveBeenCalled();
|
|
866
866
|
});
|
|
867
|
+
|
|
868
|
+
it('should expand but never select a node marked selectable=false', async () => {
|
|
869
|
+
const onChange = vi.fn();
|
|
870
|
+
const flowContext = createTestFlowContext();
|
|
871
|
+
const metaTree = [
|
|
872
|
+
{
|
|
873
|
+
name: 'date',
|
|
874
|
+
title: 'Date',
|
|
875
|
+
type: 'date',
|
|
876
|
+
paths: ['date'],
|
|
877
|
+
selectable: false,
|
|
878
|
+
children: [{ name: 'today', title: 'Today', type: 'date', paths: ['date', 'today'] }],
|
|
879
|
+
},
|
|
880
|
+
];
|
|
881
|
+
|
|
882
|
+
render(
|
|
883
|
+
<TestFlowContextWrapper context={flowContext}>
|
|
884
|
+
<FlowContextSelector metaTree={metaTree} onChange={onChange} />
|
|
885
|
+
</TestFlowContextWrapper>,
|
|
886
|
+
);
|
|
887
|
+
|
|
888
|
+
fireEvent.click(screen.getByRole('button'));
|
|
889
|
+
await waitFor(() => expect(screen.getByText('Date')).toBeInTheDocument());
|
|
890
|
+
|
|
891
|
+
fireEvent.click(screen.getByText('Date'));
|
|
892
|
+
fireEvent.click(screen.getByText('Date'));
|
|
893
|
+
expect(onChange).not.toHaveBeenCalled();
|
|
894
|
+
|
|
895
|
+
await waitFor(() => expect(screen.getByText('Today')).toBeInTheDocument());
|
|
896
|
+
fireEvent.click(screen.getByText('Today'));
|
|
897
|
+
expect(onChange).toHaveBeenCalledWith(
|
|
898
|
+
'{{ ctx.date.today }}',
|
|
899
|
+
expect.objectContaining({ paths: ['date', 'today'] }),
|
|
900
|
+
);
|
|
901
|
+
});
|
|
867
902
|
});
|
package/src/flowContext.ts
CHANGED
|
@@ -165,6 +165,10 @@ function inferSelectsFromUsage(paths: string[] = []): { generatedAppends?: strin
|
|
|
165
165
|
|
|
166
166
|
type Getter<T = any> = (ctx: FlowContext) => T | Promise<T>;
|
|
167
167
|
|
|
168
|
+
export type ResolveJsonTemplateOptions = {
|
|
169
|
+
contractModelUid?: string | number | null;
|
|
170
|
+
};
|
|
171
|
+
|
|
168
172
|
export type FlowContextDocRef = string | { url: string; title?: string };
|
|
169
173
|
|
|
170
174
|
export type FlowDeprecationDoc =
|
|
@@ -221,6 +225,8 @@ export interface MetaTreeNode {
|
|
|
221
225
|
// 变量禁用状态与原因(用于变量选择器 UI 展示)
|
|
222
226
|
disabled?: boolean | (() => boolean);
|
|
223
227
|
disabledReason?: string | (() => string | undefined);
|
|
228
|
+
// 允许节点仅用于展开子级,而不能作为变量值被选中
|
|
229
|
+
selectable?: boolean;
|
|
224
230
|
children?: MetaTreeNode[] | (() => Promise<MetaTreeNode[]>);
|
|
225
231
|
}
|
|
226
232
|
|
|
@@ -3044,7 +3050,7 @@ class BaseFlowEngineContext extends FlowContext {
|
|
|
3044
3050
|
* @deprecated use `resolveJsonTemplate` instead
|
|
3045
3051
|
*/
|
|
3046
3052
|
declare renderJson: (template: JSONValue) => Promise<any>;
|
|
3047
|
-
declare resolveJsonTemplate: (template: JSONValue) => Promise<any>;
|
|
3053
|
+
declare resolveJsonTemplate: (template: JSONValue, options?: ResolveJsonTemplateOptions) => Promise<any>;
|
|
3048
3054
|
declare getVar: (path: string) => Promise<any>;
|
|
3049
3055
|
declare request: (options: RequestOptions) => Promise<any>;
|
|
3050
3056
|
declare runjs: (code: string, variables?: Record<string, any>, options?: JSRunnerOptions) => Promise<any>;
|
|
@@ -3227,7 +3233,11 @@ export class FlowEngineContext extends BaseFlowEngineContext {
|
|
|
3227
3233
|
this.defineMethod('renderJson', function (template: any) {
|
|
3228
3234
|
return this.resolveJsonTemplate(template);
|
|
3229
3235
|
});
|
|
3230
|
-
|
|
3236
|
+
const resolveJsonTemplate = async function (
|
|
3237
|
+
this: BaseFlowEngineContext,
|
|
3238
|
+
template: any,
|
|
3239
|
+
options?: ResolveJsonTemplateOptions,
|
|
3240
|
+
) {
|
|
3231
3241
|
// 提取模板使用到的变量及其子路径
|
|
3232
3242
|
const used = extractUsedVariablePaths(template);
|
|
3233
3243
|
const usedVarNames = Object.keys(used || {});
|
|
@@ -3396,7 +3406,12 @@ export class FlowEngineContext extends BaseFlowEngineContext {
|
|
|
3396
3406
|
|
|
3397
3407
|
if (this.api) {
|
|
3398
3408
|
try {
|
|
3409
|
+
const contractRd = buildFlowModelResolveDescriptor(
|
|
3410
|
+
this as FlowRuntimeContext<FlowModel>,
|
|
3411
|
+
options?.contractModelUid,
|
|
3412
|
+
);
|
|
3399
3413
|
serverResolved = await enqueueVariablesResolve(this as FlowRuntimeContext<FlowModel>, {
|
|
3414
|
+
...(contractRd ? { contractRd } : {}),
|
|
3400
3415
|
rd: buildFlowModelResolveDescriptor(this as FlowRuntimeContext<FlowModel>, this.model?.uid),
|
|
3401
3416
|
template,
|
|
3402
3417
|
contextParams: autoContextParams || {},
|
|
@@ -3409,7 +3424,8 @@ export class FlowEngineContext extends BaseFlowEngineContext {
|
|
|
3409
3424
|
}
|
|
3410
3425
|
|
|
3411
3426
|
return resolveExpressions(serverResolved, this);
|
|
3412
|
-
}
|
|
3427
|
+
};
|
|
3428
|
+
this.defineMethod('resolveJsonTemplate', resolveJsonTemplate);
|
|
3413
3429
|
|
|
3414
3430
|
// Helper: resolve a single ctx expression value via resolveJsonTemplate behavior.
|
|
3415
3431
|
// Example: await ctx.getVar('ctx.record.id')
|
|
@@ -4595,6 +4611,10 @@ export class FlowRunJSContext extends FlowContext {
|
|
|
4595
4611
|
constructor(delegate: FlowContext) {
|
|
4596
4612
|
super();
|
|
4597
4613
|
this.addDelegate(delegate);
|
|
4614
|
+
const submit = delegate.blockModel?.submitFromRunJs?.bind(delegate.blockModel);
|
|
4615
|
+
if (delegate.form && submit) {
|
|
4616
|
+
this.defineProperty('form', { value: { ...delegate.form, submit } });
|
|
4617
|
+
}
|
|
4598
4618
|
this.defineProperty('React', { value: React });
|
|
4599
4619
|
this.defineProperty('antd', { value: antd });
|
|
4600
4620
|
this.defineProperty('dayjs', {
|
|
@@ -12,9 +12,12 @@ import {
|
|
|
12
12
|
decodeBase64Url,
|
|
13
13
|
encodeBase64Url,
|
|
14
14
|
isCompleteCtxDatePath,
|
|
15
|
+
isCtxDatePathPrefix,
|
|
15
16
|
isCtxDateExpression,
|
|
16
17
|
parseCtxDateExpression,
|
|
18
|
+
parseCtxDateExpressionConfig,
|
|
17
19
|
resolveCtxDatePath,
|
|
20
|
+
serializeCtxDateExpressionConfig,
|
|
18
21
|
serializeCtxDateValue,
|
|
19
22
|
} from '../dateVariable';
|
|
20
23
|
|
|
@@ -54,13 +57,60 @@ describe('dateVariable utils', () => {
|
|
|
54
57
|
number: 2,
|
|
55
58
|
});
|
|
56
59
|
|
|
57
|
-
const singleExpr = serializeCtxDateValue('2026-02-12')
|
|
60
|
+
const singleExpr = serializeCtxDateValue('2026-02-12');
|
|
61
|
+
if (!singleExpr) throw new Error('Expected exact date expression');
|
|
58
62
|
expect(parseCtxDateExpression(singleExpr)).toBe('2026-02-12');
|
|
59
63
|
|
|
60
|
-
const rangeExpr = serializeCtxDateValue(['2026-02-12', '2026-02-20'])
|
|
64
|
+
const rangeExpr = serializeCtxDateValue(['2026-02-12', '2026-02-20']);
|
|
65
|
+
if (!rangeExpr) throw new Error('Expected exact date range expression');
|
|
61
66
|
expect(parseCtxDateExpression(rangeExpr)).toEqual(['2026-02-12', '2026-02-20']);
|
|
62
67
|
});
|
|
63
68
|
|
|
69
|
+
it('serializes, parses and resolves formatted expressions', () => {
|
|
70
|
+
const expression = serializeCtxDateExpressionConfig({
|
|
71
|
+
kind: 'preset',
|
|
72
|
+
preset: 'today',
|
|
73
|
+
format: 'YYYY/MM/DD',
|
|
74
|
+
});
|
|
75
|
+
if (!expression) throw new Error('Expected formatted date expression');
|
|
76
|
+
|
|
77
|
+
expect(expression).toMatch(/^\{\{ ctx\.date\.format\.v[A-Za-z0-9_-]+\.preset\.today \}\}$/);
|
|
78
|
+
expect(parseCtxDateExpressionConfig(expression)).toEqual({
|
|
79
|
+
kind: 'preset',
|
|
80
|
+
preset: 'today',
|
|
81
|
+
format: 'YYYY/MM/DD',
|
|
82
|
+
});
|
|
83
|
+
// Keep the legacy parser contract for filter-form consumers.
|
|
84
|
+
expect(parseCtxDateExpression(expression)).toEqual({ type: 'today' });
|
|
85
|
+
|
|
86
|
+
const path = expression.replace('{{ ctx.', '').replace(' }}', '').split('.');
|
|
87
|
+
expect(resolveCtxDatePath(path)).toMatch(/^\d{4}\/\d{2}\/\d{2}$/);
|
|
88
|
+
expect(isCompleteCtxDatePath(path)).toBe(true);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('preserves significant whitespace in a custom Format', () => {
|
|
92
|
+
const expression = serializeCtxDateExpressionConfig({
|
|
93
|
+
kind: 'preset',
|
|
94
|
+
preset: 'today',
|
|
95
|
+
format: 'YYYY-MM-DD ',
|
|
96
|
+
});
|
|
97
|
+
if (!expression) throw new Error('Expected formatted date expression');
|
|
98
|
+
|
|
99
|
+
expect(parseCtxDateExpressionConfig(expression)?.format).toBe('YYYY-MM-DD ');
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('formats exact ranges element by element', () => {
|
|
103
|
+
const expression = serializeCtxDateExpressionConfig({
|
|
104
|
+
kind: 'exact',
|
|
105
|
+
value: ['2026-02-12', '2026-02-20'],
|
|
106
|
+
format: 'YYYYMMDD',
|
|
107
|
+
});
|
|
108
|
+
if (!expression) throw new Error('Expected formatted date range expression');
|
|
109
|
+
const path = expression.replace('{{ ctx.', '').replace(' }}', '').split('.');
|
|
110
|
+
|
|
111
|
+
expect(resolveCtxDatePath(path)).toEqual(['20260212', '20260220']);
|
|
112
|
+
});
|
|
113
|
+
|
|
64
114
|
it('resolves preset/relative/exact path', () => {
|
|
65
115
|
expect(typeof resolveCtxDatePath(['date', 'preset', 'now'])).toBe('string');
|
|
66
116
|
|
|
@@ -72,11 +122,13 @@ describe('dateVariable utils', () => {
|
|
|
72
122
|
expect(typeof rel).toBe('string');
|
|
73
123
|
expect(rel).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
|
74
124
|
|
|
75
|
-
const singleExpr = serializeCtxDateValue('2026-02-12')
|
|
125
|
+
const singleExpr = serializeCtxDateValue('2026-02-12');
|
|
126
|
+
if (!singleExpr) throw new Error('Expected exact date expression');
|
|
76
127
|
const token = singleExpr.replace('{{ ctx.date.exact.single.date.', '').replace(' }}', '');
|
|
77
128
|
expect(resolveCtxDatePath(['date', 'exact', 'single', 'date', token])).toBe('2026-02-12');
|
|
78
129
|
|
|
79
|
-
const rangeExpr = serializeCtxDateValue(['2026-02-12', '2026-02-20'])
|
|
130
|
+
const rangeExpr = serializeCtxDateValue(['2026-02-12', '2026-02-20']);
|
|
131
|
+
if (!rangeExpr) throw new Error('Expected exact date range expression');
|
|
80
132
|
const parts = rangeExpr.replace('{{ ctx.date.exact.range.date.', '').replace(' }}', '').split('.');
|
|
81
133
|
expect(resolveCtxDatePath(['date', 'exact', 'range', 'date', parts[0], parts[1]])).toEqual([
|
|
82
134
|
'2026-02-12',
|
|
@@ -90,6 +142,7 @@ describe('dateVariable utils', () => {
|
|
|
90
142
|
expect(isCompleteCtxDatePath(['date', 'exact', 'single', 'date', 'vabc'])).toBe(true);
|
|
91
143
|
expect(isCompleteCtxDatePath(['date', 'exact', 'range', 'date', 'vabc', 'vdef'])).toBe(true);
|
|
92
144
|
expect(isCompleteCtxDatePath(['date', 'relative', 'next', 'day'])).toBe(false);
|
|
145
|
+
expect(isCtxDatePathPrefix(['date', 'format'])).toBe(true);
|
|
93
146
|
expect(isCompleteCtxDatePath(['user', 'name'])).toBe(false);
|
|
94
147
|
});
|
|
95
148
|
|
|
@@ -11,7 +11,7 @@ import dayjs from 'dayjs';
|
|
|
11
11
|
|
|
12
12
|
const CTX_DATE_REGEX = /^\{\{\s*ctx\.date(?:\.(.+?))?\s*\}\}$/;
|
|
13
13
|
|
|
14
|
-
const
|
|
14
|
+
const PRESET_KEY_LIST = [
|
|
15
15
|
'today',
|
|
16
16
|
'now',
|
|
17
17
|
'yesterday',
|
|
@@ -28,10 +28,28 @@ const PRESET_KEYS = new Set([
|
|
|
28
28
|
'thisYear',
|
|
29
29
|
'lastYear',
|
|
30
30
|
'nextYear',
|
|
31
|
-
]
|
|
31
|
+
] as const;
|
|
32
|
+
|
|
33
|
+
export type CtxDatePreset = (typeof PRESET_KEY_LIST)[number];
|
|
34
|
+
export type CtxDateRelativeDirection = 'next' | 'past';
|
|
35
|
+
export type CtxDateRelativeUnit = 'day' | 'week' | 'month' | 'year';
|
|
36
|
+
|
|
37
|
+
export type CtxDateExpressionConfig =
|
|
38
|
+
| { kind: 'exact'; value: string | [string, string]; format?: string }
|
|
39
|
+
| {
|
|
40
|
+
kind: 'relative';
|
|
41
|
+
direction: CtxDateRelativeDirection;
|
|
42
|
+
amount: number;
|
|
43
|
+
unit: CtxDateRelativeUnit;
|
|
44
|
+
format?: string;
|
|
45
|
+
}
|
|
46
|
+
| { kind: 'preset'; preset: CtxDatePreset; format?: string };
|
|
47
|
+
|
|
48
|
+
const PRESET_KEYS = new Set<string>(PRESET_KEY_LIST);
|
|
32
49
|
|
|
33
50
|
const RELATIVE_DIRECTIONS = new Set(['next', 'past']);
|
|
34
51
|
const RELATIVE_UNITS = new Set(['day', 'week', 'month', 'year']);
|
|
52
|
+
const MAX_DATE_FORMAT_LENGTH = 128;
|
|
35
53
|
|
|
36
54
|
function parseCtxDateSegments(value: string): string[] | null {
|
|
37
55
|
if (typeof value !== 'string') return null;
|
|
@@ -46,8 +64,7 @@ function parseCtxDateSegments(value: string): string[] | null {
|
|
|
46
64
|
.filter(Boolean);
|
|
47
65
|
}
|
|
48
66
|
|
|
49
|
-
|
|
50
|
-
const segments = withDatePrefix((pathSegments || []).map((seg) => String(seg)));
|
|
67
|
+
function isBaseCtxDatePathPrefix(segments: string[]): boolean {
|
|
51
68
|
if (segments[0] !== 'date') return false;
|
|
52
69
|
if (segments.length === 1) return true;
|
|
53
70
|
|
|
@@ -96,6 +113,36 @@ export function isCtxDatePathPrefix(pathSegments: string[]): boolean {
|
|
|
96
113
|
return false;
|
|
97
114
|
}
|
|
98
115
|
|
|
116
|
+
function decodeFormatToken(token: string): string | undefined {
|
|
117
|
+
const raw = String(token || '');
|
|
118
|
+
if (!raw.startsWith('v')) return undefined;
|
|
119
|
+
const decoded = decodeBase64Url(raw.slice(1));
|
|
120
|
+
if (!decoded || decoded.length > MAX_DATE_FORMAT_LENGTH) return undefined;
|
|
121
|
+
return decoded;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function splitFormattedDateSegments(segments: string[]): { baseSegments: string[]; format?: string } | null {
|
|
125
|
+
if (segments[0] !== 'date') return null;
|
|
126
|
+
if (segments[1] !== 'format') return { baseSegments: segments };
|
|
127
|
+
if (segments.length < 4) return null;
|
|
128
|
+
|
|
129
|
+
const format = decodeFormatToken(segments[2]);
|
|
130
|
+
if (!format) return null;
|
|
131
|
+
return { baseSegments: ['date', ...segments.slice(3)], format };
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function isCtxDatePathPrefix(pathSegments: string[]): boolean {
|
|
135
|
+
const segments = withDatePrefix((pathSegments || []).map((seg) => String(seg)));
|
|
136
|
+
if (segments[0] !== 'date') return false;
|
|
137
|
+
if (segments.length === 1) return true;
|
|
138
|
+
if (segments[1] !== 'format') return isBaseCtxDatePathPrefix(segments);
|
|
139
|
+
if (segments.length === 2) return true;
|
|
140
|
+
if (segments.length === 3) return typeof decodeFormatToken(segments[2]) === 'string';
|
|
141
|
+
|
|
142
|
+
const formatted = splitFormattedDateSegments(segments);
|
|
143
|
+
return formatted ? isBaseCtxDatePathPrefix(formatted.baseSegments) : false;
|
|
144
|
+
}
|
|
145
|
+
|
|
99
146
|
function withDatePrefix(pathSegments: string[]): string[] {
|
|
100
147
|
if (pathSegments[0] === 'date') {
|
|
101
148
|
return pathSegments;
|
|
@@ -210,27 +257,29 @@ export function isCtxDateExpression(value: unknown): value is string {
|
|
|
210
257
|
export function isCompleteCtxDatePath(pathSegments: string[]): boolean {
|
|
211
258
|
if (!isCtxDatePathPrefix(pathSegments)) return false;
|
|
212
259
|
const segments = withDatePrefix((pathSegments || []).map((seg) => String(seg)));
|
|
213
|
-
|
|
260
|
+
const formatted = splitFormattedDateSegments(segments);
|
|
261
|
+
if (!formatted) return false;
|
|
262
|
+
const baseSegments = formatted.baseSegments;
|
|
214
263
|
|
|
215
|
-
if (
|
|
216
|
-
return
|
|
264
|
+
if (baseSegments[1] === 'preset') {
|
|
265
|
+
return baseSegments.length === 3 && PRESET_KEYS.has(baseSegments[2]);
|
|
217
266
|
}
|
|
218
267
|
|
|
219
|
-
if (
|
|
220
|
-
if (
|
|
268
|
+
if (baseSegments[1] === 'relative') {
|
|
269
|
+
if (baseSegments.length !== 5) return false;
|
|
221
270
|
return (
|
|
222
|
-
RELATIVE_DIRECTIONS.has(
|
|
223
|
-
RELATIVE_UNITS.has(
|
|
224
|
-
typeof parseNumberToken(
|
|
271
|
+
RELATIVE_DIRECTIONS.has(baseSegments[2]) &&
|
|
272
|
+
RELATIVE_UNITS.has(baseSegments[3]) &&
|
|
273
|
+
typeof parseNumberToken(baseSegments[4]) === 'number'
|
|
225
274
|
);
|
|
226
275
|
}
|
|
227
276
|
|
|
228
|
-
if (
|
|
229
|
-
return
|
|
277
|
+
if (baseSegments[1] === 'exact' && baseSegments[2] === 'single' && baseSegments[3] === 'date') {
|
|
278
|
+
return baseSegments.length === 5 && /^v.+/.test(baseSegments[4]);
|
|
230
279
|
}
|
|
231
280
|
|
|
232
|
-
if (
|
|
233
|
-
return
|
|
281
|
+
if (baseSegments[1] === 'exact' && baseSegments[2] === 'range' && baseSegments[3] === 'date') {
|
|
282
|
+
return baseSegments.length === 6 && /^v.+/.test(baseSegments[4]) && /^v.+/.test(baseSegments[5]);
|
|
234
283
|
}
|
|
235
284
|
|
|
236
285
|
return false;
|
|
@@ -238,7 +287,10 @@ export function isCompleteCtxDatePath(pathSegments: string[]): boolean {
|
|
|
238
287
|
|
|
239
288
|
export function parseCtxDateExpression(value: unknown): any {
|
|
240
289
|
if (!isCtxDateExpression(value)) return undefined;
|
|
241
|
-
const
|
|
290
|
+
const rawSegments = withDatePrefix(parseCtxDateSegments(value as string) || []);
|
|
291
|
+
const formatted = splitFormattedDateSegments(rawSegments);
|
|
292
|
+
if (!formatted) return undefined;
|
|
293
|
+
const segments = formatted.baseSegments;
|
|
242
294
|
|
|
243
295
|
if (segments[1] === 'preset' && segments.length === 3 && PRESET_KEYS.has(segments[2])) {
|
|
244
296
|
return { type: segments[2] };
|
|
@@ -276,6 +328,66 @@ export function parseCtxDateExpression(value: unknown): any {
|
|
|
276
328
|
return undefined;
|
|
277
329
|
}
|
|
278
330
|
|
|
331
|
+
export function parseCtxDateExpressionConfig(value: unknown): CtxDateExpressionConfig | undefined {
|
|
332
|
+
if (!isCtxDateExpression(value)) return undefined;
|
|
333
|
+
const segments = withDatePrefix(parseCtxDateSegments(value) || []);
|
|
334
|
+
const formatted = splitFormattedDateSegments(segments);
|
|
335
|
+
if (!formatted) return undefined;
|
|
336
|
+
|
|
337
|
+
const parsed = parseCtxDateExpression(value);
|
|
338
|
+
const formatConfig = formatted.format ? { format: formatted.format } : {};
|
|
339
|
+
if (typeof parsed === 'string') {
|
|
340
|
+
return { kind: 'exact', value: parsed, ...formatConfig };
|
|
341
|
+
}
|
|
342
|
+
if (Array.isArray(parsed) && parsed.length === 2 && typeof parsed[0] === 'string' && typeof parsed[1] === 'string') {
|
|
343
|
+
return { kind: 'exact', value: [parsed[0], parsed[1]], ...formatConfig };
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (!parsed || typeof parsed !== 'object') return undefined;
|
|
347
|
+
const typed = parsed as { type?: unknown; unit?: unknown; number?: unknown };
|
|
348
|
+
if (typed.type === 'past' || typed.type === 'next') {
|
|
349
|
+
if (typeof typed.unit !== 'string' || !RELATIVE_UNITS.has(typed.unit) || typeof typed.number !== 'number') {
|
|
350
|
+
return undefined;
|
|
351
|
+
}
|
|
352
|
+
return {
|
|
353
|
+
kind: 'relative',
|
|
354
|
+
direction: typed.type,
|
|
355
|
+
amount: typed.number,
|
|
356
|
+
unit: typed.unit as CtxDateRelativeUnit,
|
|
357
|
+
...formatConfig,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
if (typeof typed.type === 'string' && PRESET_KEYS.has(typed.type)) {
|
|
362
|
+
return { kind: 'preset', preset: typed.type as CtxDatePreset, ...formatConfig };
|
|
363
|
+
}
|
|
364
|
+
return undefined;
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
export function serializeCtxDateExpressionConfig(config: CtxDateExpressionConfig): string | undefined {
|
|
368
|
+
let legacyValue: unknown;
|
|
369
|
+
|
|
370
|
+
if (config.kind === 'preset') {
|
|
371
|
+
if (!PRESET_KEYS.has(config.preset)) return undefined;
|
|
372
|
+
legacyValue = { type: config.preset };
|
|
373
|
+
} else if (config.kind === 'relative') {
|
|
374
|
+
if (!RELATIVE_DIRECTIONS.has(config.direction) || !RELATIVE_UNITS.has(config.unit)) return undefined;
|
|
375
|
+
const amount = Math.floor(Number(config.amount));
|
|
376
|
+
if (!Number.isFinite(amount) || amount <= 0) return undefined;
|
|
377
|
+
legacyValue = { type: config.direction, unit: config.unit, number: amount };
|
|
378
|
+
} else {
|
|
379
|
+
legacyValue = config.value;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const expression = serializeCtxDateValue(legacyValue);
|
|
383
|
+
if (!expression || !config.format) return expression;
|
|
384
|
+
|
|
385
|
+
const format = String(config.format);
|
|
386
|
+
if (!format.trim() || format.length > MAX_DATE_FORMAT_LENGTH) return undefined;
|
|
387
|
+
const segments = withDatePrefix(parseCtxDateSegments(expression) || []);
|
|
388
|
+
return toCtxDateExpression(['date', 'format', `v${encodeBase64Url(format)}`, ...segments.slice(1)]);
|
|
389
|
+
}
|
|
390
|
+
|
|
279
391
|
export function serializeCtxDateValue(value: unknown): string | undefined {
|
|
280
392
|
if (isCtxDateExpression(value)) {
|
|
281
393
|
return String(value).trim();
|
|
@@ -327,8 +439,23 @@ export function serializeCtxDateValue(value: unknown): string | undefined {
|
|
|
327
439
|
return undefined;
|
|
328
440
|
}
|
|
329
441
|
|
|
442
|
+
function formatResolvedDateValue(value: unknown, format: string): unknown {
|
|
443
|
+
const formatValue = (item: unknown) => {
|
|
444
|
+
if (typeof item !== 'string') return item;
|
|
445
|
+
const parsed = dayjs(item);
|
|
446
|
+
return parsed.isValid() ? parsed.format(format) : item;
|
|
447
|
+
};
|
|
448
|
+
return Array.isArray(value) ? value.map(formatValue) : formatValue(value);
|
|
449
|
+
}
|
|
450
|
+
|
|
330
451
|
export function resolveCtxDatePath(pathSegments: string[]): any {
|
|
331
|
-
const
|
|
452
|
+
const rawSegments = withDatePrefix((pathSegments || []).map((seg) => String(seg)));
|
|
453
|
+
const formatted = splitFormattedDateSegments(rawSegments);
|
|
454
|
+
if (!formatted) return undefined;
|
|
455
|
+
if (formatted.format) {
|
|
456
|
+
return formatResolvedDateValue(resolveCtxDatePath(formatted.baseSegments), formatted.format);
|
|
457
|
+
}
|
|
458
|
+
const segments = formatted.baseSegments;
|
|
332
459
|
if (segments[0] !== 'date') return undefined;
|
|
333
460
|
|
|
334
461
|
if (segments[1] === 'preset' && segments.length === 3) {
|
package/src/utils/index.ts
CHANGED
|
@@ -92,8 +92,14 @@ export {
|
|
|
92
92
|
isCtxDatePathPrefix,
|
|
93
93
|
isCtxDateExpression,
|
|
94
94
|
parseCtxDateExpression,
|
|
95
|
+
parseCtxDateExpressionConfig,
|
|
95
96
|
resolveCtxDatePath,
|
|
97
|
+
serializeCtxDateExpressionConfig,
|
|
96
98
|
serializeCtxDateValue,
|
|
99
|
+
type CtxDateExpressionConfig,
|
|
100
|
+
type CtxDatePreset,
|
|
101
|
+
type CtxDateRelativeDirection,
|
|
102
|
+
type CtxDateRelativeUnit,
|
|
97
103
|
} from './dateVariable';
|
|
98
104
|
|
|
99
105
|
// RunJS value helpers
|
|
@@ -79,6 +79,7 @@ export type JSONValue = string | { [key: string]: JSONValue } | JSONValue[];
|
|
|
79
79
|
// =========================
|
|
80
80
|
|
|
81
81
|
type BatchPayload = {
|
|
82
|
+
contractRd?: string;
|
|
82
83
|
rd?: string;
|
|
83
84
|
template: JSONValue;
|
|
84
85
|
contextParams?: ServerContextParams | undefined;
|
|
@@ -172,6 +173,7 @@ export function enqueueVariablesResolve(ctx: FlowRuntimeContext, payload: BatchP
|
|
|
172
173
|
try {
|
|
173
174
|
const batch = items.map((it) => ({
|
|
174
175
|
id: it.id,
|
|
176
|
+
contractRd: it.payload.contractRd,
|
|
175
177
|
rd: it.payload.rd,
|
|
176
178
|
template: it.payload.template,
|
|
177
179
|
contextParams: it.payload.contextParams || {},
|