@jsb188/app 1.0.4 → 1.1.2
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/package.json +57 -37
- package/src/constants/agent.ts +74 -0
- package/src/constants/app.ts +389 -0
- package/src/constants/emoji.ts +9153 -0
- package/src/constants/other.ts +13 -0
- package/src/constants/user.ts +27 -0
- package/src/constants/wsActions.ts +49 -0
- package/src/i18n/account.ts +139 -0
- package/src/i18n/agent.ts +397 -0
- package/src/i18n/agentToolBusiness.ts +196 -0
- package/src/i18n/agentToolGrid.ts +137 -0
- package/src/i18n/agentToolWorkflow.ts +101 -0
- package/src/i18n/agent_note.ts +109 -0
- package/src/i18n/app.ts +124 -0
- package/src/i18n/auth.ts +128 -0
- package/src/i18n/billing.ts +7 -0
- package/src/i18n/c.ts +907 -0
- package/src/i18n/campaign.ts +919 -0
- package/src/i18n/country.ts +249 -0
- package/src/i18n/datetime.ts +66 -0
- package/src/i18n/editor.ts +58 -0
- package/src/i18n/error.ts +579 -0
- package/src/i18n/field_doc_editor.ts +21 -0
- package/src/i18n/field_doc_programs.ts +52 -0
- package/src/i18n/field_docs.ts +190 -0
- package/src/i18n/index.ts +64 -0
- package/src/i18n/log.ts +566 -0
- package/src/i18n/memory.ts +59 -0
- package/src/i18n/message.ts +13 -0
- package/src/i18n/note.ts +19 -0
- package/src/i18n/org.ts +306 -0
- package/src/i18n/schedule.ts +209 -0
- package/src/i18n/sheet.ts +339 -0
- package/src/i18n/sheet_formula.ts +165 -0
- package/src/i18n/workflow.ts +111 -0
- package/src/main.ts +89 -0
- package/src/platform.ts +166 -0
- package/src/types/ai.d.ts +63 -0
- package/src/types/app.d.ts +127 -0
- package/src/types/auth.d.ts +94 -0
- package/src/types/console.d.ts +3 -0
- package/src/types/node-polyglot.d.ts +23 -0
- package/src/types/other.d.ts +66 -0
- package/src/types.d.ts +29 -0
- package/src/utils/account.ts +97 -0
- package/src/utils/api.ts +358 -0
- package/src/utils/authSession.ts +24 -0
- package/src/utils/clientIP.ts +213 -0
- package/src/utils/color.ts +279 -0
- package/src/utils/cron.ts +310 -0
- package/src/utils/csv.ts +19 -0
- package/src/utils/datetime.ts +1394 -0
- package/src/utils/deferredSave.ts +89 -0
- package/src/utils/email.ts +39 -0
- package/src/utils/emoji.ts +174 -0
- package/src/utils/expression.helpers.ts +470 -0
- package/src/utils/expression.test.ts +793 -0
- package/src/utils/expression.ts +2261 -0
- package/src/utils/interval.ts +80 -0
- package/src/utils/language.ts +9 -0
- package/src/utils/logic.ts +299 -0
- package/src/utils/managedSession.ts +34 -0
- package/src/utils/managedSessionBff.test.ts +60 -0
- package/src/utils/managedSessionBff.ts +117 -0
- package/src/utils/number.ts +338 -0
- package/src/utils/object.ts +916 -0
- package/src/utils/promise.ts +98 -0
- package/src/utils/queryReset.ts +266 -0
- package/src/utils/recurringTask.ts +60 -0
- package/src/utils/schema.ts +293 -0
- package/src/utils/string.test.ts +278 -0
- package/src/utils/string.ts +709 -0
- package/src/utils/timeZone.ts +2048 -0
- package/src/utils/url_client.ts +206 -0
- package/tsconfig.json +12 -0
- package/constants/app.ts +0 -47
- package/constants/billing.ts +0 -146
- package/constants/emoji.ts +0 -8945
- package/constants/user.ts +0 -36
- package/constants/ws.ts +0 -47
- package/i18n/app.ts +0 -99
- package/i18n/auth.ts +0 -57
- package/i18n/billing.ts +0 -94
- package/i18n/datetime.ts +0 -22
- package/i18n/error.ts +0 -138
- package/i18n/form.ts +0 -73
- package/i18n/index.ts +0 -6
- package/i18n/user.ts +0 -98
- package/main.ts +0 -62
- package/types/app.d.ts +0 -46
- package/types/datetime.d.ts +0 -10
- package/types/form.d.ts +0 -56
- package/types/user.d.ts +0 -52
- package/types.d.ts +0 -23
- package/utils/api.ts +0 -99
- package/utils/billing.ts +0 -134
- package/utils/datetime.ts +0 -358
- package/utils/emoji.ts +0 -151
- package/utils/logic.ts +0 -115
- package/utils/number.ts +0 -115
- package/utils/object.ts +0 -367
- package/utils/string.ts +0 -211
- package/utils/url_client.ts +0 -138
- package/utils/user.ts +0 -273
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Types
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
export type MaybePromise<T> = T | Promise<T>;
|
|
6
|
+
|
|
7
|
+
/*
|
|
8
|
+
* Return whether one value is thenable.
|
|
9
|
+
*/
|
|
10
|
+
export function isPromiseLike<T>(value: MaybePromise<T>): value is Promise<T> {
|
|
11
|
+
return Boolean(
|
|
12
|
+
value && (typeof value === 'object' || typeof value === 'function') && typeof (value as Promise<T>).then === 'function',
|
|
13
|
+
);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Chain one continuation onto a maybe-promise without forcing async:
|
|
18
|
+
* plain values invoke the continuation synchronously.
|
|
19
|
+
*/
|
|
20
|
+
export function chainMaybePromise<T, R>(value: MaybePromise<T>, onValue: (value: T) => MaybePromise<R>): MaybePromise<R> {
|
|
21
|
+
return isPromiseLike(value) ? value.then(onValue) : onValue(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/*
|
|
25
|
+
* Run one async task per item with at most `limit` in flight, starting the next
|
|
26
|
+
* item as soon as any task finishes. Every item runs even when some fail; the
|
|
27
|
+
* first failure is rethrown once all tasks have settled.
|
|
28
|
+
*/
|
|
29
|
+
export async function runWithConcurrencyLimit<T>(items: readonly T[], limit: number, task: (item: T, index: number) => Promise<void>) {
|
|
30
|
+
let nextIndex = 0;
|
|
31
|
+
let failure: { error: unknown } | null = null;
|
|
32
|
+
const runWorker = async () => {
|
|
33
|
+
while (nextIndex < items.length) {
|
|
34
|
+
const index = nextIndex++;
|
|
35
|
+
try {
|
|
36
|
+
await task(items[index], index);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
failure = failure || { error };
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const workerLimit = Number.isFinite(limit) ? Math.floor(limit) : 1;
|
|
44
|
+
await Promise.all(Array.from({ length: Math.max(1, Math.min(workerLimit, items.length)) }, runWorker));
|
|
45
|
+
if (failure) {
|
|
46
|
+
throw (failure as { error: unknown }).error;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export type ConcurrencyGate = {
|
|
51
|
+
run: <T>(task: () => Promise<T>) => Promise<T>;
|
|
52
|
+
tryRun: <T>(task: () => Promise<T>) => Promise<{ ran: true; value: T } | { ran: false }>;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
/*
|
|
56
|
+
* Create a gate that lets at most `getLimit()` tasks run at once across every
|
|
57
|
+
* caller that shares it. `run` waits for a slot in arrival order; `tryRun` runs
|
|
58
|
+
* only when a slot is free now and nobody is waiting, and otherwise returns
|
|
59
|
+
* ran=false at once. The limit is read at each admission, so it may come from
|
|
60
|
+
* configuration loaded after the gate was created.
|
|
61
|
+
*/
|
|
62
|
+
export function createConcurrencyGate(getLimit: () => number): ConcurrencyGate {
|
|
63
|
+
let active = 0;
|
|
64
|
+
const waiters: Array<() => void> = [];
|
|
65
|
+
const hasSlot = () => active < Math.max(1, Math.floor(getLimit()));
|
|
66
|
+
const release = () => {
|
|
67
|
+
active -= 1;
|
|
68
|
+
while (waiters.length && hasSlot()) {
|
|
69
|
+
active += 1;
|
|
70
|
+
waiters.shift()?.();
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
const runAdmitted = async <T>(task: () => Promise<T>) => {
|
|
74
|
+
try {
|
|
75
|
+
return await task();
|
|
76
|
+
} finally {
|
|
77
|
+
release();
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
return {
|
|
82
|
+
run: async (task) => {
|
|
83
|
+
if (hasSlot() && !waiters.length) {
|
|
84
|
+
active += 1;
|
|
85
|
+
} else {
|
|
86
|
+
await new Promise<void>((resolve) => waiters.push(resolve));
|
|
87
|
+
}
|
|
88
|
+
return await runAdmitted(task);
|
|
89
|
+
},
|
|
90
|
+
tryRun: async (task) => {
|
|
91
|
+
if (!hasSlot() || waiters.length) {
|
|
92
|
+
return { ran: false };
|
|
93
|
+
}
|
|
94
|
+
active += 1;
|
|
95
|
+
return { ran: true, value: await runAdmitted(task) };
|
|
96
|
+
},
|
|
97
|
+
};
|
|
98
|
+
}
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Structured query-reset targets. A target names one GraphQL query and,
|
|
3
|
+
* optionally, the serialized variable values a cached page must carry to be
|
|
4
|
+
* reset by it without building or evaluating a regex.
|
|
5
|
+
*
|
|
6
|
+
* Cache keys are '#queryName:' + makeGraphQLVariablesKey(variables). Request
|
|
7
|
+
* identity preserves exact JSON values. Reset targets retain their existing
|
|
8
|
+
* case-insensitive variable matching and also understand legacy cache keys.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
export interface QueryResetTarget {
|
|
12
|
+
name: string;
|
|
13
|
+
match?: Record<string, string>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/*
|
|
17
|
+
* Build one structured query-reset target. Variable names and values are
|
|
18
|
+
* lowercased for compatibility with existing server reset payloads.
|
|
19
|
+
*
|
|
20
|
+
* Callers decide which constraints apply: omit a key to widen the target (no
|
|
21
|
+
* constraint on that variable), and pass an empty value only if the intent is
|
|
22
|
+
* a target that matches nothing, since makeVariablesKey() drops empty values
|
|
23
|
+
* from cache keys entirely.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
export function makeQueryResetTarget(
|
|
27
|
+
name: string,
|
|
28
|
+
match?: Record<string, string | number | bigint | undefined>,
|
|
29
|
+
): QueryResetTarget {
|
|
30
|
+
const normalizedMatch: Record<string, string> = {};
|
|
31
|
+
|
|
32
|
+
for (const [variableName, value] of Object.entries(match || {})) {
|
|
33
|
+
// An explicitly undefined value is an absent constraint, which is how
|
|
34
|
+
// callers widen a target; an empty string is a real constraint that
|
|
35
|
+
// matches nothing, since makeVariablesKey() drops empty values
|
|
36
|
+
if (value === undefined) {
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
normalizedMatch[variableName.toLowerCase()] = String(value).toLowerCase();
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return Object.keys(normalizedMatch).length
|
|
44
|
+
? { name, match: normalizedMatch }
|
|
45
|
+
: { name };
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/*
|
|
49
|
+
* Build unconstrained structured reset targets for a list of GraphQL queries.
|
|
50
|
+
*/
|
|
51
|
+
|
|
52
|
+
export function makeQueryResetTargets(...names: string[]) {
|
|
53
|
+
return names.map((name) => makeQueryResetTarget(name));
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/*
|
|
57
|
+
* Parse serialized variables while preserving dollar signs inside JSON filter values.
|
|
58
|
+
*/
|
|
59
|
+
|
|
60
|
+
function parseVariablesKeySegments(variablesKey: string) {
|
|
61
|
+
const pairs: Record<string, string[]> = {};
|
|
62
|
+
const segments: string[] = [];
|
|
63
|
+
let start = 0;
|
|
64
|
+
let quoted = false;
|
|
65
|
+
let escaped = false;
|
|
66
|
+
let readingValue = false;
|
|
67
|
+
let jsonDepth = 0;
|
|
68
|
+
let jsonStart = -1;
|
|
69
|
+
for (let index = 0; index < variablesKey.length; index++) {
|
|
70
|
+
const character = variablesKey[index];
|
|
71
|
+
if (escaped) {
|
|
72
|
+
escaped = false;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (!readingValue && character === ':') {
|
|
76
|
+
readingValue = true;
|
|
77
|
+
jsonStart = index + 1;
|
|
78
|
+
} else if (quoted && character === '\\') {
|
|
79
|
+
escaped = true;
|
|
80
|
+
} else if (jsonDepth && character === '"') {
|
|
81
|
+
quoted = !quoted;
|
|
82
|
+
} else if (
|
|
83
|
+
!quoted &&
|
|
84
|
+
jsonDepth &&
|
|
85
|
+
(character === '}' || character === ']')
|
|
86
|
+
) {
|
|
87
|
+
jsonDepth--;
|
|
88
|
+
} else if (
|
|
89
|
+
!quoted &&
|
|
90
|
+
(jsonDepth || index === jsonStart) &&
|
|
91
|
+
(character === '{' || character === '[')
|
|
92
|
+
) {
|
|
93
|
+
jsonDepth++;
|
|
94
|
+
} else if (!quoted && !jsonDepth && character === '$') {
|
|
95
|
+
segments.push(variablesKey.slice(start, index));
|
|
96
|
+
start = index + 1;
|
|
97
|
+
readingValue = false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
segments.push(variablesKey.slice(start));
|
|
101
|
+
|
|
102
|
+
for (const segment of segments) {
|
|
103
|
+
const separatorIndex = segment.indexOf(':');
|
|
104
|
+
if (separatorIndex < 1) {
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
const variableName = segment.slice(0, separatorIndex);
|
|
109
|
+
const value = segment.slice(separatorIndex + 1);
|
|
110
|
+
if (pairs[variableName]) {
|
|
111
|
+
pairs[variableName].push(value);
|
|
112
|
+
} else {
|
|
113
|
+
pairs[variableName] = [value];
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
return pairs;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/*
|
|
121
|
+
* Match a nested filter field without requiring every pagination and filter variable to be identical.
|
|
122
|
+
*/
|
|
123
|
+
function nestedVariableMatches(
|
|
124
|
+
pairs: Record<string, string[]>,
|
|
125
|
+
variableName: string,
|
|
126
|
+
expectedValue: string,
|
|
127
|
+
) {
|
|
128
|
+
const [root, ...path] = variableName.split('.');
|
|
129
|
+
if (
|
|
130
|
+
!path.length ||
|
|
131
|
+
path.some((key) => ['__proto__', 'constructor', 'prototype'].includes(key))
|
|
132
|
+
)
|
|
133
|
+
return false;
|
|
134
|
+
return (pairs[root] || []).some((serialized) => {
|
|
135
|
+
try {
|
|
136
|
+
let value: unknown = JSON.parse(serialized);
|
|
137
|
+
for (const key of path) {
|
|
138
|
+
if (!value || typeof value !== 'object' || !Object.hasOwn(value, key))
|
|
139
|
+
return false;
|
|
140
|
+
value = (value as Record<string, unknown>)[key];
|
|
141
|
+
}
|
|
142
|
+
return (
|
|
143
|
+
value !== null && value !== undefined && String(value) === expectedValue
|
|
144
|
+
);
|
|
145
|
+
} catch {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/*
|
|
152
|
+
* Return whether one cached query key is covered by a structured reset target.
|
|
153
|
+
* A target with no match constraints covers every page of that query, which is
|
|
154
|
+
* what the plain '#queryName:' prefix keys have always done.
|
|
155
|
+
*/
|
|
156
|
+
|
|
157
|
+
export function queryCacheKeyMatchesResetTarget(
|
|
158
|
+
queryCacheKey: string,
|
|
159
|
+
target: QueryResetTarget,
|
|
160
|
+
) {
|
|
161
|
+
const queryPrefix = `#${target.name}:`;
|
|
162
|
+
if (!queryCacheKey.startsWith(queryPrefix)) {
|
|
163
|
+
return false;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
const matchEntries = Object.entries(target.match || {});
|
|
167
|
+
if (!matchEntries.length) {
|
|
168
|
+
return true;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
const variablesKey = queryCacheKey.slice(queryPrefix.length);
|
|
172
|
+
// New keys preserve exact GraphQL values. Reset targets intentionally keep
|
|
173
|
+
// their legacy case-insensitive matching so existing server emits still work.
|
|
174
|
+
if (variablesKey.startsWith('@')) {
|
|
175
|
+
try {
|
|
176
|
+
const variables = JSON.parse(variablesKey.slice(1));
|
|
177
|
+
return matchEntries.every(([path, expected]) => {
|
|
178
|
+
let value = variables;
|
|
179
|
+
for (const part of path.split('.')) {
|
|
180
|
+
if (!value || typeof value !== 'object') return false;
|
|
181
|
+
const key = Object.keys(value).find((key) => key.toLowerCase() === part.toLowerCase());
|
|
182
|
+
if (!key || ['__proto__', 'constructor', 'prototype'].includes(key)) return false;
|
|
183
|
+
value = value[key];
|
|
184
|
+
}
|
|
185
|
+
return value != null && String(value).toLowerCase() === expected.toLowerCase();
|
|
186
|
+
});
|
|
187
|
+
} catch {
|
|
188
|
+
return false;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
const pairs = parseVariablesKeySegments(variablesKey);
|
|
192
|
+
return matchEntries.every(
|
|
193
|
+
([variableName, value]) =>
|
|
194
|
+
Boolean(pairs[variableName]?.includes(value)) ||
|
|
195
|
+
nestedVariableMatches(pairs, variableName, value),
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/*
|
|
200
|
+
* Return whether any target in a list covers one cached query key.
|
|
201
|
+
*/
|
|
202
|
+
|
|
203
|
+
export function queryCacheKeyMatchesAnyResetTarget(
|
|
204
|
+
queryCacheKey: string,
|
|
205
|
+
targets: QueryResetTarget[],
|
|
206
|
+
) {
|
|
207
|
+
return targets.some((target) =>
|
|
208
|
+
queryCacheKeyMatchesResetTarget(queryCacheKey, target),
|
|
209
|
+
);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/*
|
|
213
|
+
* Remove targets that duplicate an earlier one by value. Structured targets are
|
|
214
|
+
* plain objects, so they need stable value identities for deduplication.
|
|
215
|
+
*/
|
|
216
|
+
|
|
217
|
+
export function dedupeQueryResetTargets(targets: QueryResetTarget[]) {
|
|
218
|
+
const seenIds = new Set<string>();
|
|
219
|
+
|
|
220
|
+
return targets.filter((target) => {
|
|
221
|
+
const targetId = getQueryResetTargetId(target);
|
|
222
|
+
if (seenIds.has(targetId)) {
|
|
223
|
+
return false;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
seenIds.add(targetId);
|
|
227
|
+
return true;
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/*
|
|
232
|
+
* Build the structured reset field for websocket payload builders that measure
|
|
233
|
+
* their complete packet before publishing.
|
|
234
|
+
*/
|
|
235
|
+
|
|
236
|
+
export function buildResetQueryPayloadFields(
|
|
237
|
+
targets?: QueryResetTarget[] | null,
|
|
238
|
+
) {
|
|
239
|
+
if (!targets?.length) {
|
|
240
|
+
return { resetQueries: undefined };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
resetQueries: targets,
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/*
|
|
249
|
+
* Return a stable identity string for one target. Used as the query observer
|
|
250
|
+
* event name where a single string is required; the '~' prefix keeps it from
|
|
251
|
+
* colliding with a real cache key.
|
|
252
|
+
*/
|
|
253
|
+
|
|
254
|
+
export function getQueryResetTargetId(target: QueryResetTarget) {
|
|
255
|
+
const matchEntries = Object.entries(target.match || {});
|
|
256
|
+
|
|
257
|
+
if (!matchEntries.length) {
|
|
258
|
+
return `~#${target.name}:`;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const matchers = matchEntries
|
|
262
|
+
.map(([variableName, value]) => `$${variableName}:${value}`)
|
|
263
|
+
.join('');
|
|
264
|
+
|
|
265
|
+
return `~#${target.name}:${matchers}`;
|
|
266
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import type { MaybePromise } from './promise.ts';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Run one asynchronous task on a recurring start-to-start cadence without
|
|
5
|
+
* allowing executions to overlap. Errors are delegated safely and never stop
|
|
6
|
+
* future attempts; the returned idempotent function cancels the next attempt.
|
|
7
|
+
*/
|
|
8
|
+
export function startAsyncRecurringTask(
|
|
9
|
+
task: () => MaybePromise<unknown>,
|
|
10
|
+
intervalMs: number,
|
|
11
|
+
onError: (error: unknown) => MaybePromise<unknown>,
|
|
12
|
+
): () => void {
|
|
13
|
+
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
|
|
14
|
+
throw new TypeError('Recurring task interval must be a positive number.');
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
let stopped = false;
|
|
18
|
+
let timeoutId: ReturnType<typeof setTimeout> | null = null;
|
|
19
|
+
|
|
20
|
+
/*
|
|
21
|
+
* Schedule the next attempt only while this recurring task remains active.
|
|
22
|
+
*/
|
|
23
|
+
const schedule = (delayMs: number) => {
|
|
24
|
+
if (!stopped) {
|
|
25
|
+
timeoutId = setTimeout(run, delayMs);
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
/*
|
|
30
|
+
* Settle one attempt before scheduling the next start on the same cadence.
|
|
31
|
+
*/
|
|
32
|
+
const run = async () => {
|
|
33
|
+
timeoutId = null;
|
|
34
|
+
const startedAt = performance.now();
|
|
35
|
+
try {
|
|
36
|
+
await task();
|
|
37
|
+
} catch (error) {
|
|
38
|
+
try {
|
|
39
|
+
void Promise.resolve(onError(error)).catch(() => {});
|
|
40
|
+
} catch {
|
|
41
|
+
// Diagnostics must never break task scheduling.
|
|
42
|
+
}
|
|
43
|
+
} finally {
|
|
44
|
+
schedule(Math.max(0, intervalMs - (performance.now() - startedAt)));
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
schedule(intervalMs);
|
|
49
|
+
|
|
50
|
+
/*
|
|
51
|
+
* Stop future attempts without interrupting an already-running task.
|
|
52
|
+
*/
|
|
53
|
+
return () => {
|
|
54
|
+
stopped = true;
|
|
55
|
+
if (timeoutId !== null) {
|
|
56
|
+
clearTimeout(timeoutId);
|
|
57
|
+
timeoutId = null;
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pruning-only object schemas.
|
|
3
|
+
*
|
|
4
|
+
* A schema describes the shape a plain object is expected to have, and
|
|
5
|
+
* pruneToSchema() removes everything that does not match it. Nothing is ever
|
|
6
|
+
* rejected wholesale and nothing ever throws: a value that fails its node is
|
|
7
|
+
* dropped, and the surrounding object survives without that key. The worst
|
|
8
|
+
* outcome for a completely foreign value is an empty object.
|
|
9
|
+
*
|
|
10
|
+
* This exists for data that crosses a version boundary the code cannot
|
|
11
|
+
* control (persisted drafts, restored local state, third-party payloads),
|
|
12
|
+
* where an old shape reaching React is a crash and dropping it is not.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export type DraftSchemaPrimitive = 'any' | 'boolean' | 'number' | 'string';
|
|
16
|
+
|
|
17
|
+
export type DraftSchemaExplicitNode =
|
|
18
|
+
| { type: 'any' }
|
|
19
|
+
| { type: 'array'; maxLength?: number; of: DraftSchemaNode }
|
|
20
|
+
| { type: 'boolean' }
|
|
21
|
+
| { type: 'number'; integer?: boolean; max?: number; min?: number }
|
|
22
|
+
| { type: 'object'; shape: DraftSchema }
|
|
23
|
+
| { type: 'string'; maxLength?: number; oneOf?: readonly string[] };
|
|
24
|
+
|
|
25
|
+
export type DraftSchemaNode =
|
|
26
|
+
| DraftSchemaPrimitive
|
|
27
|
+
| DraftSchemaExplicitNode
|
|
28
|
+
// Shorthand for { type: 'object', shape }
|
|
29
|
+
| DraftSchema
|
|
30
|
+
// Shorthand for { type: 'array', of }
|
|
31
|
+
| [DraftSchemaNode];
|
|
32
|
+
|
|
33
|
+
export interface DraftSchema {
|
|
34
|
+
[key: string]: DraftSchemaNode;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const SCHEMA_CONSTANTS = {
|
|
38
|
+
nodeTypes: ['any', 'array', 'boolean', 'number', 'object', 'string'],
|
|
39
|
+
// Keys an explicit node is allowed to carry; a foreign key means the object
|
|
40
|
+
// is a nested shape that happens to have a "type" field of its own
|
|
41
|
+
nodeOptionKeys: [
|
|
42
|
+
'type',
|
|
43
|
+
'integer',
|
|
44
|
+
'max',
|
|
45
|
+
'maxLength',
|
|
46
|
+
'min',
|
|
47
|
+
'of',
|
|
48
|
+
'oneOf',
|
|
49
|
+
'shape',
|
|
50
|
+
],
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Check whether a value is a plain object (excludes arrays, Date, Map, class
|
|
55
|
+
* instances, and null), which is the only thing an object node accepts.
|
|
56
|
+
*/
|
|
57
|
+
|
|
58
|
+
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
|
59
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const prototype = Object.getPrototypeOf(value);
|
|
64
|
+
return prototype === Object.prototype || prototype === null;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Resolve one schema node to its explicit form, expanding the nested-shape and
|
|
69
|
+
* array shorthands.
|
|
70
|
+
*
|
|
71
|
+
* An object is read as an explicit node only when its "type" names a known
|
|
72
|
+
* node type and every other key is a valid option for a node; anything else is
|
|
73
|
+
* a nested shape. That keeps a shape like { type: 'string', name: 'string' }
|
|
74
|
+
* readable as a shape. The one shorthand this cannot express is a shape whose
|
|
75
|
+
* only key is "type" — write { type: 'object', shape: { type: 'string' } } for
|
|
76
|
+
* that case.
|
|
77
|
+
*/
|
|
78
|
+
|
|
79
|
+
function normalizeSchemaNode(
|
|
80
|
+
node: DraftSchemaNode,
|
|
81
|
+
): DraftSchemaExplicitNode | null {
|
|
82
|
+
if (typeof node === 'string') {
|
|
83
|
+
return SCHEMA_CONSTANTS.nodeTypes.includes(node)
|
|
84
|
+
? ({ type: node } as DraftSchemaExplicitNode)
|
|
85
|
+
: null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (Array.isArray(node)) {
|
|
89
|
+
return node.length ? { type: 'array', of: node[0] } : null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (!isPlainObject(node)) {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
const nodeType = (node as any).type;
|
|
97
|
+
if (
|
|
98
|
+
typeof nodeType === 'string' &&
|
|
99
|
+
SCHEMA_CONSTANTS.nodeTypes.includes(nodeType)
|
|
100
|
+
) {
|
|
101
|
+
const hasForeignKey = Object.keys(node).some(
|
|
102
|
+
(key) => !SCHEMA_CONSTANTS.nodeOptionKeys.includes(key),
|
|
103
|
+
);
|
|
104
|
+
if (!hasForeignKey) {
|
|
105
|
+
return node as DraftSchemaExplicitNode;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return { type: 'object', shape: node as DraftSchema };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Prune one value against one schema node.
|
|
114
|
+
*
|
|
115
|
+
* Returns whether the value survives, plus the (possibly rewritten) value.
|
|
116
|
+
* null passes every node as an explicit "no value"; undefined never survives.
|
|
117
|
+
*/
|
|
118
|
+
|
|
119
|
+
function pruneSchemaValue(
|
|
120
|
+
value: unknown,
|
|
121
|
+
node: DraftSchemaNode,
|
|
122
|
+
): { keep: boolean; value: unknown } {
|
|
123
|
+
if (value === undefined) {
|
|
124
|
+
return { keep: false, value: undefined };
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
const explicitNode = normalizeSchemaNode(node);
|
|
128
|
+
if (!explicitNode) {
|
|
129
|
+
return { keep: false, value: undefined };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (value === null) {
|
|
133
|
+
return { keep: true, value: null };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
switch (explicitNode.type) {
|
|
137
|
+
case 'any':
|
|
138
|
+
return { keep: true, value };
|
|
139
|
+
|
|
140
|
+
case 'string': {
|
|
141
|
+
if (typeof value !== 'string') {
|
|
142
|
+
return { keep: false, value: undefined };
|
|
143
|
+
}
|
|
144
|
+
if (explicitNode.oneOf && !explicitNode.oneOf.includes(value)) {
|
|
145
|
+
return { keep: false, value: undefined };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const maxLength = explicitNode.maxLength;
|
|
149
|
+
return {
|
|
150
|
+
keep: true,
|
|
151
|
+
value:
|
|
152
|
+
typeof maxLength === 'number' && value.length > maxLength
|
|
153
|
+
? value.substring(0, maxLength)
|
|
154
|
+
: value,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
case 'number': {
|
|
159
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
160
|
+
return { keep: false, value: undefined };
|
|
161
|
+
}
|
|
162
|
+
if (explicitNode.integer && !Number.isInteger(value)) {
|
|
163
|
+
return { keep: false, value: undefined };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Out-of-range numbers are dropped rather than clamped; clamping
|
|
167
|
+
// would invent a value the writer never had
|
|
168
|
+
if (typeof explicitNode.min === 'number' && value < explicitNode.min) {
|
|
169
|
+
return { keep: false, value: undefined };
|
|
170
|
+
}
|
|
171
|
+
if (typeof explicitNode.max === 'number' && value > explicitNode.max) {
|
|
172
|
+
return { keep: false, value: undefined };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
return { keep: true, value };
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
case 'boolean':
|
|
179
|
+
return typeof value === 'boolean'
|
|
180
|
+
? { keep: true, value }
|
|
181
|
+
: { keep: false, value: undefined };
|
|
182
|
+
|
|
183
|
+
case 'object': {
|
|
184
|
+
if (!isPlainObject(value)) {
|
|
185
|
+
return { keep: false, value: undefined };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// An object whose keys all fail still survives as {}; merging with a
|
|
189
|
+
// default value fills it back in at read time
|
|
190
|
+
return { keep: true, value: pruneSchemaShape(value, explicitNode.shape) };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
case 'array': {
|
|
194
|
+
if (!Array.isArray(value)) {
|
|
195
|
+
return { keep: false, value: undefined };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const prunedItems: unknown[] = [];
|
|
199
|
+
for (const item of value) {
|
|
200
|
+
const prunedItem = pruneSchemaValue(item, explicitNode.of);
|
|
201
|
+
if (prunedItem.keep) {
|
|
202
|
+
prunedItems.push(prunedItem.value);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (
|
|
206
|
+
typeof explicitNode.maxLength === 'number' &&
|
|
207
|
+
prunedItems.length >= explicitNode.maxLength
|
|
208
|
+
) {
|
|
209
|
+
break;
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return { keep: true, value: prunedItems };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
default:
|
|
217
|
+
return { keep: false, value: undefined };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Prune every key of one plain object against one schema shape. Keys absent
|
|
223
|
+
* from the schema are dropped.
|
|
224
|
+
*/
|
|
225
|
+
|
|
226
|
+
function pruneSchemaShape(
|
|
227
|
+
value: Record<string, unknown>,
|
|
228
|
+
schema: DraftSchema,
|
|
229
|
+
): Record<string, unknown> {
|
|
230
|
+
const pruned: Record<string, unknown> = {};
|
|
231
|
+
|
|
232
|
+
for (const key in schema) {
|
|
233
|
+
if (!Object.hasOwn(schema, key) || !Object.hasOwn(value, key)) {
|
|
234
|
+
continue;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const prunedValue = pruneSchemaValue(value[key], schema[key]);
|
|
238
|
+
if (prunedValue.keep) {
|
|
239
|
+
pruned[key] = prunedValue.value;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
return pruned;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* Prune one value against one schema, keeping only what matches.
|
|
248
|
+
*
|
|
249
|
+
* Returns null when the value is not a plain object, since a schema describes
|
|
250
|
+
* a shape and there is nothing to keep from a value that has none.
|
|
251
|
+
*/
|
|
252
|
+
|
|
253
|
+
export function pruneToSchema<T = Record<string, unknown>>(
|
|
254
|
+
value: unknown,
|
|
255
|
+
schema: DraftSchema,
|
|
256
|
+
): T | null {
|
|
257
|
+
if (!isPlainObject(value)) {
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
return pruneSchemaShape(value, schema) as T;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Merge a pruned value over its default value.
|
|
266
|
+
*
|
|
267
|
+
* Plain objects merge key by key so a field dropped during pruning falls back
|
|
268
|
+
* to its default instead of arriving undefined. Arrays and every other value
|
|
269
|
+
* replace the default outright: a persisted list is authoritative, including
|
|
270
|
+
* when it is empty.
|
|
271
|
+
*/
|
|
272
|
+
|
|
273
|
+
export function mergeSchemaDefaults<T>(value: unknown, defaultValue: T): T {
|
|
274
|
+
if (value === undefined) {
|
|
275
|
+
return defaultValue;
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
if (!isPlainObject(value) || !isPlainObject(defaultValue)) {
|
|
279
|
+
return value as T;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const merged: Record<string, unknown> = { ...defaultValue };
|
|
283
|
+
for (const key in value) {
|
|
284
|
+
if (Object.hasOwn(value, key)) {
|
|
285
|
+
merged[key] = mergeSchemaDefaults(
|
|
286
|
+
value[key],
|
|
287
|
+
(defaultValue as Record<string, unknown>)[key],
|
|
288
|
+
);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
return merged as T;
|
|
293
|
+
}
|