0
# Utility Functions
1
2
This document covers helper functions for type checking, SRI hash generation, and data processing available both as standalone imports and through the plugin's utils property.
3
4
## Import Utilities
5
6
You can import utility functions directly from their respective modules:
7
8
```typescript
9
import { getSRIHash } from "webpack-assets-manifest/helpers";
10
import { isObject, isKeyValuePair, isPropertyKey } from "webpack-assets-manifest/type-predicate";
11
import { optionsSchema } from "webpack-assets-manifest/options-schema";
12
```
13
14
Or access them through the plugin instance:
15
16
```typescript
17
const manifest = new WebpackAssetsManifest();
18
const { isKeyValuePair, isObject, getSRIHash } = manifest.utils;
19
```
20
21
## Subresource Integrity
22
23
### getSRIHash Function
24
25
Generates Subresource Integrity hashes for content:
26
27
```typescript { .api }
28
function getSRIHash(algorithm: string, content: string | BinaryLike): string;
29
```
30
31
```typescript
32
import { getSRIHash } from "webpack-assets-manifest/helpers";
33
34
// Generate SHA256 hash
35
const hash = getSRIHash("sha256", "console.log('Hello World');");
36
// Result: "sha256-abc123..."
37
38
// Generate SHA384 hash from buffer
39
const buffer = Buffer.from("console.log('Hello');");
40
const hash384 = getSRIHash("sha384", buffer);
41
// Result: "sha384-def456..."
42
43
// Multiple algorithms
44
const algorithms = ["sha256", "sha384", "sha512"];
45
const hashes = algorithms.map(alg => getSRIHash(alg, content));
46
```
47
48
## Type Predicates
49
50
### isObject Function
51
52
Checks if a value is a plain object (not null, not array):
53
54
```typescript { .api }
55
function isObject<T extends object = UnknownRecord>(input: unknown): input is T;
56
```
57
58
```typescript
59
import { isObject } from "webpack-assets-manifest/type-predicate";
60
61
// Basic usage
62
console.log(isObject({})); // true
63
console.log(isObject([])); // false
64
console.log(isObject(null)); // false
65
console.log(isObject("string")); // false
66
67
// Type narrowing
68
if (isObject(someValue)) {
69
// someValue is now typed as object
70
console.log(someValue.someProperty);
71
}
72
73
// Generic type parameter
74
interface MyType { name: string; }
75
if (isObject<MyType>(input)) {
76
// input is now typed as MyType
77
console.log(input.name);
78
}
79
```
80
81
### isKeyValuePair Function
82
83
Checks if a value is a KeyValuePair object:
84
85
```typescript { .api }
86
function isKeyValuePair(input: unknown): input is KeyValuePair;
87
```
88
89
```typescript
90
import { isKeyValuePair } from "webpack-assets-manifest/type-predicate";
91
92
// Valid KeyValuePair objects
93
console.log(isKeyValuePair({ key: "main.js", value: "main-abc.js" })); // true
94
console.log(isKeyValuePair({ key: "style.css" })); // true (value optional)
95
console.log(isKeyValuePair({ value: "script.js" })); // true (key optional)
96
97
// Invalid objects
98
console.log(isKeyValuePair({})); // false (neither key nor value)
99
console.log(isKeyValuePair({ name: "test" })); // false (wrong properties)
100
101
// Usage in customize hook
102
manifest.hooks.customize.tap("Validator", (entry, original, manifest) => {
103
if (isKeyValuePair(entry)) {
104
// entry is properly typed as KeyValuePair
105
const { key = original.key, value = original.value } = entry;
106
return { key, value };
107
}
108
return entry;
109
});
110
```
111
112
### isPropertyKey Function
113
114
Checks if a value is a valid PropertyKey (string, number, or symbol):
115
116
```typescript { .api }
117
function isPropertyKey(input: unknown): input is PropertyKey;
118
```
119
120
```typescript
121
import { isPropertyKey } from "webpack-assets-manifest/type-predicate";
122
123
// Valid property keys
124
console.log(isPropertyKey("string")); // true
125
console.log(isPropertyKey(123)); // true
126
console.log(isPropertyKey(Symbol("test"))); // true
127
128
// Invalid property keys
129
console.log(isPropertyKey({})); // false
130
console.log(isPropertyKey(null)); // false
131
console.log(isPropertyKey(undefined)); // false
132
133
// Usage example
134
function setProperty(obj: object, key: unknown, value: any) {
135
if (isPropertyKey(key)) {
136
obj[key] = value; // TypeScript knows key is valid
137
}
138
}
139
```
140
141
## Helper Functions
142
143
## Internal Helper Functions
144
145
These functions are exported but marked as internal in the source code. They are used internally by the plugin but can be imported if needed:
146
147
### asArray Function
148
149
Converts a value to an array:
150
151
```typescript { .api }
152
function asArray<T>(data: T | T[]): T[];
153
```
154
155
```typescript
156
import { asArray } from "webpack-assets-manifest/helpers";
157
158
// Single value to array
159
console.log(asArray("main.js")); // ["main.js"]
160
161
// Array remains array
162
console.log(asArray(["main.js", "vendor.js"])); // ["main.js", "vendor.js"]
163
```
164
165
### getSortedObject Function
166
167
Sorts an object by its keys (internal):
168
169
```typescript { .api }
170
function getSortedObject(
171
object: Record<string, unknown>,
172
compareFunction?: (left: string, right: string) => number
173
): typeof object;
174
```
175
176
### findMapKeysByValue Function
177
178
Creates a function to find Map keys by their values (internal):
179
180
```typescript { .api }
181
function findMapKeysByValue<K = string, V = string>(map: Map<K, V>): (searchValue: V) => K[];
182
```
183
184
### group Function
185
186
Groups array items based on a callback (internal):
187
188
```typescript { .api }
189
function group<T>(
190
data: readonly T[],
191
getGroup: (item: T) => PropertyKey | undefined,
192
mapper?: (item: T, group: PropertyKey) => T
193
): Record<PropertyKey, T[]>;
194
```
195
196
### getLockFilename Function
197
198
Builds a file path to a lock file in the tmp directory (internal):
199
200
```typescript { .api }
201
function getLockFilename(filename: string): string;
202
```
203
204
### lock Function
205
206
Creates an async lockfile (internal):
207
208
```typescript { .api }
209
function lock(filename: string): Promise<void>;
210
```
211
212
### unlock Function
213
214
Removes an async lockfile (internal):
215
216
```typescript { .api }
217
function unlock(filename: string): Promise<void>;
218
```
219
220
**Note:** These internal functions are used by the plugin itself for file operations and data processing. While they are exported and can be imported, they may change or be removed in future versions.
221
222
## Options Schema
223
224
### optionsSchema Constant
225
226
JSON schema used for validating plugin options:
227
228
```typescript { .api }
229
const optionsSchema: Schema;
230
```
231
232
```typescript
233
import { optionsSchema } from "webpack-assets-manifest/options-schema";
234
import { validate } from "schema-utils";
235
236
// Custom validation
237
try {
238
validate(optionsSchema, userOptions, { name: "MyPlugin" });
239
console.log("Options are valid");
240
} catch (error) {
241
console.error("Invalid options:", error.message);
242
}
243
```
244
245
The schema defines validation rules for all plugin options including types, default values, and constraints.
246
247
## Usage in Plugin Context
248
249
### Via Plugin Utils
250
251
```typescript
252
const manifest = new WebpackAssetsManifest({
253
customize(entry, original, manifest, asset) {
254
// Access utilities through plugin
255
const { isKeyValuePair, isObject, getSRIHash } = manifest.utils;
256
257
if (isKeyValuePair(entry) && isObject(entry.value)) {
258
// Add custom integrity hash
259
const content = asset?.source.source();
260
if (content) {
261
entry.value.customHash = getSRIHash("md5", content);
262
}
263
}
264
265
return entry;
266
},
267
});
268
```
269
270
### Standalone Usage
271
272
```typescript
273
import { getSRIHash, isObject } from "webpack-assets-manifest/helpers";
274
import { isKeyValuePair } from "webpack-assets-manifest/type-predicate";
275
276
// Use utilities outside of plugin context
277
function processAssets(assets: unknown[]) {
278
return assets
279
.filter(isObject)
280
.filter(asset => isKeyValuePair(asset))
281
.map(asset => ({
282
...asset,
283
integrity: getSRIHash("sha256", asset.content),
284
}));
285
}
286
```
287
288
## Type Definitions
289
290
```typescript { .api }
291
type UnknownRecord = Record<PropertyKey, unknown>;
292
293
type BinaryLike = string | NodeJS.ArrayBufferView;
294
295
type PropertyKey = string | number | symbol;
296
```
297
298
The utility functions provide comprehensive type safety and are designed to work seamlessly with both TypeScript and JavaScript projects.