-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathscriptsSlice.ts
More file actions
179 lines (164 loc) · 4.62 KB
/
Copy pathscriptsSlice.ts
File metadata and controls
179 lines (164 loc) · 4.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import {
createAsyncThunk,
createSlice,
nanoid,
PayloadAction,
} from "@reduxjs/toolkit";
import { importScript } from "./api/scriptApi";
import { ScriptExecution, ScriptsState, UserScript } from "./types";
import { validateUrlPattern } from "./utils/patternUtils";
import { validateScript } from "./utils/scriptValidator";
// Async thunk to add a new user script by importing from a URL or direct input
export const addUserScript = createAsyncThunk<
UserScript,
{
url?: string;
code?: string;
name: string;
description?: string;
urlPatterns: string[];
runAt: "document-start" | "document-ready" | "document-end";
},
{ rejectValue: string }
>("scripts/createUserScript", async (args, { rejectWithValue }) => {
try {
// Validate URL patterns
const urlPatternValidations = args.urlPatterns.map(validateUrlPattern);
const invalidPatterns = urlPatternValidations.filter(
(result) => !result.valid
);
if (invalidPatterns.length > 0) {
return rejectWithValue(
invalidPatterns.map((result) => result.error).join(", ")
);
}
let code: string | undefined;
if (args.code) {
code = args.code;
} else if (args.url) {
code = await importScript(args.url);
} else {
return rejectWithValue("Either 'url' or 'code' must be provided.");
}
// Validate the script code before creating the script
const scriptValidation = validateScript(code);
if (!scriptValidation.valid) {
return rejectWithValue(
scriptValidation.error ?? "Unknown validation error"
);
}
const now = new Date().toISOString();
return {
id: nanoid(),
name: args.name,
description: args.description,
runAt: args.runAt,
code,
urlPatterns: args.urlPatterns,
enabled: true,
createdAt: now,
updatedAt: now,
};
} catch (error) {
return rejectWithValue((error as Error).message);
}
});
const initialState: ScriptsState = {
userScripts: {},
executions: {},
isLoading: false,
error: null,
};
const scriptsSlice = createSlice({
name: "scripts",
initialState,
reducers: {
updateUserScript: {
reducer: (
state,
action: PayloadAction<{
id: string;
updates: Partial<UserScript>;
updatedAt: string;
}>
) => {
const { id, updates, updatedAt } = action.payload;
const script = state.userScripts[id];
if (script) {
Object.assign(script, { ...updates, updatedAt });
}
},
prepare: (id: string, updates: Partial<UserScript>) => {
return {
payload: {
id,
updates,
updatedAt: new Date().toISOString(),
},
};
},
},
deleteUserScript: (state, action: PayloadAction<string>) => {
const scriptId = action.payload;
// Remove the script
delete state.userScripts[scriptId];
// Also remove related execution logs
Object.entries(state.executions).forEach(([id, execution]) => {
if (execution.scriptId === scriptId) {
delete state.executions[id];
}
});
},
toggleUserScript: {
reducer: (
state,
action: PayloadAction<{ id: string; updatedAt: string }>
) => {
const script = state.userScripts[action.payload.id];
if (script) {
script.enabled = !script.enabled;
script.updatedAt = action.payload.updatedAt;
}
},
prepare: (id: string) => ({
payload: {
id,
updatedAt: new Date().toISOString(),
},
}),
},
logScriptExecution: (state, action: PayloadAction<ScriptExecution>) => {
state.executions[action.payload.id] = action.payload;
},
clearExecutionLogs: (state) => {
state.executions = {};
},
setError: (state, action: PayloadAction<string | null>) => {
state.error = action.payload;
},
},
extraReducers: (builder) => {
builder
.addCase(addUserScript.pending, (state) => {
state.isLoading = true;
state.error = null;
})
.addCase(addUserScript.fulfilled, (state, action) => {
state.isLoading = false;
state.userScripts[action.payload.id] = action.payload;
})
.addCase(addUserScript.rejected, (state, action) => {
state.isLoading = false;
state.error = action.error.message || "Script import failed!";
});
},
});
export const {
updateUserScript,
deleteUserScript,
toggleUserScript,
logScriptExecution,
clearExecutionLogs,
setError,
} = scriptsSlice.actions;
export default scriptsSlice.reducer;