@metoceanapi/wxtiles-common 0.0.7 → 0.0.10

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/biome.json CHANGED
@@ -8,5 +8,17 @@
8
8
  "rules": {
9
9
  "recommended": true
10
10
  }
11
+ },
12
+ "files": {
13
+ "ignore": ["docs", "dist"]
14
+ },
15
+ "javascript": {
16
+ "formatter": {
17
+ "trailingCommas": "es5",
18
+ "quoteStyle": "single",
19
+ "jsxQuoteStyle": "single",
20
+ "arrowParentheses": "always",
21
+ "lineWidth": 160
22
+ }
11
23
  }
12
24
  }
@@ -0,0 +1,274 @@
1
+ import { WXLOG, fetchJson } from "../utils/wxtools";
2
+ import type {
3
+ WxAllBoundariesMeta,
4
+ WxAllDatasetsShortMetas,
5
+ WxDatasetMeta,
6
+ WxVariableMeta,
7
+ WxDate,
8
+ WxLayerVarsNames,
9
+ WxLayerOptions,
10
+ WxDataSetManagerOptions,
11
+ } from "../types";
12
+ import type { WxAPI } from "../wxapi";
13
+
14
+ /**
15
+ * Base class for managing a WX dataset and its related operations.
16
+ *
17
+ * Instances of concrete subclasses of this class handle metadata, variables,
18
+ * valid times, zoom levels, and URI construction for WX datasets.
19
+ *
20
+ * **Usage Note:** Do not create instances directly using the constructor.
21
+ * Use {@link WxAPI.createDatasetManager} instead.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * const wxapi = new WxAPI({ dataServerURL: "https://example.com" });
26
+ * const wxDatasetManager = await wxapi.createDatasetManager("gfs.global");
27
+ * console.log(wxDatasetManager.getAllVariables());
28
+ * ```
29
+ */
30
+ export abstract class BaseDatasetManager {
31
+ /** The name of the dataset being managed. */
32
+ readonly datasetName: string;
33
+
34
+ /**
35
+ * @internal
36
+ * A reference to the WX API instance that created this manager.
37
+ */
38
+ readonly wxAPI: WxAPI;
39
+
40
+ /** @ignore The current instance name of the dataset (for time-stepped datasets). */
41
+ protected _datasetCurrentInstance: string;
42
+
43
+ /** @ignore The current metadata for the dataset. */
44
+ protected _datasetCurrentMeta: WxDatasetMeta;
45
+
46
+ /** @ignore Array of instances for time-stepped datasets (optional). */
47
+ protected _instanced?: string[];
48
+
49
+ /** @ignore Map of metadata for each dataset instance (optional). */
50
+ protected _metas?: Map<string, WxDatasetMeta>;
51
+
52
+ /**
53
+ * Do not use this constructor directly. Use {@link WxAPI.createDatasetManager} instead.
54
+ *
55
+ * @param {WxDataSetManagerOptions} options - Dataset manager options.
56
+ */
57
+ constructor({
58
+ datasetName,
59
+ datasetCurrentInstance,
60
+ instanced,
61
+ datasetCurrentMeta,
62
+ metas,
63
+ wxAPI,
64
+ }: WxDataSetManagerOptions) {
65
+ this.datasetName = datasetName;
66
+ this._instanced = instanced;
67
+ this._datasetCurrentInstance = datasetCurrentInstance;
68
+ this._datasetCurrentMeta = datasetCurrentMeta;
69
+ this._metas = metas;
70
+ this.wxAPI = wxAPI;
71
+ WXLOG(`WxDataSetManager.constructor: ${this.datasetName}`);
72
+ }
73
+
74
+ /**
75
+ * Finds the nearest valid time in the dataset based on the input.
76
+ *
77
+ * - If `time` is an empty string, the last available time is returned.
78
+ * - If `time` is a string matching a valid time, that time is returned.
79
+ * - If `time` is a number:
80
+ * - Negative: Returns the first time.
81
+ * - Within range: Returns the corresponding indexed time.
82
+ * - Otherwise, finds the closest time in milliseconds.
83
+ *
84
+ * @param {WxDate} [time=Date()] - Input time as a string, number, or Date object.
85
+ * @returns {string} - The nearest valid time from the dataset's time steps.
86
+ *
87
+ * @example
88
+ * ```ts
89
+ * const nearestTime = wxDatasetManager.getNearestValidTime("2024-06-10T12:00:00Z");
90
+ * console.log(nearestTime); // Closest valid time
91
+ * ```
92
+ */
93
+ getNearestValidTime(time: WxDate = Date()): string {
94
+ WXLOG(`WxDataSetManager.getValidTime: ${this.datasetName}, ${time}`);
95
+ const times = this.getAllTimes();
96
+
97
+ if (time === "") return times[times.length - 1]; // for empty string use last time
98
+
99
+ if (typeof time === "string") {
100
+ const index = times.indexOf(time);
101
+ if (index !== -1) return times[index]; // if found use time from array
102
+ }
103
+
104
+ if (typeof time === "number") {
105
+ if (time <= 0) return times[0]; // for negative numbers use first time
106
+ if (time < times.length) return times[time]; // for numbers in range use time from array
107
+ }
108
+
109
+ const ms = new Date(time).getTime(); // otherwise convert time as milliseconds
110
+ if (Number.isNaN(ms)) return times[times.length - 1]; // if not valid use first time
111
+
112
+ const found = times.find((t) => new Date(t).getTime() >= ms);
113
+ return found || times[times.length - 1];
114
+ }
115
+
116
+ /**
117
+ * Retrieves all available time steps for the dataset.
118
+ *
119
+ * @returns {string[]} - A copy of the dataset's time steps.
120
+ */
121
+ getAllTimes(): string[] {
122
+ WXLOG(`WxDataSetManager.getTimes: ${this.datasetName}`);
123
+ return this._instanced || this._datasetCurrentMeta.times;
124
+ }
125
+
126
+ /**
127
+ * Retrieves all available variables for the dataset.
128
+ *
129
+ * @returns {string[]} - List of all variable names in the dataset.
130
+ */
131
+ getAllVariables(): string[] {
132
+ WXLOG(`WxDataSetManager.getVariables: ${this.datasetName}`);
133
+ return this._datasetCurrentMeta.variables;
134
+ }
135
+
136
+ /**
137
+ * Get the variable's meta from the dataset.
138
+ * @argument {string} variable - variable name
139
+ * @returns {WxVariableMeta | undefined} - dataset variable's meta
140
+ * */
141
+ getVariableCurrentMeta(variable: string): WxVariableMeta | undefined {
142
+ WXLOG(
143
+ `WxDataSetManager.getVariableCurrentMeta: ${this.datasetName}, ${variable}`,
144
+ );
145
+ return this._datasetCurrentMeta.variablesMeta[variable];
146
+ }
147
+
148
+ /**
149
+ * Get the variable meta from the instanced dataset.
150
+ * @argument {string} variable - variable name
151
+ * @argument {string} instance - instance name
152
+ * @returns {WxVariableMeta | undefined} - dataset variable's meta for the given instance
153
+ * */
154
+ getInstanceVariableMeta(
155
+ variable: string,
156
+ instance?: string,
157
+ ): WxVariableMeta | undefined {
158
+ WXLOG(
159
+ `WxDataSetManager.getInstanceVariableMeta: ${this.datasetName}, ${variable}, ${instance}`,
160
+ );
161
+ return this.getInstanceMeta(instance).variablesMeta[variable];
162
+ }
163
+
164
+ /**
165
+ * Get dataset's native maximum zoom level.
166
+ * @returns {number} - maximum zoom level of the dataset
167
+ * */
168
+ getMaxZoom(): number {
169
+ WXLOG(`WxDataSetManager.getMaxZoom: ${this.datasetName}`);
170
+ return this._datasetCurrentMeta.maxZoom;
171
+ }
172
+
173
+ /**
174
+ * Get dataset's boundaries.
175
+ * @returns {WxAllBoundariesMeta | undefined} - dataset's boundaries
176
+ * */
177
+ getBoundaries(): WxAllBoundariesMeta | undefined {
178
+ WXLOG(`WxDataSetManager.getBoundaries: ${this.datasetName}`);
179
+ return this._datasetCurrentMeta.boundaries;
180
+ }
181
+
182
+ /**
183
+ * Get dataset's metadata for the given instance.
184
+ * @param {string} instance
185
+ * @returns {WxDatasetMeta}
186
+ */
187
+ getInstanceMeta(instance?: string): WxDatasetMeta {
188
+ WXLOG(`WxDataSetManager.getInstanceMeta: ${this.datasetName}, ${instance}`);
189
+ return (instance && this._metas?.get(instance)) || this._datasetCurrentMeta;
190
+ }
191
+
192
+ /**
193
+ * Constructs the URI for fetching dataset tiles.
194
+ *
195
+ * @param {string} variable - The variable name (e.g., "temperature").
196
+ * @param {string} validTime - The valid time step for the dataset.
197
+ * @param {'webp'} [ext='webp'] - File extension (must be 'webp').
198
+ * @returns {string} - A URI ready for fetching tiles.
199
+ *
200
+ * @throws {Error} - If the variable is invalid.
201
+ *
202
+ * @example
203
+ * ```ts
204
+ * const uri = wxDatasetManager.createURI("temperature", "2024-06-10T12:00:00Z");
205
+ * console.log(uri);
206
+ * ```
207
+ */
208
+ createURI(variable: string, validTime: string, ext: "webp" = "webp"): string {
209
+ WXLOG(
210
+ `WxDataSetManager.createURI: ${this.datasetName}, ${variable}, ${validTime}`,
211
+ );
212
+ if (!this.isVariableValid(variable))
213
+ throw new Error(
214
+ `in dataset ${this.datasetName} variable ${variable} not found`,
215
+ );
216
+ const instance = this._instanced ? validTime : this._datasetCurrentInstance;
217
+ return `${this.wxAPI.dataServerURL + this.datasetName}/${instance}/${variable}/${validTime}/{z}/{x}/{y}.${ext}`;
218
+ }
219
+
220
+ /**
221
+ * Check if given variable is available in the dataset.
222
+ * @argument {string} variable - variable name
223
+ * @returns {boolean} - true if variable is available in the dataset
224
+ * */
225
+ isVariableValid(variable: string): boolean {
226
+ WXLOG(
227
+ `WxDataSetManager.checkVariableValid: ${this.datasetName}, ${variable}`,
228
+ );
229
+ return this._datasetCurrentMeta.variablesMeta[variable] !== undefined;
230
+ }
231
+
232
+ // TODO FIXME why is this created here?
233
+ // this doesn't reinit the object and has nothing impl specific, we can avoid it by decomposing, right?
234
+ /** @internal Update dataset's meta data. */
235
+ async update() {
236
+ const opts = await this.wxAPI.createDatasetManagerOptions(this.datasetName);
237
+
238
+ this._datasetCurrentInstance = opts.datasetCurrentInstance;
239
+ this._instanced = opts.instanced;
240
+ this._datasetCurrentMeta = opts.datasetCurrentMeta;
241
+ this._metas = opts.metas;
242
+ }
243
+
244
+ /** @internal Get dataset's current instance. @returns {boolean} - true if dataset is instanced */
245
+ isInstanced(): boolean {
246
+ return this._instanced !== undefined;
247
+ }
248
+
249
+ /**
250
+ * @internal
251
+ * Checks if variable is a vector component.
252
+ * @argument {string} variable - variable name
253
+ * @returns {WxLayerVarsNames} - [variable] or [variable.eastward, variable.northward]
254
+ * */
255
+ protected _checkCombineVariableIfVector(variable: string): WxLayerVarsNames {
256
+ WXLOG(
257
+ `WxDataSetManager.checkCombineVariableIfVector: ${this.datasetName}, ${variable}`,
258
+ );
259
+ const variableMeta = this._datasetCurrentMeta.variablesMeta[variable];
260
+ if (!variableMeta)
261
+ throw new Error(
262
+ `in dataset ${this.datasetName} variable ${variable} not found`,
263
+ );
264
+ return variableMeta.vector || [variable]; // check if variable is vector and use vector components if so
265
+ }
266
+
267
+ /**
268
+ * Creates a source layer for this dataset.
269
+ */
270
+ /*abstract createSourceLayer<WxSourceLayerOptionsT extends WxLayerOptions, FrameworkOptionsT, WxTileSourceT>(
271
+ options: WxSourceLayerOptionsT,
272
+ frwOptions: FrameworkOptionsT,
273
+ ): WxTileSourceT;*/
274
+ }
@@ -0,0 +1,60 @@
1
+ import type { WxAllDatasetsShortMetas } from "../types";
2
+ import type { WxAPI } from "../wxapi";
3
+ import { WXLOG, fetchJson } from "../utils/wxtools";
4
+
5
+ /**
6
+ * Base class for managing all datasets metadata.
7
+ * This class provides methods to fetch and manage metadata for all datasets
8
+ * or update metadata for a specific dataset.
9
+ *
10
+ * @internal
11
+ */
12
+ export class WxAllDatasetsManager {
13
+ allDatasetsShortMetas: WxAllDatasetsShortMetas = {};
14
+ ready: Promise<WxAllDatasetsShortMetas>;
15
+
16
+ /**
17
+ * Creates an instance of WxAllDatasetsManager.
18
+ *
19
+ * @param {WxAPI} wxAPI - An instance of WxAPI to interact with the data server.
20
+ * The wxAPI provides the base URL and request configuration for API calls.
21
+ */
22
+ constructor(protected readonly wxAPI: WxAPI) {
23
+ this.ready = this.updateAll(); // init _ready
24
+ }
25
+
26
+ /**
27
+ * Fetches and updates metadata for all datasets.
28
+ *
29
+ * @returns {Promise<WxAllDatasetsShortMetas>} A promise that resolves with
30
+ * the metadata of all datasets once the update is complete.
31
+ */
32
+ updateAll(): Promise<WxAllDatasetsShortMetas> {
33
+ this.ready = fetchJson(
34
+ `${this.wxAPI.dataServerURL}meta.json`,
35
+ this.wxAPI.requestInit,
36
+ );
37
+ this.ready.then((dms) => {this.allDatasetsShortMetas = dms});
38
+ return this.ready;
39
+ }
40
+
41
+ /**
42
+ * Updates the metadata for a specific dataset.
43
+ * If the specified dataset's metadata cannot be fetched (e.g., if the dataset does not exist),
44
+ * it will trigger an update for all datasets instead.
45
+ *
46
+ * @param {string} datasetName - The name of the dataset whose metadata needs to be updated.
47
+ * @returns {Promise<WxAllDatasetsShortMetas>} A promise that resolves with
48
+ * the updated metadata for the dataset or all datasets if the fetch for the specific dataset fails.
49
+ */
50
+ async updateOne(datasetName: string): Promise<WxAllDatasetsShortMetas> {
51
+ try {
52
+ const urlMeta = `${this.wxAPI.dataServerURL + datasetName}/meta.json`;
53
+ const datasetMeta = await fetchJson(urlMeta, this.wxAPI.requestInit);
54
+ return Object.assign(this.allDatasetsShortMetas, datasetMeta);
55
+ } catch {
56
+ // If fetching the specific dataset fails, fetch metadata for all datasets
57
+ return this.updateAll();
58
+ }
59
+ }
60
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metoceanapi/wxtiles-common",
3
- "version": "0.0.7",
3
+ "version": "0.0.10",
4
4
  "description": "Common resources shared by wxtiles mapbox and leaflet packages.",
5
5
  "exports": {
6
6
  "./*": "./*.ts",
@@ -15,8 +15,9 @@
15
15
  "author": "MetOcean",
16
16
  "license": "ISC",
17
17
  "devDependencies": {
18
+ "@biomejs/biome": "1.9.4",
18
19
  "git-format-staged": "^3.1.1",
19
- "husky": "^9.1.6"
20
+ "husky": "^9.1.7"
20
21
  },
21
22
  "repository": {
22
23
  "type": "git",