@ckeditor/ckeditor5-watchdog 0.0.0-internal-20241017.0

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.
@@ -0,0 +1,233 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
7
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
8
+ */
9
+ /**
10
+ * @module watchdog/watchdog
11
+ */
12
+ import type { CKEditorError } from 'ckeditor5/src/utils.js';
13
+ import type { EditorWatchdogRestartEvent } from './editorwatchdog.js';
14
+ import type { ContextWatchdogItemErrorEvent, ContextWatchdogItemRestartEvent } from './contextwatchdog.js';
15
+ /**
16
+ * An abstract watchdog class that handles most of the error handling process and the state of the underlying component.
17
+ *
18
+ * See the {@glink features/watchdog Watchdog feature guide} to learn the rationale behind it and how to use it.
19
+ *
20
+ * @internal
21
+ */
22
+ export default abstract class Watchdog {
23
+ /**
24
+ * An array of crashes saved as an object with the following properties:
25
+ *
26
+ * * `message`: `String`,
27
+ * * `stack`: `String`,
28
+ * * `date`: `Number`,
29
+ * * `filename`: `String | undefined`,
30
+ * * `lineno`: `Number | undefined`,
31
+ * * `colno`: `Number | undefined`,
32
+ */
33
+ readonly crashes: Array<{
34
+ message: string;
35
+ stack?: string;
36
+ date: number;
37
+ filename?: string;
38
+ lineno?: number;
39
+ colno?: number;
40
+ }>;
41
+ /**
42
+ * Specifies the state of the item watched by the watchdog. The state can be one of the following values:
43
+ *
44
+ * * `initializing` &ndash; Before the first initialization, and after crashes, before the item is ready.
45
+ * * `ready` &ndash; A state when the user can interact with the item.
46
+ * * `crashed` &ndash; A state when an error occurs. It quickly changes to `initializing` or `crashedPermanently`
47
+ * depending on how many and how frequent errors have been caught recently.
48
+ * * `crashedPermanently` &ndash; A state when the watchdog stops reacting to errors and keeps the item it is watching crashed,
49
+ * * `destroyed` &ndash; A state when the item is manually destroyed by the user after calling `watchdog.destroy()`.
50
+ */
51
+ state: WatchdogState;
52
+ /**
53
+ * @see module:watchdog/watchdog~WatchdogConfig
54
+ */
55
+ private _crashNumberLimit;
56
+ /**
57
+ * Returns the result of the `Date.now()` call. It can be overridden in tests to mock time as some popular
58
+ * approaches like `sinon.useFakeTimers()` do not work well with error handling.
59
+ */
60
+ private _now;
61
+ /**
62
+ * @see module:watchdog/watchdog~WatchdogConfig
63
+ */
64
+ private _minimumNonErrorTimePeriod;
65
+ /**
66
+ * Checks if the event error comes from the underlying item and restarts the item.
67
+ */
68
+ private _boundErrorHandler;
69
+ /**
70
+ * The method responsible for restarting the watched item.
71
+ */
72
+ protected abstract _restart(): Promise<unknown>;
73
+ /**
74
+ * Traverses the error context and the watched item to find out whether the error should
75
+ * be handled by the given item.
76
+ *
77
+ * @internal
78
+ */
79
+ abstract _isErrorComingFromThisItem(error: CKEditorError): boolean;
80
+ /**
81
+ * The watched item.
82
+ *
83
+ * @internal
84
+ */
85
+ abstract get _item(): unknown;
86
+ /**
87
+ * A dictionary of event emitter listeners.
88
+ */
89
+ private _listeners;
90
+ /**
91
+ * @param {module:watchdog/watchdog~WatchdogConfig} config The watchdog plugin configuration.
92
+ */
93
+ constructor(config: WatchdogConfig);
94
+ /**
95
+ * Destroys the watchdog and releases the resources.
96
+ */
97
+ destroy(): void;
98
+ /**
99
+ * Starts listening to a specific event name by registering a callback that will be executed
100
+ * whenever an event with a given name fires.
101
+ *
102
+ * Note that this method differs from the CKEditor 5's default `EventEmitterMixin` implementation.
103
+ *
104
+ * @param eventName The event name.
105
+ * @param callback A callback which will be added to event listeners.
106
+ */
107
+ on<K extends keyof EventMap>(eventName: K, callback: EventCallback<K>): void;
108
+ /**
109
+ * Stops listening to the specified event name by removing the callback from event listeners.
110
+ *
111
+ * Note that this method differs from the CKEditor 5's default `EventEmitterMixin` implementation.
112
+ *
113
+ * @param eventName The event name.
114
+ * @param callback A callback which will be removed from event listeners.
115
+ */
116
+ off(eventName: keyof EventMap, callback: unknown): void;
117
+ /**
118
+ * Fires an event with a given event name and arguments.
119
+ *
120
+ * Note that this method differs from the CKEditor 5's default `EventEmitterMixin` implementation.
121
+ */
122
+ protected _fire<K extends keyof EventMap>(eventName: K, ...args: EventArgs<K>): void;
123
+ /**
124
+ * Starts error handling by attaching global error handlers.
125
+ */
126
+ protected _startErrorHandling(): void;
127
+ /**
128
+ * Stops error handling by detaching global error handlers.
129
+ */
130
+ protected _stopErrorHandling(): void;
131
+ /**
132
+ * Checks if an error comes from the watched item and restarts it.
133
+ * It reacts to {@link module:utils/ckeditorerror~CKEditorError `CKEditorError` errors} only.
134
+ *
135
+ * @fires error
136
+ * @param error Error.
137
+ * @param evt An error event.
138
+ */
139
+ private _handleError;
140
+ /**
141
+ * Checks whether an error should be handled by the watchdog.
142
+ *
143
+ * @param error An error that was caught by the error handling process.
144
+ */
145
+ private _shouldReactToError;
146
+ /**
147
+ * Checks if the watchdog should restart the underlying item.
148
+ */
149
+ private _shouldRestart;
150
+ }
151
+ /**
152
+ * Fired when a new {@link module:utils/ckeditorerror~CKEditorError `CKEditorError`} error connected to the watchdog instance occurs
153
+ * and the watchdog will react to it.
154
+ *
155
+ * ```ts
156
+ * watchdog.on( 'error', ( evt, { error, causesRestart } ) => {
157
+ * console.log( 'An error occurred.' );
158
+ * } );
159
+ * ```
160
+ *
161
+ * @eventName ~Watchdog#error
162
+ */
163
+ export type WatchdogErrorEvent = {
164
+ name: 'error';
165
+ args: [WatchdogErrorEventData];
166
+ };
167
+ /**
168
+ * The `error` event data.
169
+ */
170
+ export type WatchdogErrorEventData = {
171
+ error: Error;
172
+ causesRestart: boolean;
173
+ };
174
+ /**
175
+ * Fired when the watchdog state changed.
176
+ *
177
+ * @eventName ~Watchdog#stateChange
178
+ */
179
+ export type WatchdogStateChangeEvent = {
180
+ name: 'stateChange';
181
+ args: [];
182
+ };
183
+ /**
184
+ * The map of watchdog events.
185
+ */
186
+ export interface EventMap {
187
+ stateChange: WatchdogStateChangeEvent;
188
+ error: WatchdogErrorEvent;
189
+ restart: EditorWatchdogRestartEvent;
190
+ itemError: ContextWatchdogItemErrorEvent;
191
+ itemRestart: ContextWatchdogItemRestartEvent;
192
+ }
193
+ /**
194
+ * Utility type that gets the arguments type for the given event.
195
+ */
196
+ export type EventArgs<K extends keyof EventMap> = EventMap[K]['args'];
197
+ /**
198
+ * Utility type that gets the callback type for the given event.
199
+ */
200
+ export type EventCallback<K extends keyof EventMap> = (evt: null, ...args: EventArgs<K>) => void;
201
+ /**
202
+ * The watchdog plugin configuration.
203
+ */
204
+ export interface WatchdogConfig {
205
+ /**
206
+ * A threshold specifying the number of watched item crashes
207
+ * when the watchdog stops restarting the item in case of errors.
208
+ * After this limit is reached and the time between the last errors is shorter than `minimumNonErrorTimePeriod`,
209
+ * the watchdog changes its state to `crashedPermanently` and it stops restarting the item. This prevents an infinite restart loop.
210
+ *
211
+ * @default 3
212
+ */
213
+ crashNumberLimit?: number;
214
+ /**
215
+ * An average number of milliseconds between the last watched item errors
216
+ * (defaults to 5000). When the period of time between errors is lower than that and the `crashNumberLimit` is also reached,
217
+ * the watchdog changes its state to `crashedPermanently` and it stops restarting the item. This prevents an infinite restart loop.
218
+ *
219
+ * @default 5000
220
+ */
221
+ minimumNonErrorTimePeriod?: number;
222
+ /**
223
+ * A minimum number of milliseconds between saving the editor data internally (defaults to 5000).
224
+ * Note that for large documents this might impact the editor performance.
225
+ *
226
+ * @default 5000
227
+ */
228
+ saveInterval?: number;
229
+ }
230
+ /**
231
+ * Specifies the state of the item watched by the watchdog.
232
+ */
233
+ export type WatchdogState = 'initializing' | 'ready' | 'crashed' | 'crashedPermanently' | 'destroyed';
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@ckeditor/ckeditor5-watchdog",
3
+ "version": "0.0.0-internal-20241017.0",
4
+ "description": "A watchdog feature for CKEditor 5 editors. It keeps a CKEditor 5 editor instance running.",
5
+ "keywords": [
6
+ "ckeditor",
7
+ "ckeditor5",
8
+ "ckeditor 5",
9
+ "ckeditor5-lib",
10
+ "ckeditor5-dll"
11
+ ],
12
+ "type": "module",
13
+ "main": "src/index.js",
14
+ "dependencies": {
15
+ "lodash-es": "4.17.21"
16
+ },
17
+ "author": "CKSource (http://cksource.com/)",
18
+ "license": "GPL-2.0-or-later",
19
+ "homepage": "https://ckeditor.com/ckeditor-5",
20
+ "bugs": "https://github.com/ckeditor/ckeditor5/issues",
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "https://github.com/ckeditor/ckeditor5.git",
24
+ "directory": "packages/ckeditor5-watchdog"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "lang",
29
+ "src/**/*.js",
30
+ "src/**/*.d.ts",
31
+ "theme",
32
+ "ckeditor5-metadata.json",
33
+ "CHANGELOG.md"
34
+ ],
35
+ "types": "src/index.d.ts"
36
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ import type { EditorData } from './editorwatchdog.js';
6
+ declare module '@ckeditor/ckeditor5-core' {
7
+ interface EditorConfig {
8
+ /**
9
+ * The temporary property that is used for passing data to the plugin which restores the editor state.
10
+ *
11
+ * @internal
12
+ */
13
+ _watchdogInitialData?: EditorData;
14
+ }
15
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ export {};
@@ -0,0 +1,333 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module watchdog/contextwatchdog
7
+ */
8
+ import type { Context, Editor, EditorConfig, ContextConfig } from 'ckeditor5/src/core.js';
9
+ import type { ArrayOrItem, CKEditorError } from 'ckeditor5/src/utils.js';
10
+ import Watchdog, { type WatchdogConfig, type WatchdogState } from './watchdog.js';
11
+ import EditorWatchdog, { type EditorCreatorFunction } from './editorwatchdog.js';
12
+ /**
13
+ * A watchdog for the {@link module:core/context~Context} class.
14
+ *
15
+ * See the {@glink features/watchdog Watchdog feature guide} to learn the rationale behind it and
16
+ * how to use it.
17
+ */
18
+ export default class ContextWatchdog<TContext extends Context = Context> extends Watchdog {
19
+ /**
20
+ * A map of internal watchdogs for added items.
21
+ */
22
+ protected _watchdogs: Map<string, EditorWatchdog<Editor>>;
23
+ /**
24
+ * The watchdog configuration.
25
+ */
26
+ private readonly _watchdogConfig;
27
+ /**
28
+ * The current context instance.
29
+ */
30
+ private _context;
31
+ /**
32
+ * Context properties (nodes/references) that are gathered during the initial context creation
33
+ * and are used to distinguish the origin of an error.
34
+ */
35
+ private _contextProps;
36
+ /**
37
+ * An action queue, which is used to handle async functions queuing.
38
+ */
39
+ private _actionQueues;
40
+ /**
41
+ * The configuration for the {@link module:core/context~Context}.
42
+ */
43
+ private _contextConfig?;
44
+ /**
45
+ * The creation method.
46
+ *
47
+ * @see #setCreator
48
+ */
49
+ protected _creator: (config: ContextConfig) => Promise<TContext>;
50
+ /**
51
+ * The destruction method.
52
+ *
53
+ * @see #setDestructor
54
+ */
55
+ protected _destructor: (context: Context) => Promise<unknown>;
56
+ /**
57
+ * The watched item.
58
+ */
59
+ _item: unknown;
60
+ /**
61
+ * The context watchdog class constructor.
62
+ *
63
+ * ```ts
64
+ * const watchdog = new ContextWatchdog( Context );
65
+ *
66
+ * await watchdog.create( contextConfiguration );
67
+ *
68
+ * await watchdog.add( item );
69
+ * ```
70
+ *
71
+ * See the {@glink features/watchdog Watchdog feature guide} to learn more how to use this feature.
72
+ *
73
+ * @param Context The {@link module:core/context~Context} class.
74
+ * @param watchdogConfig The watchdog configuration.
75
+ */
76
+ constructor(Context: {
77
+ create(...args: any): Promise<TContext>;
78
+ }, watchdogConfig?: WatchdogConfig);
79
+ /**
80
+ * Sets the function that is responsible for the context creation.
81
+ * It expects a function that should return a promise (or `undefined`).
82
+ *
83
+ * ```ts
84
+ * watchdog.setCreator( config => Context.create( config ) );
85
+ * ```
86
+ */
87
+ setCreator(creator: (config: ContextConfig) => Promise<TContext>): void;
88
+ /**
89
+ * Sets the function that is responsible for the context destruction.
90
+ * Overrides the default destruction function, which destroys only the context instance.
91
+ * It expects a function that should return a promise (or `undefined`).
92
+ *
93
+ * ```ts
94
+ * watchdog.setDestructor( context => {
95
+ * // Do something before the context is destroyed.
96
+ *
97
+ * return context
98
+ * .destroy()
99
+ * .then( () => {
100
+ * // Do something after the context is destroyed.
101
+ * } );
102
+ * } );
103
+ * ```
104
+ */
105
+ setDestructor(destructor: (context: Context) => Promise<unknown>): void;
106
+ /**
107
+ * The context instance. Keep in mind that this property might be changed when the context watchdog restarts,
108
+ * so do not keep this instance internally. Always operate on the `ContextWatchdog#context` property.
109
+ */
110
+ get context(): Context | null;
111
+ /**
112
+ * Initializes the context watchdog. Once it is created, the watchdog takes care about
113
+ * recreating the context and the provided items, and starts the error handling mechanism.
114
+ *
115
+ * ```ts
116
+ * await watchdog.create( {
117
+ * plugins: []
118
+ * } );
119
+ * ```
120
+ *
121
+ * @param contextConfig The context configuration. See {@link module:core/context~Context}.
122
+ */
123
+ create(contextConfig?: ContextConfig): Promise<unknown>;
124
+ /**
125
+ * Returns an item instance with the given `itemId`.
126
+ *
127
+ * ```ts
128
+ * const editor1 = watchdog.getItem( 'editor1' );
129
+ * ```
130
+ *
131
+ * @param itemId The item ID.
132
+ * @returns The item instance or `undefined` if an item with a given ID has not been found.
133
+ */
134
+ getItem(itemId: string): unknown;
135
+ /**
136
+ * Gets the state of the given item. See {@link #state} for a list of available states.
137
+ *
138
+ * ```ts
139
+ * const editor1State = watchdog.getItemState( 'editor1' );
140
+ * ```
141
+ *
142
+ * @param itemId Item ID.
143
+ * @returns The state of the item.
144
+ */
145
+ getItemState(itemId: string): WatchdogState;
146
+ /**
147
+ * Adds items to the watchdog. Once created, instances of these items will be available using the {@link #getItem} method.
148
+ *
149
+ * Items can be passed together as an array of objects:
150
+ *
151
+ * ```ts
152
+ * await watchdog.add( [ {
153
+ * id: 'editor1',
154
+ * type: 'editor',
155
+ * sourceElementOrData: document.querySelector( '#editor' ),
156
+ * config: {
157
+ * plugins: [ Essentials, Paragraph, Bold, Italic ],
158
+ * toolbar: [ 'bold', 'italic', 'alignment' ]
159
+ * },
160
+ * creator: ( element, config ) => ClassicEditor.create( element, config )
161
+ * } ] );
162
+ * ```
163
+ *
164
+ * Or one by one as objects:
165
+ *
166
+ * ```ts
167
+ * await watchdog.add( {
168
+ * id: 'editor1',
169
+ * type: 'editor',
170
+ * sourceElementOrData: document.querySelector( '#editor' ),
171
+ * config: {
172
+ * plugins: [ Essentials, Paragraph, Bold, Italic ],
173
+ * toolbar: [ 'bold', 'italic', 'alignment' ]
174
+ * },
175
+ * creator: ( element, config ) => ClassicEditor.create( element, config )
176
+ * ] );
177
+ * ```
178
+ *
179
+ * Then an instance can be retrieved using the {@link #getItem} method:
180
+ *
181
+ * ```ts
182
+ * const editor1 = watchdog.getItem( 'editor1' );
183
+ * ```
184
+ *
185
+ * Note that this method can be called multiple times, but for performance reasons it is better
186
+ * to pass all items together.
187
+ *
188
+ * @param itemConfigurationOrItemConfigurations An item configuration object or an array of item configurations.
189
+ */
190
+ add(itemConfigurationOrItemConfigurations: ArrayOrItem<WatchdogItemConfiguration>): Promise<unknown>;
191
+ /**
192
+ * Removes and destroys item(s) with given ID(s).
193
+ *
194
+ * ```ts
195
+ * await watchdog.remove( 'editor1' );
196
+ * ```
197
+ *
198
+ * Or
199
+ *
200
+ * ```ts
201
+ * await watchdog.remove( [ 'editor1', 'editor2' ] );
202
+ * ```
203
+ *
204
+ * @param itemIdOrItemIds Item ID or an array of item IDs.
205
+ */
206
+ remove(itemIdOrItemIds: ArrayOrItem<string>): Promise<unknown>;
207
+ /**
208
+ * Destroys the context watchdog and all added items.
209
+ * Once the context watchdog is destroyed, new items cannot be added.
210
+ *
211
+ * ```ts
212
+ * await watchdog.destroy();
213
+ * ```
214
+ */
215
+ destroy(): Promise<unknown>;
216
+ /**
217
+ * Restarts the context watchdog.
218
+ */
219
+ protected _restart(): Promise<unknown>;
220
+ /**
221
+ * Initializes the context watchdog.
222
+ */
223
+ private _create;
224
+ /**
225
+ * Destroys the context instance and all added items.
226
+ */
227
+ private _destroy;
228
+ /**
229
+ * Returns the watchdog for a given item ID.
230
+ *
231
+ * @param itemId Item ID.
232
+ */
233
+ protected _getWatchdog(itemId: string): Watchdog;
234
+ /**
235
+ * Checks whether an error comes from the context instance and not from the item instances.
236
+ *
237
+ * @internal
238
+ */
239
+ _isErrorComingFromThisItem(error: CKEditorError): boolean;
240
+ }
241
+ /**
242
+ * Fired after the watchdog restarts the context and the added items because of a crash.
243
+ *
244
+ * ```ts
245
+ * watchdog.on( 'restart', () => {
246
+ * console.log( 'The context has been restarted.' );
247
+ * } );
248
+ * ```
249
+ *
250
+ * @eventName ~ContextWatchdog#restart
251
+ */
252
+ export type ContextWatchdogRestartEvent = {
253
+ name: 'restart';
254
+ args: [];
255
+ return: undefined;
256
+ };
257
+ /**
258
+ * Fired when a new error occurred in one of the added items.
259
+ *
260
+ * ```ts
261
+ * watchdog.on( 'itemError', ( evt, { error, itemId } ) => {
262
+ * console.log( `An error occurred in an item with the '${ itemId }' ID.` );
263
+ * } );
264
+ * ```
265
+ *
266
+ * @eventName ~ContextWatchdog#itemError
267
+ */
268
+ export type ContextWatchdogItemErrorEvent = {
269
+ name: 'itemError';
270
+ args: [ContextWatchdogItemErrorEventData];
271
+ return: undefined;
272
+ };
273
+ /**
274
+ * The `itemError` event data.
275
+ */
276
+ export type ContextWatchdogItemErrorEventData = {
277
+ itemId: string;
278
+ error: Error;
279
+ };
280
+ /**
281
+ * Fired after an item has been restarted.
282
+ *
283
+ * ```ts
284
+ * watchdog.on( 'itemRestart', ( evt, { itemId } ) => {
285
+ * console.log( 'An item with with the '${ itemId }' ID has been restarted.' );
286
+ * } );
287
+ * ```
288
+ *
289
+ * @eventName ~ContextWatchdog#itemRestart
290
+ */
291
+ export type ContextWatchdogItemRestartEvent = {
292
+ name: 'itemRestart';
293
+ args: [ContextWatchdogItemRestartEventData];
294
+ return: undefined;
295
+ };
296
+ /**
297
+ * The `itemRestart` event data.
298
+ */
299
+ export type ContextWatchdogItemRestartEventData = {
300
+ itemId: string;
301
+ };
302
+ /**
303
+ * The watchdog item configuration interface.
304
+ */
305
+ export interface WatchdogItemConfiguration {
306
+ /**
307
+ * id A unique item identificator.
308
+ */
309
+ id: string;
310
+ /**
311
+ * The type of the item to create. At the moment, only `'editor'` is supported.
312
+ */
313
+ type: 'editor';
314
+ /**
315
+ * A function that initializes the item (the editor). The function takes editor initialization arguments
316
+ * and should return a promise. For example: `( el, config ) => ClassicEditor.create( el, config )`.
317
+ */
318
+ creator: EditorCreatorFunction;
319
+ /**
320
+ * A function that destroys the item instance (the editor). The function
321
+ * takes an item and should return a promise. For example: `editor => editor.destroy()`
322
+ */
323
+ destructor?: (editor: Editor) => Promise<unknown>;
324
+ /**
325
+ * The source element or data that will be passed
326
+ * as the first argument to the `Editor.create()` method.
327
+ */
328
+ sourceElementOrData: string | HTMLElement;
329
+ /**
330
+ * An editor configuration.
331
+ */
332
+ config: EditorConfig;
333
+ }