navi-hey 0.4.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.
Files changed (77) hide show
  1. package/bin/navi.js +9 -0
  2. package/lib/exceptions/AppError.js +13 -0
  3. package/lib/exceptions/ClientNotFound.js +16 -0
  4. package/lib/exceptions/ConfigurationFileNotFound.js +10 -0
  5. package/lib/exceptions/ConfigurationFileNotProvided.js +10 -0
  6. package/lib/exceptions/InvalidResponseBody.js +19 -0
  7. package/lib/exceptions/ItemNotFound.js +16 -0
  8. package/lib/exceptions/LockedByOtherWorker.js +14 -0
  9. package/lib/exceptions/MissingActionResource.js +13 -0
  10. package/lib/exceptions/MissingClientsConfig.js +14 -0
  11. package/lib/exceptions/MissingMappingVariable.js +17 -0
  12. package/lib/exceptions/MissingResourceConfig.js +14 -0
  13. package/lib/exceptions/MissingTopLevelConfgKey.js +15 -0
  14. package/lib/exceptions/NullResponse.js +13 -0
  15. package/lib/exceptions/RequestFailed.js +16 -0
  16. package/lib/exceptions/ResourceNotFound.js +16 -0
  17. package/lib/factories/Factory.js +79 -0
  18. package/lib/factories/JobFactory.js +82 -0
  19. package/lib/factories/WorkerFactory.js +35 -0
  20. package/lib/models/ActionEnqueuer.js +34 -0
  21. package/lib/models/ActionProcessingJob.js +51 -0
  22. package/lib/models/ActionsEnqueuer.js +42 -0
  23. package/lib/models/Config.js +68 -0
  24. package/lib/models/Job.js +87 -0
  25. package/lib/models/ParametersMapper.js +43 -0
  26. package/lib/models/PathResolver.js +77 -0
  27. package/lib/models/PathSegmentTraverser.js +82 -0
  28. package/lib/models/Resource.js +47 -0
  29. package/lib/models/ResourceRequest.js +80 -0
  30. package/lib/models/ResourceRequestAction.js +73 -0
  31. package/lib/models/ResourceRequestJob.js +61 -0
  32. package/lib/models/ResponseParser.js +36 -0
  33. package/lib/models/ResponseWrapper.js +86 -0
  34. package/lib/models/WebConfig.js +15 -0
  35. package/lib/models/Worker.js +57 -0
  36. package/lib/models/WorkersConfig.js +18 -0
  37. package/lib/registry/ClientRegistry.js +92 -0
  38. package/lib/registry/JobRegistry.js +125 -0
  39. package/lib/registry/JobRegistryInstance.js +149 -0
  40. package/lib/registry/NamedRegistry.js +73 -0
  41. package/lib/registry/ResourceRegistry.js +91 -0
  42. package/lib/registry/WorkersRegistry.js +106 -0
  43. package/lib/registry/WorkersRegistryInstance.js +139 -0
  44. package/lib/server/RequestHandler.js +15 -0
  45. package/lib/server/RouteRegister.js +27 -0
  46. package/lib/server/Router.js +44 -0
  47. package/lib/server/StatsRequestHandler.js +31 -0
  48. package/lib/server/WebServer.js +45 -0
  49. package/lib/services/Application.js +113 -0
  50. package/lib/services/ArgumentsParser.js +36 -0
  51. package/lib/services/Client.js +108 -0
  52. package/lib/services/ConfigLoader.js +75 -0
  53. package/lib/services/ConfigParser.js +131 -0
  54. package/lib/services/Engine.js +67 -0
  55. package/lib/services/WorkersAllocator.js +74 -0
  56. package/lib/utils/EnvResolver.js +53 -0
  57. package/lib/utils/PromiseAggregator.js +37 -0
  58. package/lib/utils/ResourceRequestCollector.js +35 -0
  59. package/lib/utils/collections/Collection.js +17 -0
  60. package/lib/utils/collections/IdentifyableCollection.js +86 -0
  61. package/lib/utils/collections/Queue.js +45 -0
  62. package/lib/utils/collections/SortedArrayMerger.js +84 -0
  63. package/lib/utils/collections/SortedArraySearcher.js +101 -0
  64. package/lib/utils/collections/SortedCollection.js +169 -0
  65. package/lib/utils/generators/IdGenerator.js +79 -0
  66. package/lib/utils/generators/IncrementalIdGenerator.js +25 -0
  67. package/lib/utils/generators/UUidGenerator.js +49 -0
  68. package/lib/utils/index.js +2 -0
  69. package/lib/utils/logging/BaseLogger.js +93 -0
  70. package/lib/utils/logging/BufferedLogger.js +91 -0
  71. package/lib/utils/logging/ConsoleLogger.js +19 -0
  72. package/lib/utils/logging/Log.js +70 -0
  73. package/lib/utils/logging/LogBuffer.js +101 -0
  74. package/lib/utils/logging/LogFactory.js +32 -0
  75. package/lib/utils/logging/Logger.js +134 -0
  76. package/lib/utils/logging/LoggerGroup.js +100 -0
  77. package/package.json +78 -0
