@eik/node-client 1.1.61 → 1.1.63

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/dist/index.cjs CHANGED
@@ -4,115 +4,348 @@ var common = require('@eik/common');
4
4
  var undici = require('undici');
5
5
  var path = require('path');
6
6
 
7
+ /**
8
+ * @typedef {object} AssetOptions
9
+ * @property {string} [value=""]
10
+ */
11
+
12
+ /**
13
+ * Holds attributes for use when linking to assets hosted on Eik.
14
+ *
15
+ * @example
16
+ * ```
17
+ * // JS and <script>
18
+ * const script = eik.file("/app.js");
19
+ * const html = `<script
20
+ * src="${script.value}"
21
+ * ${script.integrity ? `integrity="${script.integrity}"` : ""}
22
+ * type="module"></script>`;
23
+ * ```
24
+ * @example
25
+ * ```
26
+ * // CSS and <link>
27
+ * const styles = eik.file("/styles.css");
28
+ * const html = `<link
29
+ * href="${styles.value}"
30
+ * ${styles.integrity ? `integrity="${styles.integrity}"` : ""}
31
+ * rel="stylesheet" />`;
32
+ * ```
33
+ */
7
34
  class Asset {
8
- constructor({
9
- value = '',
10
- } = {}) {
11
- this.integrity = undefined;
12
- this.value = value;
13
- }
35
+ /**
36
+ * Value for use in [subresource integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity#examples).
37
+ * Not calculated if `development` is `true`.
38
+ *
39
+ * @type {string | undefined}
40
+ */
41
+ integrity = undefined;
42
+
43
+ /**
44
+ * URL to the file for use in `<script>` or `<link>`.
45
+ * @type {string}
46
+ */
47
+ value;
48
+
49
+ /**
50
+ * @param {AssetOptions} options
51
+ */
52
+ constructor({ value = "" } = {}) {
53
+ this.integrity = undefined;
54
+ this.value = value;
55
+ }
14
56
  }
15
57
 
