CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-webpack-assets-manifest

Webpack plugin that generates JSON manifest files mapping original filenames to their hashed versions with extensive customization options

Pending
Overview
Eval results
Files

utilities.mddocs/

Utility Functions

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.

Import Utilities

You can import utility functions directly from their respective modules:

import { getSRIHash } from "webpack-assets-manifest/helpers";
import { isObject, isKeyValuePair, isPropertyKey } from "webpack-assets-manifest/type-predicate";
import { optionsSchema } from "webpack-assets-manifest/options-schema";

Or access them through the plugin instance:

const manifest = new WebpackAssetsManifest();
const { isKeyValuePair, isObject, getSRIHash } = manifest.utils;

Subresource Integrity

getSRIHash Function

Generates Subresource Integrity hashes for content:

function getSRIHash(algorithm: string, content: string | BinaryLike): string;
import { getSRIHash } from "webpack-assets-manifest/helpers";

// Generate SHA256 hash
const hash = getSRIHash("sha256", "console.log('Hello World');");
// Result: "sha256-abc123..."

// Generate SHA384 hash from buffer
const buffer = Buffer.from("console.log('Hello');");
const hash384 = getSRIHash("sha384", buffer);
// Result: "sha384-def456..."

// Multiple algorithms
const algorithms = ["sha256", "sha384", "sha512"];
const hashes = algorithms.map(alg => getSRIHash(alg, content));

Type Predicates

isObject Function

Checks if a value is a plain object (not null, not array):

function isObject<T extends object = UnknownRecord>(input: unknown): input is T;
import { isObject } from "webpack-assets-manifest/type-predicate";

// Basic usage
console.log(isObject({})); // true
console.log(isObject([])); // false
console.log(isObject(null)); // false
console.log(isObject("string")); // false

// Type narrowing
if (isObject(someValue)) {
  // someValue is now typed as object
  console.log(someValue.someProperty);
}

// Generic type parameter
interface MyType { name: string; }
if (isObject<MyType>(input)) {
  // input is now typed as MyType
  console.log(input.name);
}

isKeyValuePair Function

Checks if a value is a KeyValuePair object:

function isKeyValuePair(input: unknown): input is KeyValuePair;
import { isKeyValuePair } from "webpack-assets-manifest/type-predicate";

// Valid KeyValuePair objects
console.log(isKeyValuePair({ key: "main.js", value: "main-abc.js" })); // true
console.log(isKeyValuePair({ key: "style.css" })); // true (value optional)
console.log(isKeyValuePair({ value: "script.js" })); // true (key optional)

// Invalid objects
console.log(isKeyValuePair({})); // false (neither key nor value)
console.log(isKeyValuePair({ name: "test" })); // false (wrong properties)

// Usage in customize hook
manifest.hooks.customize.tap("Validator", (entry, original, manifest) => {
  if (isKeyValuePair(entry)) {
    // entry is properly typed as KeyValuePair
    const { key = original.key, value = original.value } = entry;
    return { key, value };
  }
  return entry;
});

isPropertyKey Function

Checks if a value is a valid PropertyKey (string, number, or symbol):

function isPropertyKey(input: unknown): input is PropertyKey;
import { isPropertyKey } from "webpack-assets-manifest/type-predicate";

// Valid property keys
console.log(isPropertyKey("string")); // true
console.log(isPropertyKey(123)); // true
console.log(isPropertyKey(Symbol("test"))); // true

// Invalid property keys
console.log(isPropertyKey({})); // false
console.log(isPropertyKey(null)); // false
console.log(isPropertyKey(undefined)); // false

// Usage example
function setProperty(obj: object, key: unknown, value: any) {
  if (isPropertyKey(key)) {
    obj[key] = value; // TypeScript knows key is valid
  }
}

Helper Functions

Internal Helper Functions

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:

asArray Function

Converts a value to an array:

function asArray<T>(data: T | T[]): T[];
import { asArray } from "webpack-assets-manifest/helpers";

// Single value to array
console.log(asArray("main.js")); // ["main.js"]

// Array remains array
console.log(asArray(["main.js", "vendor.js"])); // ["main.js", "vendor.js"]

getSortedObject Function

Sorts an object by its keys (internal):

function getSortedObject(
  object: Record<string, unknown>,
  compareFunction?: (left: string, right: string) => number
): typeof object;

findMapKeysByValue Function

Creates a function to find Map keys by their values (internal):

function findMapKeysByValue<K = string, V = string>(map: Map<K, V>): (searchValue: V) => K[];

group Function

Groups array items based on a callback (internal):

function group<T>(
  data: readonly T[],
  getGroup: (item: T) => PropertyKey | undefined,
  mapper?: (item: T, group: PropertyKey) => T
): Record<PropertyKey, T[]>;

getLockFilename Function

Builds a file path to a lock file in the tmp directory (internal):

function getLockFilename(filename: string): string;

lock Function

Creates an async lockfile (internal):

function lock(filename: string): Promise<void>;

unlock Function

Removes an async lockfile (internal):

function unlock(filename: string): Promise<void>;

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.

Options Schema

optionsSchema Constant

JSON schema used for validating plugin options:

const optionsSchema: Schema;
import { optionsSchema } from "webpack-assets-manifest/options-schema";
import { validate } from "schema-utils";

// Custom validation
try {
  validate(optionsSchema, userOptions, { name: "MyPlugin" });
  console.log("Options are valid");
} catch (error) {
  console.error("Invalid options:", error.message);
}

The schema defines validation rules for all plugin options including types, default values, and constraints.

Usage in Plugin Context

Via Plugin Utils

const manifest = new WebpackAssetsManifest({
  customize(entry, original, manifest, asset) {
    // Access utilities through plugin
    const { isKeyValuePair, isObject, getSRIHash } = manifest.utils;
    
    if (isKeyValuePair(entry) && isObject(entry.value)) {
      // Add custom integrity hash
      const content = asset?.source.source();
      if (content) {
        entry.value.customHash = getSRIHash("md5", content);
      }
    }
    
    return entry;
  },
});

Standalone Usage

import { getSRIHash, isObject } from "webpack-assets-manifest/helpers";
import { isKeyValuePair } from "webpack-assets-manifest/type-predicate";

// Use utilities outside of plugin context
function processAssets(assets: unknown[]) {
  return assets
    .filter(isObject)
    .filter(asset => isKeyValuePair(asset))
    .map(asset => ({
      ...asset,
      integrity: getSRIHash("sha256", asset.content),
    }));
}

Type Definitions

type UnknownRecord = Record<PropertyKey, unknown>;

type BinaryLike = string | NodeJS.ArrayBufferView;

type PropertyKey = string | number | symbol;

The utility functions provide comprehensive type safety and are designed to work seamlessly with both TypeScript and JavaScript projects.

Install with Tessl CLI

npx tessl i tessl/npm-webpack-assets-manifest

docs

asset-management.md

hooks.md

index.md

plugin-configuration.md

utilities.md

tile.json