@@ -0,0 +1,75 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import YAML from 'yaml';
3
+ import { ConfigParser } from './ConfigParser.js';
4
+ import { ConfigurationFileNotFound } from '../exceptions/ConfigurationFileNotFound.js';
5
+ import { Logger } from '../utils/logging/Logger.js';
6
+
7
+ /**
8
+ * ConfigLoader loads a YAML configuration file and delegates parsing to ConfigParser.
9
+ * @author darthjee
10
+ */
11
+ class ConfigLoader {
12
+ /**
13
+ * @param {string} filePath Path to the YAML configuration file.
14
+ */
15
+ constructor(filePath) {
16
+ this.filePath = filePath;
17
+ }
18
+
19
+ /**
20
+ * Creates a mapped resource object from a YAML file.
21
+ *
22
+ * The YAML must contain a top-level `resources` key.
23
+ *
24
+ * @param {string} filePath Path to the YAML configuration file.
25
+ * @returns {{
26
+ * resources: Record<string, Resource>,
27
+ * clients: Record<string, Client>,
28
+ * workers: WorkersConfig
29
+ * }} Mapped resources and clients by name. and workers configuration.
30
+ * @throws {MissingTopLevelConfigKey} Throws when the file is invalid or does not contain required keys.
31
+ * @throws {ConfigurationFileNotFound} If the configuration file is not found at the specified path.
32
+ */
33
+ static fromFile(filePath) {
34
+ return new ConfigLoader(filePath).load();
35
+ }
36
+
37
+ /**
38
+ * Reads and parses the YAML configuration file, then delegates to ConfigParser.
39
+ * @returns {{
40
+ * resources: Record<string, Resource>,
41
+ * clients: Record<string, Client>,
42
+ * workersConfig: WorkersConfig
43
+ * }} Mapped resources and clients by name. and workers configuration.
44
+ * @throws {ConfigurationFileNotFound} If the configuration file is not found at the specified path.
45
+ * @throws {MissingTopLevelConfigKey} Throws when the file is invalid or does not contain required keys.
46
+ */
47
+ load() {
48
+ return ConfigParser.fromObject(this.#parseYaml());
49
+ }
50
+
51
+ /**
52
+ * Reads and parses the raw YAML file content into a plain object.
53
+ * @returns {object} The raw parsed YAML object.
54
+ * @throws {ConfigurationFileNotFound} If the configuration file is not found at the specified path.
55
+ */
56
+ #parseYaml() {
57
+ return YAML.parse(this.#yamlContent());
58
+ }
59
+
60
+ /**
61
+ * Reads the YAML configuration file content.
62
+ * @returns {string} The content of the YAML file as a string.
63
+ * @throws {ConfigurationFileNotFound} If the configuration file is not found at the specified path.
64
+ */
65
+ #yamlContent() {
66
+ try {
67
+ return readFileSync(this.filePath, 'utf8');
68
+ } catch (err) {
69
+ Logger.error(`Configuration file not found: ${this.filePath}`);
70
+ throw new ConfigurationFileNotFound(this.filePath);
71
+ }
72
+ }
73
+ }
74
+
75
+ export { ConfigLoader };
@@ -0,0 +1,131 @@
1
+ import { Client } from './Client.js';
2
+ import { MissingClientsConfig } from '../exceptions/MissingClientsConfig.js';
3
+ import { MissingResourceConfig } from '../exceptions/MissingResourceConfig.js';
4
+ import { Resource } from '../models/Resource.js';
5
+ import { WebConfig } from '../models/WebConfig.js';
6
+ import { WorkersConfig } from '../models/WorkersConfig.js';
7
+
8
+ /**
9
+ * ConfigParser receives a parsed YAML configuration object and maps it to
10
+ * Resource and Client model instances.
11
+ * @author darthjee
12
+ */
13
+ class ConfigParser {
14
+ /**
15
+ * @param {object} config Parsed configuration object from a YAML file.
16
+ */
17
+ constructor(config) {
18
+ this.config = config;
19
+ }
20
+
21
+ /**
22
+ * Creates a mapped configuration from a plain parsed YAML object.
23
+ *
24
+ * @param {object} config Parsed configuration object from a YAML file.
25
+ * @returns {{
26
+ * resources: Record<string, Resource>,
27
+ * clients: Record<string, Client>,
28
+ * workersConfig: WorkersConfig
29
+ * }} Mapped resources and clients by name. and workers configuration.
30
+ * @throws {Error} Throws when the config is invalid or missing required keys.
31
+ */
32
+ static fromObject(config) {
33
+ return new ConfigParser(config).parse();
34
+ }
35
+
36
+ /**
37
+ * Parses the config object into a structured configuration.
38
+ * @returns {{
39
+ * resources: Record<string, Resource>,
40
+ * clients: Record<string, Client>,
41
+ * workersConfig: WorkersConfig,
42
+ * webConfig: WebConfig|null
43
+ * }} Parsed configuration with resources, clients, workersConfig, and webConfig.
44
+ */
45
+ parse() {
46
+ const mappedResources = Object.fromEntries(
47
+ this.#resourcesEntries()
48
+ );
49
+
50
+ const mappedClients = Object.fromEntries(
51
+ this.#clientsEntries()
52
+ );
53
+
54
+ return {
55
+ resources: mappedResources,
56
+ clients: mappedClients,
57
+ workersConfig: this.#workersConfig(),
58
+ webConfig: this.#webConfig(),
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Creates a WorkersConfig from the parsed YAML workers section.
64
+ * @returns {WorkersConfig} The workers configuration instance.
65
+ */
66
+ #workersConfig() {
67
+ return new WorkersConfig(this.config.workers);
68
+ }
69
+
70
+ /**
71
+ * Creates a WebConfig from the parsed YAML web section, or null if absent.
72
+ * @returns {WebConfig|null} The web configuration instance or null.
73
+ */
74
+ #webConfig() {
75
+ if (!this.config.web) return null;
76
+ return new WebConfig(this.config.web);
77
+ }
78
+
79
+ /**
80
+ * Maps the resources to entries suitable for Object.fromEntries.
81
+ * @returns {Array<Array>} Entries of resource name and Resource instance.
82
+ */
83
+ #resourcesEntries() {
84
+ return this.#loadResources().map((resource) => { return [resource.name, resource]; });
85
+ }
86
+
87
+ /**
88
+ * Maps the clients to entries suitable for Object.fromEntries.
89
+ * @returns {Array<Array>} Entries of client name and Client instance.
90
+ */
91
+ #clientsEntries() {
92
+ return this.#loadClients().map((client) => { return [client.name, client]; });
93
+ }
94
+
95
+ /**
96
+ * Validates and loads resources from the config object.
97
+ * @returns {Array<Resource>} List of Resource instances.
98
+ * @throws {MissingResourceConfig} Throws when the config does not contain a `resources` key.
99
+ */
100
+ #loadResources() {
101
+ this.#requireKey('resources', MissingResourceConfig);
102
+
103
+ return Resource.fromListObject(this.config.resources);
104
+ }
105
+
106
+ /**
107
+ * Validates and loads clients from the config object.
108
+ * @returns {Array<Client>} List of Client instances.
109
+ * @throws {MissingClientsConfig} Throws when the config does not contain a `clients` key.
110
+ */
111
+ #loadClients() {
112
+ this.#requireKey('clients', MissingClientsConfig);
113
+
114
+ return Client.fromListObject(this.config.clients);
115
+ }
116
+
117
+ /**
118
+ * Validates that the config object contains the specified key.
119
+ * @param {string} key - The key to check for.
120
+ * @param {Function} ExceptionClass - The exception class to throw if the key is missing.
121
+ * @returns {void}
122
+ * @throws {Error} Throws if the config is invalid or missing the key.
123
+ */
124
+ #requireKey(key, ExceptionClass) {
125
+ if (!this.config || typeof this.config !== 'object' || !(key in this.config)) {
126
+ throw new ExceptionClass();
127
+ }
128
+ }
129
+ }
130
+
131
+ export { ConfigParser };
@@ -0,0 +1,67 @@
1
+ import { WorkersAllocator } from './WorkersAllocator.js';
2
+ import { JobRegistry } from '../registry/JobRegistry.js';
3
+ import { WorkersRegistry } from '../registry/WorkersRegistry.js';
4
+ import { Logger } from '../utils/logging/Logger.js';
5
+
6
+ /**
7
+ * Engine is responsible for managing the job processing workflow.
8
+ *
9
+ * It continuously checks for available jobs and idle workers, and assigns
10
+ * jobs to workers until there are no more jobs and no more busy workers.
11
+ */
12
+ class Engine {
13
+ #sleepMs;
14
+
15
+ /**
16
+ * Creates an instance of Engine.
17
+ * @param {object} param0 - The parameters for creating an Engine instance.
18
+ * @param {WorkersAllocator} param0.allocator - The workers allocator to manage job allocation.
19
+ * @param {number} [param0.sleepMs=500] - Milliseconds to wait when all jobs are in cooldown. Use a negative value to disable sleeping (e.g. in tests).
20
+ */
21
+ constructor({ allocator, sleepMs = 500 } = {}) {
22
+ this.#sleepMs = sleepMs;
23
+
24
+ this.allocator = allocator || new WorkersAllocator();
25
+ }
26
+
27
+ /**
28
+ * Starts the engine by processing jobs.
29
+ *
30
+ * This method continuously checks for available jobs and idle workers, and assigns
31
+ * jobs to workers until there are no more jobs and no more busy workers.
32
+ * @returns {Promise<void>}
33
+ */
34
+ async start() {
35
+ while (this.#continueAllocating()) {
36
+ Logger.debug('Promoting ready jobs and allocating to idle workers if available...');
37
+ JobRegistry.promoteReadyJobs();
38
+
39
+ if (JobRegistry.hasReadyJob()) {
40
+ this.allocator.allocate();
41
+ }
42
+
43
+ // wait before next iteration so the block runs ~once per second
44
+ await this.#sleep();
45
+ }
46
+ }
47
+
48
+ /**
49
+ * Checks if the engine should continue allocating jobs to workers.
50
+ * @returns {boolean} True if there are jobs to process or busy workers, false otherwise.
51
+ */
52
+ #continueAllocating() {
53
+ return JobRegistry.hasJob() || WorkersRegistry.hasBusyWorker();
54
+ }
55
+
56
+ /**
57
+ * Waits for the given number of milliseconds.
58
+ * @returns {Promise<void>}
59
+ */
60
+ #sleep() {
61
+ const ms = this.#sleepMs;
62
+ if (ms < 0) return Promise.resolve();
63
+ return new Promise(resolve => setTimeout(resolve, ms));
64
+ }
65
+ }
66
+
67
+ export { Engine };
@@ -0,0 +1,74 @@
1
+ import { JobRegistry } from '../registry/JobRegistry.js';
2
+ import { WorkersRegistry } from '../registry/WorkersRegistry.js';
3
+
4
+ /**
5
+ * WorkersAllocator is responsible for allocating jobs to idle workers.
6
+ *
7
+ * It continuously checks for available jobs and idle workers, and assigns
8
+ * jobs to workers until there are no more jobs or no more idle workers.
9
+ */
10
+ class WorkersAllocator {
11
+ /**
12
+ * Creates an instance of WorkersAllocator.
13
+ */
14
+ constructor() {}
15
+
16
+ /**
17
+ * Allocates jobs to idle workers.
18
+ *
19
+ * This method continuously checks for available jobs and idle workers, and assigns
20
+ * jobs to workers until there are no more jobs or no more idle workers.
21
+ * @returns {void}
22
+ */
23
+ allocate() {
24
+ while (this._canAllocate()) {
25
+ this._allocateNext();
26
+ }
27
+ }
28
+
29
+ /**
30
+ * Allocates a single worker to a job.
31
+ *
32
+ * This method picks a job from the job registry and an idle worker from the workers registry,
33
+ * and assigns the job to the worker. If no job is available, returns immediately.
34
+ * If no idle worker is available, the job is re-enqueued.
35
+ * @returns {void}
36
+ */
37
+ _allocateNext() {
38
+ const job = JobRegistry.pick();
39
+ if (!job) return;
40
+
41
+ const worker = WorkersRegistry.getIdleWorker();
42
+ if (!worker) {
43
+ JobRegistry.requeue(job);
44
+ return;
45
+ }
46
+
47
+ this._allocateWorkerToJob(worker, job);
48
+ }
49
+
50
+ /**
51
+ * Allocates a worker to a job.
52
+ *
53
+ * This method assigns the given job to the given worker and then performs the job.
54
+ * @param {Worker} worker - The worker to allocate the job to.
55
+ * @param {Job} job - The job to be allocated to the worker.
56
+ * @returns {void}
57
+ */
58
+ _allocateWorkerToJob(worker, job) {
59
+ worker.assign(job);
60
+ worker.perform();
61
+ }
62
+
63
+ /**
64
+ * Checks if there are available jobs and idle workers to allocate.
65
+ *
66
+ * This method checks if the job registry has any jobs and if the workers registry has any idle workers.
67
+ * @returns {boolean} True if there are available jobs and idle workers, false otherwise.
68
+ */
69
+ _canAllocate() {
70
+ return WorkersRegistry.hasIdleWorker() && JobRegistry.hasReadyJob();
71
+ }
72
+ }
73
+
74
+ export { WorkersAllocator };
@@ -0,0 +1,53 @@
1
+ import { Logger } from './logging/Logger.js';
2
+
3
+ /**
4
+ * Pattern matching environment variable references in strings.
5
+ * Supports `$VAR_NAME` and `${VAR_NAME}` syntax.
6
+ * @type {RegExp}
7
+ */
8
+ const ENV_VAR_PATTERN = /\$\{([^}]+)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g;
9
+
10
+ /**
11
+ * Resolves environment variable references in string values.
12
+ *
13
+ * Supports `$VAR_NAME` and `${VAR_NAME}` syntax, resolved from
14
+ * `process.env` at call time. Logs a warning when a referenced
15
+ * variable is not defined and replaces it with an empty string.
16
+ *
17
+ * @author darthjee
18
+ */
19
+ class EnvResolver {
20
+ /**
21
+ * Resolves environment variable references in all values of an object.
22
+ *
23
+ * @param {object} object Map of keys to raw string values.
24
+ * @returns {object} A new object with env var references resolved in values.
25
+ */
26
+ static resolveObject(object) {
27
+ return Object.fromEntries(
28
+ Object.entries(object).map(([key, value]) => [key, EnvResolver.resolveValue(value)])
29
+ );
30
+ }
31
+
32
+ /**
33
+ * Resolves environment variable references in a single string value.
34
+ *
35
+ * @param {string} value Raw string value.
36
+ * @returns {string} Resolved value with env var references replaced.
37
+ */
38
+ static resolveValue(value) {
39
+ return String(value).replace(ENV_VAR_PATTERN, (_match, braced, bare) => {
40
+ const varName = braced || bare;
41
+ const resolved = process.env[varName];
42
+
43
+ if (resolved === undefined) {
44
+ Logger.warn(`Environment variable not defined: ${varName}`);
45
+ return '';
46
+ }
47
+
48
+ return resolved;
49
+ });
50
+ }
51
+ }
52
+
53
+ export { EnvResolver };
@@ -0,0 +1,37 @@
1
+ /**
2
+ * Collects promises and exposes a single wait() method that resolves
3
+ * only after all registered promises have settled.
4
+ *
5
+ * @author darthjee
6
+ */
7
+ class PromiseAggregator {
8
+ #promises = [];
9
+
10
+ /**
11
+ * Registers a promise into the collection.
12
+ * Silently ignores null and undefined values.
13
+ * @param {Promise|null|undefined} promise - The promise to add.
14
+ * @returns {void}
15
+ */
16
+ add(promise) {
17
+ if (promise === null || promise === undefined) return;
18
+ this.#promises.push(promise);
19
+ }
20
+
21
+ /**
22
+ * Waits for all registered promises to settle.
23
+ * If one or more promises reject, it still waits for the remaining
24
+ * ones and then re-throws the first rejection error.
25
+ * @returns {Promise<void>}
26
+ */
27
+ async wait() {
28
+ const results = await Promise.allSettled(this.#promises);
29
+ const firstRejection = results.find((r) => r.status === 'rejected');
30
+
31
+ if (firstRejection) {
32
+ throw firstRejection.reason;
33
+ }
34
+ }
35
+ }
36
+
37
+ export { PromiseAggregator };
@@ -0,0 +1,35 @@
1
+ /**
2
+ * ResourceRequestCollector gathers ResourceRequest instances from a ResourceRegistry.
3
+ * It provides methods to retrieve all requests or only those that do not require parameters.
4
+ * @author darthjee
5
+ */
6
+ class ResourceRequestCollector {
7
+ /**
8
+ * @param {ResourceRegistry} resourceRegistry The registry containing all resources.
9
+ */
10
+ constructor(resourceRegistry) {
11
+ this.resourceRegistry = resourceRegistry;
12
+ }
13
+
14
+ /**
15
+ * Returns a flat array of all ResourceRequest instances from all resources in the registry.
16
+ * @returns {Array<ResourceRequest>} All resource requests across every resource.
17
+ */
18
+ allRequests() {
19
+ return this.resourceRegistry
20
+ .filter(() => true)
21
+ .flatMap((resource) => resource.resourceRequests);
22
+ }
23
+
24
+ /**
25
+ * Returns only the ResourceRequest instances that do not require parameter substitution,
26
+ * i.e. those whose URL templates contain no {:placeholder} tokens.
27
+ * These are safe to enqueue at startup without any additional context.
28
+ * @returns {Array<ResourceRequest>} Resource requests that need no parameters.
29
+ */
30
+ requestsNeedingNoParams() {
31
+ return this.allRequests().filter((request) => !request.needsParams());
32
+ }
33
+ }
34
+
35
+ export { ResourceRequestCollector };
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Abstract base class for collection types.
3
+ *
4
+ * Provides shared interface methods (`hasAny`) that delegate
5
+ * to `size()`, which concrete subclasses must implement.
6
+ */
7
+ class Collection {
8
+ /**
9
+ * Checks if the collection has any items.
10
+ * @returns {boolean} True if the collection has any items, false otherwise.
11
+ */
12
+ hasAny() {
13
+ return this.size() > 0;
14
+ }
15
+ }
16
+
17
+ export { Collection };
@@ -0,0 +1,86 @@
1
+ import { Collection } from './Collection.js';
2
+
3
+ /**
4
+ * An identifiable collection that stores items keyed by their id property.
5
+ * @author darthjee
6
+ */
7
+ class IdentifyableCollection extends Collection {
8
+ #items;
9
+ #size = null;
10
+
11
+ /**
12
+ * @param {object} items - Optional initial items, keyed by id.
13
+ */
14
+ constructor(items = {}) {
15
+ super();
16
+ this.#items = items;
17
+ }
18
+
19
+ /**
20
+ * Adds an item to the collection.
21
+ * @param {object} item - The item to add, must have a unique id.
22
+ * @returns {void}
23
+ */
24
+ push(item) {
25
+ this.#size = null;
26
+ this.#items[item.id] = item;
27
+ }
28
+
29
+ /**
30
+ * Removes an item from the collection by id.
31
+ * @param {string|number} id - The id of the item to remove.
32
+ * @returns {void}
33
+ */
34
+ remove(id) {
35
+ this.#size = null;
36
+ delete this.#items[id];
37
+ }
38
+
39
+ /**
40
+ * Retrieves an item from the collection by id.
41
+ * @param {string} id - The id of the item to retrieve.
42
+ * @returns {object | undefined} - The item if found, otherwise undefined.
43
+ */
44
+ get(id) {
45
+ return this.#items[id];
46
+ }
47
+
48
+ /**
49
+ * Checks if the collection has an item with the specified id.
50
+ * @param {string|number} id - The id of the item to check.
51
+ * @returns {boolean} - True if the item exists, false otherwise.
52
+ */
53
+ has(id) {
54
+ return this.#items[id] !== undefined;
55
+ }
56
+
57
+ /**
58
+ * Retrieves an item from the collection by index.
59
+ * @param {number} index - The index of the item to retrieve.
60
+ * @returns {object | undefined} - The item if found, otherwise undefined.
61
+ */
62
+ byIndex(index) {
63
+ return this.list()[index];
64
+ }
65
+
66
+ /**
67
+ * Retrieves all items in the collection.
68
+ * @returns {object[]} - An array of all items in the collection.
69
+ */
70
+ list() {
71
+ return Object.values(this.#items);
72
+ }
73
+
74
+ /**
75
+ * Retrieves the number of items in the collection.
76
+ * @returns {number} - The number of items in the collection.
77
+ */
78
+ size() {
79
+ if (this.#size === null) {
80
+ this.#size = this.list().length;
81
+ }
82
+ return this.#size;
83
+ }
84
+ }
85
+
86
+ export { IdentifyableCollection };
@@ -0,0 +1,45 @@
1
+ import { Collection } from './Collection.js';
2
+
3
+ /**
4
+ * A simple queue implementation for managing items in a first-in-first-out (FIFO) manner.
5
+ *
6
+ * The Queue class provides methods to add items to the queue, retrieve items from the queue, and check if the queue has any items.
7
+ * It uses an array to store the items and provides a simple interface for managing the queue.
8
+ */
9
+ class Queue extends Collection {
10
+ /**
11
+ * Creates an instance of Queue.
12
+ *
13
+ * This constructor initializes an empty array to store the items in the queue.
14
+ */
15
+ constructor() {
16
+ super();
17
+ this.items = [];
18
+ }
19
+
20
+ /**
21
+ * Adds an item to the end of the queue.
22
+ * @param {*} item - The item to be added to the queue.
23
+ */
24
+ push(item) {
25
+ this.items.push(item);
26
+ }
27
+
28
+ /**
29
+ * Removes and returns the item at the front of the queue.
30
+ * @returns {*} The item at the front of the queue.
31
+ */
32
+ pick() {
33
+ return this.items.shift();
34
+ }
35
+
36
+ /**
37
+ * Returns the number of items currently in the queue.
38
+ * @returns {number} The number of items currently in the queue.
39
+ */
40
+ size() {
41
+ return this.items.length;
42
+ }
43
+ }
44
+
45
+ export { Queue };