16
- const trimSlash = (value = '') => {
17
- if (value.endsWith('/')) return value.substring(0, value.length - 1);
18
- return value;
58
+ const trimSlash = (value = "") => {
59
+ if (value.endsWith("/")) return value.substring(0, value.length - 1);
60
+ return value;
19
61
  };
20
62
 
21
63
  const fetchImportMaps = async (urls = []) => {
22
- try{
23
- const maps = urls.map(async (map) => {
24
- const {
25
- statusCode,
26
- body
27
- } = await undici.request(map, { maxRedirections: 2 });
28
-
29
- if (statusCode === 404) {
30
- throw new Error('Import map could not be found on server');
31
- } else if (statusCode >= 400 && statusCode < 500) {
32
- throw new Error('Server rejected client request');
33
- } else if (statusCode >= 500) {
34
- throw new Error('Server error');
35
- }
36
- return body.json();
37
- });
38
- return await Promise.all(maps);
39
- } catch (err) {
40
- throw new Error(
41
- `Unable to load import map file from server: ${err.message}`,
42
- );
43
- }
64
+ try {
65
+ const maps = urls.map(async (map) => {
66
+ const { statusCode, body } = await undici.request(map, {
67
+ maxRedirections: 2,
68
+ });
69
+
70
+ if (statusCode === 404) {
71
+ throw new Error("Import map could not be found on server");
72
+ } else if (statusCode >= 400 && statusCode < 500) {
73
+ throw new Error("Server rejected client request");
74
+ } else if (statusCode >= 500) {
75
+ throw new Error("Server error");
76
+ }
77
+ return body.json();
78
+ });
79
+ return await Promise.all(maps);
80
+ } catch (err) {
81
+ throw new Error(
82
+ `Unable to load import map file from server: ${err.message}`,
83
+ );
84
+ }
44
85
  };
45
86
 
46
- class NodeClient {
47
- #development;
48
- #loadMaps;
49
- #config;
50
- #path;
51
- #base;
52
- #maps;
53
- constructor({
54
- development = false,
55
- loadMaps = false,
56
- base = '',
57
- path = process.cwd(),
58
- } = {}) {
59
- this.#development = development;
60
- this.#loadMaps = loadMaps;
61
- this.#config = {};
62
- this.#path = path;
63
- this.#base = trimSlash(base);
64
- this.#maps = [];
65
- }
66
-
67
- async load() {
68
- this.#config = await common.helpers.getDefaults(this.#path);
69
- if (this.#loadMaps) {
70
- this.#maps = await fetchImportMaps(this.#config.map);
71
- }
72
- }
73
-
74
- get name() {
75
- if (this.#config.name) return this.#config.name;
76
- throw new Error('Eik config was not loaded before calling .name');
77
- }
78
-
79
- get version() {
80
- if (this.#config.version) return this.#config.version;
81
- throw new Error('Eik config was not loaded before calling .version');
82
- }
83
-
84
- get type() {
85
- if (this.#config.type && this.#config.type === 'package') return 'pkg';
86
- if (this.#config.type) return this.#config.type;
87
- throw new Error('Eik config was not loaded before calling .type');
88
- }
89
-
90
- get server() {
91
- if (this.#config.server) return this.#config.server;
92
- throw new Error('Eik config was not loaded before calling .server');
93
- }
94
-
95
- get pathname() {
96
- if (this.#config.type && this.#config.name && this.#config.version) return path.join('/', this.type, this.name, this.version);
97
- throw new Error('Eik config was not loaded before calling .pathname');
98
- }
99
-
100
- base() {
101
- if (this.#development) return this.#base;
102
- return `${this.server}${this.pathname}`;
103
- }
104
-
105
- file(file = '') {
106
- const base = this.base();
107
- return new Asset({
108
- value: `${base}${file}`,
109
- });
110
- }
111
-
112
- maps() {
113
- if (this.#config.version && this.#loadMaps) return this.#maps;
114
- throw new Error('Eik config was not loaded or "loadMaps" is "false" when calling .maps()');
115
- }
87
+ /**
88
+ * @typedef {object} Options
89
+ * @property {string} [base=null]
90
+ * @property {boolean} [development=false]
91
+ * @property {boolean} [loadMaps=false]
92
+ * @property {string} [path=process.cwd()]
93
+ */
94
+
95
+ /**
96
+ * @typedef {object} ImportMap
97
+ * @property {Record<string, string>} imports
98
+ */
99
+
100
+ /**
101
+ * An Eik utility for servers running on Node. With it you can:
102
+ * - generate different URLs to assets on an Eik server depending on environment (development vs production).
103
+ * - get the import maps you have configured in `eik.json` from the Eik server, should you want to use them in the HTML response.
104
+ *
105
+ * @example
106
+ * ```js
107
+ * // Create an instance, then load information from `eik.json` and the Eik server
108
+ * import Eik from "@eik/node-client";
109
+ *
110
+ * const eik = new Eik();
111
+ * await eik.load();
112
+ * ```
113
+ * @example
114
+ * ```js
115
+ * // Serve a local version of a file from `./public`
116
+ * // in development and from Eik in production
117
+ * import path from "node:path";
118
+ * import Eik from "@eik/node-client";
119
+ * import fastifyStatic from "@fastify/static";
120
+ * import fastify from "fastify";
121
+ *
122
+ * const app = fastify();
123
+ * app.register(fastifyStatic, {
124
+ * root: path.join(process.cwd(), "public"),
125
+ * prefix: "/public/",
126
+ * });
127
+ *
128
+ * const eik = new Eik({
129
+ * development: process.env.NODE_ENV === "development",
130
+ * base: "/public",
131
+ * });
132
+ *
133
+ * // load information from `eik.json` and the Eik server
134
+ * await eik.load();
135
+ *
136
+ * // when development is true script.value will be /public/script.js.
137
+ * // when development is false script.value will be
138
+ * // https://{server}/pkg/{name}/{version}/script.js
139
+ * // where {server}, {name} and {version} are read from eik.json
140
+ * const script = eik.file("/script.js");
141
+ *
142
+ * app.get("/", (req, reply) => {
143
+ * reply.type("text/html; charset=utf-8");
144
+ * reply.send(`<html><body>
145
+ * <script
146
+ * src="${script.value}"
147
+ * ${script.integrity ? `integrity="${script.integrity}"` : ""}
148
+ * type="module"></script>
149
+ * </body></html>`);
150
+ * });
151
+ *
152
+ * app.listen({
153
+ * port: 3000,
154
+ * });
155
+ *
156
+ * console.log("Listening on http://localhost:3000");
157
+ * ```
158
+ */
159
+ class Eik {
160
+ #development;
161
+ #loadMaps;
162
+ #config;
163
+ #path;
164
+ #base;
165
+ #maps;
166
+
167
+ /**
168
+ * @param {Options} options
169
+ */
170
+ constructor({
171
+ development = false,
172
+ loadMaps = false,
173
+ base = "",
174
+ path = process.cwd(),
175
+ } = {}) {
176
+ this.#development = development;
177
+ this.#loadMaps = loadMaps;
178
+ this.#config = {};
179
+ this.#path = path;
180
+ this.#base = trimSlash(base);
181
+ this.#maps = [];
182
+ }
183
+
184
+ /**
185
+ * Reads the Eik config from disk into the object instance, used for building {@link file} links in production.
186
+ *
187
+ * If {@link Options.loadMaps} is `true` the import maps
188
+ * defined in the Eik config will be fetched from the Eik server for
189
+ * use in {@link maps}.
190
+ */
191
+ async load() {
192
+ this.#config = await common.helpers.getDefaults(this.#path);
193
+ if (this.#loadMaps) {
194
+ this.#maps = await fetchImportMaps(this.#config.map);
195
+ }
196
+ }
197
+
198
+ /**
199
+ * The `"name"` field from the Eik config
200
+ * @throws if read before calling {@link load}
201
+ */
202
+ get name() {
203
+ if (this.#config.name) return this.#config.name;
204
+ throw new Error("Eik config was not loaded before calling .name");
205
+ }
206
+
207
+ /**
208
+ * The `"version"` field from the Eik config
209
+ * @throws if read before calling {@link load}
210
+ */
211
+ get version() {
212
+ if (this.#config.version) return this.#config.version;
213
+ throw new Error("Eik config was not loaded before calling .version");
214
+ }
215
+
216
+ /**
217
+ * The `"type"` field from the Eik config mapped to its URL equivalent (eg. "package" is "pkg").
218
+ * @throws if read before calling {@link load}
219
+ */
220
+ get type() {
221
+ if (this.#config.type && this.#config.type === "package") return "pkg";
222
+ if (this.#config.type) return this.#config.type;
223
+ throw new Error("Eik config was not loaded before calling .type");
224
+ }
225
+
226
+ /**
227
+ * The `"server"` field from the Eik config
228
+ * @throws if read before calling {@link load}
229
+ */
230
+ get server() {
231
+ if (this.#config.server) return this.#config.server;
232
+ throw new Error("Eik config was not loaded before calling .server");
233
+ }
234
+
235
+ /**
236
+ * The pathname to the base on Eik (ex. /pkg/my-app/1.0.0/)
237
+ * @throws if read before calling {@link load}
238
+ */
239
+ get pathname() {
240
+ if (this.#config.type && this.#config.name && this.#config.version)
241
+ return path.join("/", this.type, this.name, this.version).replace(/\\/g, "/");
242
+ throw new Error("Eik config was not loaded before calling .pathname");
243
+ }
244
+
245
+ /**
246
+ * Similar to {@link file}, this method returns a path to the base on Eik
247
+ * (ex. https://eik.store.com/pkg/my-app/1.0.0), or {@link Options.base}
248
+ * if {@link Options.development} is true.
249
+ *
250
+ * You can use this instead of `file` if you have a directory full of files
251
+ * and you don't need {@link Asset.integrity}.
252
+ *
253
+ * @returns {string} The base path for assets published on Eik
254
+ * @throws when {@link Options.development} is false if called before calling {@link load}
255
+ */
256
+ base() {
257
+ if (this.#development) return this.#base;
258
+ return `${this.server}${this.pathname}`;
259
+ }
260
+
261
+ /**
262
+ * Get a link to a file that is published on Eik when running in production.
263
+ * When {@link Options.development} is `true` the pathname is prefixed
264
+ * with the {@link Options.base} option instead of pointing to Eik.
265
+ *
266
+ * @param {string} pathname pathname to the file relative to the base on Eik (ex: /path/to/script.js for a prod URL https://eik.store.com/pkg/my-app/1.0.0/path/to/script.js)
267
+ * @returns {import('./asset.js').Asset}
268
+ * @throws when {@link Options.development} is false if called before calling {@link load}
269
+ *
270
+ * @example
271
+ * ```js
272
+ * // in production
273
+ * const eik = new Eik({
274
+ * development: false,
275
+ * });
276
+ * await eik.load();
277
+ *
278
+ * const file = eik.file("/path/to/script.js");
279
+ * // {
280
+ * // value: https://eik.store.com/pkg/my-app/1.0.0/path/to/script.js
281
+ * // integrity: sha512-zHQjnD-etc.
282
+ * // }
283
+ * // where the server URL, app name and version are read from eik.json
284
+ * // {
285
+ * // "name": "my-app",
286
+ * // "version": "1.0.0",
287
+ * // "server": "https://eik.store.com",
288
+ * // }
289
+ * ```
290
+ * @example
291
+ * ```js
292
+ * // in development
293
+ * const eik = new Eik({
294
+ * development: true,
295
+ * base: "/public",
296
+ * });
297
+ * await eik.load();
298
+ *
299
+ * const file = eik.file("/path/to/script.js");
300
+ * // {
301
+ * // value: /public/path/to/script.js
302
+ * // integrity: undefined
303
+ * // }
304
+ * ```
305
+ */
306
+ file(pathname = "") {
307
+ const base = this.base();
308
+ return new Asset({
309
+ value: `${base}${pathname}`,
310
+ });
311
+ }
312
+
313
+ /**
314
+ * When {@link Options.loadMaps} is `true` and you call {@link load}, the client
315
+ * fetches the configured import maps from the Eik server.
316
+ *
317
+ * This method returns the import maps that were fetched during `load`.
318
+ *
319
+ * @returns {ImportMap[]}
320
+ * @throws if {@link Options.loadMaps} is not `true` or called before calling {@link load}
321
+ *
322
+ * @example
323
+ * ```js
324
+ * // generate a <script type="importmap">
325
+ * // for import mapping in the browser
326
+ * const client = new Eik({
327
+ * loadMaps: true,
328
+ * });
329
+ * await client.load();
330
+ *
331
+ * const maps = client.maps();
332
+ * const combined = maps
333
+ * .map((map) => map.imports)
334
+ * .reduce((map, acc) => ({ ...acc, ...map }), {});
335
+ *
336
+ * const html = `
337
+ * <script type="importmap">
338
+ * ${JSON.stringify(combined, null, 2)}
339
+ * </script>
340
+ * `;
341
+ * ```
342
+ */
343
+ maps() {
344
+ if (this.#config.version && this.#loadMaps) return this.#maps;
345
+ throw new Error(
346
+ 'Eik config was not loaded or "loadMaps" is "false" when calling .maps()',
347
+ );
348
+ }
116
349
  }
117
350
 
118
- module.exports = NodeClient;
351
+ module.exports = Eik;
package/package.json CHANGED
@@ -1,10 +1,12 @@
1
1
  {
2
2
  "name": "@eik/node-client",
3
- "version": "1.1.61",
4
- "description": "A node.js client for interacting with a Eik server.",
3
+ "version": "1.1.63",
4
+ "description": "Utilities for working with assets and import maps on an Eik server",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",
7
+ "types": "./types/index.d.ts",
7
8
  "exports": {
9
+ "types": "./types/index.d.ts",
8
10
  "import": "./src/index.js",
9
11
  "require": "./dist/index.cjs"
10
12
  },
@@ -13,22 +15,26 @@
13
15
  "package.json",
14
16
  "LICENSE",
15
17
  "dist",
16
- "src"
18
+ "src",
19
+ "types"
17
20
  ],
18
21
  "scripts": {
19
- "test": "tap --disable-coverage --allow-empty-coverage",
20
- "lint:fix": "eslint --fix .",
22
+ "build": "rollup -c",
23
+ "clean": "rimraf .tap dist node_modules types",
21
24
  "lint": "eslint .",
22
- "prepare": "npm run -s build",
23
- "build": "rollup -c"
25
+ "lint:fix": "eslint --fix .",
26
+ "test": "tap --disable-coverage --allow-empty-coverage",
27
+ "types": "run-s types:module types:test",
28
+ "types:module": "tsc",
29
+ "types:test": "tsc --project tsconfig.test.json",
30
+ "prepare": "npm run -s build"
24
31
  },
25
32
  "repository": {
26
33
  "type": "git",
27
34
  "url": "git@github.com:eik-lib/node-client.git"
28
35
  },
29
36
  "keywords": [
30
- "eik",
31
- "esm"
37
+ "eik"
32
38
  ],
33
39
  "author": "Finn.no",
34
40
  "license": "MIT",
@@ -42,17 +48,17 @@
42
48
  "undici": "5.28.4"
43
49
  },
44
50
  "devDependencies": {
45
- "@babel/eslint-parser": "7.24.5",
46
- "@semantic-release/changelog": "6.0.3",
47
- "@semantic-release/git": "10.0.1",
48
- "eslint": "8.57.0",
49
- "eslint-config-airbnb-base": "15.0.0",
50
- "eslint-config-prettier": "9.1.0",
51
- "eslint-plugin-import": "2.29.1",
52
- "eslint-plugin-prettier": "5.1.3",
53
- "prettier": "3.2.5",
54
- "rollup": "4.13.2",
55
- "semantic-release": "23.0.8",
56
- "tap": "18.7.2"
51
+ "@eik/eslint-config": "1.0.2",
52
+ "@eik/prettier-config": "1.0.1",
53
+ "@eik/semantic-release-config": "1.0.0",
54
+ "@eik/typescript-config": "1.0.0",
55
+ "eslint": "9.8.0",
56
+ "npm-run-all": "4.1.5",
57
+ "prettier": "3.3.3",
58
+ "rimraf": "6.0.1",
59
+ "rollup": "4.20.0",
60
+ "semantic-release": "24.0.0",
61
+ "tap": "21.0.0",
62
+ "typescript": "5.5.4"
57
63
  }
58
64
  }
package/src/asset.js CHANGED
@@ -1,8 +1,50 @@
1
- export default class Asset {
2
- constructor({
3
- value = '',
4
- } = {}) {
5
- this.integrity = undefined;
6
- this.value = value;
7
- }
1
+ /**
2
+ * @typedef {object} AssetOptions
3
+ * @property {string} [value=""]
4
+ */
5
+
6
+ /**
7
+ * Holds attributes for use when linking to assets hosted on Eik.
8
+ *
9
+ * @example
10
+ * ```
11
+ * // JS and <script>
12
+ * const script = eik.file("/app.js");
13
+ * const html = `<script
14
+ * src="${script.value}"
15
+ * ${script.integrity ? `integrity="${script.integrity}"` : ""}
16
+ * type="module"></script>`;
17
+ * ```
18
+ * @example
19
+ * ```
20
+ * // CSS and <link>
21
+ * const styles = eik.file("/styles.css");
22
+ * const html = `<link
23
+ * href="${styles.value}"
24
+ * ${styles.integrity ? `integrity="${styles.integrity}"` : ""}
25
+ * rel="stylesheet" />`;
26
+ * ```
27
+ */
28
+ export class Asset {
29
+ /**
30
+ * Value for use in [subresource integrity](https://developer.mozilla.org/en-US/docs/Web/Security/Subresource_Integrity#examples).
31
+ * Not calculated if `development` is `true`.
32
+ *
33
+ * @type {string | undefined}
34
+ */
35
+ integrity = undefined;
36
+
37
+ /**
38
+ * URL to the file for use in `<script>` or `<link>`.
39
+ * @type {string}
40
+ */
41
+ value;
42
+
43
+ /**
44
+ * @param {AssetOptions} options
45
+ */
46
+ constructor({ value = "" } = {}) {
47
+ this.integrity = undefined;
48
+ this.value = value;
49
+ }
8
50
  }