npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@ferndev/woo

v2.0.0

Published

WooCommerce actions to work with the Fern Framework

Readme

@ferndev/woo

WooCommerce integration library for the Fern PHP framework with reactive state management.

Version Bundle Size License

Features

  • 🛒 Cart Management - Full WooCommerce cart operations
  • 🔄 Reactive State - Powered by Nanostores for efficient reactivity
  • 💰 Price Formatting - Automatic currency formatting based on shop config
  • 🎫 Coupon Support - Apply and remove discount codes
  • Race-Condition Safe - Handles concurrent operations correctly
  • 🛡️ Defensive Programming - Validates quantities and handles edge cases
  • 📝 Fully Typed - Complete TypeScript definitions
  • 🪶 Lightweight - Only 6.3 KB (1.66 KB gzipped)

Installation

bun add @ferndev/woo @ferndev/core nanostores
# or
npm install @ferndev/woo @ferndev/core nanostores
# or
yarn add @ferndev/woo @ferndev/core nanostores

Quick Start

1. Initialize Cart on App Mount

import { initializeCart } from '@ferndev/woo';

// Call once when your app starts
await initializeCart();

2. Use Cart Functions

import { addToCart, removeFromCart, $cartItemsCount } from '@ferndev/woo';

// Cart actions return a normalized CartResult discriminated union.
// A business failure (out-of-stock, etc.) yields { status: 'error', error }.
const result = await addToCart({ productId: 123, quantity: 2 });

if (result.status === 'ok') {
  console.log('Added — cart total:', result.cart.total);
} else {
  // result.error.code may be e.g. 'out_of_stock'
  showToast(result.error.message);
}

// React to cart changes
$cartItemsCount.subscribe(count => {
  console.log(`Cart has \${count} items`);
});

Result types. Single actions return CartResult ({ status: 'ok'; cart } | { status: 'error'; error: WooError }). initializeCart() returns InitialStateResult (adds config); batchAddToCart() returns BatchCartResult (adds per-item results). The $cart store is only updated on success.

API Reference

Cart Operations

initializeCart()

Initialize cart and shop configuration. Must be called before any other cart operations.

await initializeCart();

addToCart(options)

Add a product to the cart.

// Simple product
await addToCart({
  productId: 123,
  quantity: 2
});

// Variable product
await addToCart({
  productId: 456,
  quantity: 1,
  variationId: 789,
  variation: { size: 'large', color: 'blue' }
});

batchAddToCart({ items })

Add multiple products in one operation.

await batchAddToCart({
  items: [
    { productId: 123, quantity: 2 },
    { productId: 456, quantity: 1, variationId: 789 }
  ]
});

updateQuantity(cartItemKey, quantity)

Update item quantity. Validates quantity and auto-removes if zero.

await updateQuantity('abc123', 3);  // Set to 3
await updateQuantity('abc123', 0);  // Removes item
await updateQuantity('abc123', -1); // Throws error

removeFromCart(cartItemKey)

Remove an item from cart.

await removeFromCart('abc123');

clearCart()

Remove all items from cart.

await clearCart();

applyCoupon(code) / removeCoupon(code)

Manage discount coupons.

await applyCoupon('SAVE20');
await removeCoupon('SAVE20');

Reactive Stores

All stores are Nanostores that you can subscribe to for reactive updates:

import {
  \$cart,              // Full cart object
  \$cartItemsCount,    // Number of items
  \$cartTotal,         // Total amount
  \$cartSubtotal,      // Subtotal (before tax/shipping)
  \$cartTaxTotal,      // Total tax
  \$cartShippingTotal, // Shipping cost
  \$cartIsLoading,     // Loading state
  \$shopConfig         // WooCommerce configuration
} from '@ferndev/woo';

// React to changes
\$cartItemsCount.subscribe(count => {
  document.getElementById('cart-badge').textContent = count;
});

// Get current value
const currentTotal = \$cartTotal.get();

Price Formatting

import { formatPrice } from '@ferndev/woo';

// Automatically formats based on shop configuration
formatPrice(1234.56);  // "$1,234.56" (or €1.234,56 depending on config)
formatPrice(-10.00);    // "-$10.00"

Framework Integration

React / Solid / Preact

import { useStore } from '@nanostores/react'; // or @nanostores/solid, etc.
import { \$cartItemsCount, addToCart } from '@ferndev/woo';

function CartBadge() {
  const count = useStore(\$cartItemsCount);
  
  return <span className="badge">{count}</span>;
}

function AddToCartButton({ productId }: { productId: number }) {
  const handleClick = async () => {
    await addToCart({ productId, quantity: 1 });
  };
  
  return <button onClick={handleClick}>Add to Cart</button>;
}

Svelte

<script>
  import { \$cartItemsCount, addToCart } from '@ferndev/woo';
</script>

<div class="cart-badge">{\$cartItemsCount}</div>

<button on:click={() => addToCart({ productId: 123, quantity: 1 })}>
  Add to Cart
</button>

Vue

<script setup>
import { useStore } from '@nanostores/vue';
import { \$cartItemsCount, addToCart } from '@ferndev/woo';

const count = useStore(\$cartItemsCount);
</script>

<template>
  <span class="badge">{{ count }}</span>
  <button @click="addToCart({ productId: 123, quantity: 1 })">
    Add to Cart
  </button>
</template>

Error Handling

All cart functions throw descriptive errors with context:

try {
  await addToCart({ productId: 123, quantity: 2 });
} catch (error) {
  // Error messages are descriptive:
  // "Failed to add product 123 to cart: Out of stock"
  console.error(error.message);
  
  // Original error preserved in .cause
  console.error(error.cause);
}

Concurrent Operations

The library handles concurrent operations safely:

// These can run simultaneously without issues
await Promise.all([
  addToCart({ productId: 1, quantity: 1 }),
  addToCart({ productId: 2, quantity: 1 }),
  addToCart({ productId: 3, quantity: 1 })
]);

// Loading state remains true until ALL complete

Bundle Size

  • ES Module: 6.30 KB (1.66 KB gzipped)
  • UMD Module: 5.32 KB (1.68 KB gzipped)

TypeScript

Fully typed with exported interfaces:

import type {
  Cart,
  CartItem,
  WooCommerceConfig,
  AddToCartArgs,
  UpdateCartItemArgs
} from '@ferndev/woo';

v2 note: the open-ended meta_data bags (Cart, CartItem, Variation, CartItemData.variations[]) are now Record<string, unknown> instead of { [key: string]: any }. Cast or narrow the specific keys you read:

const note = cart.meta_data['delivery_note'] as string | undefined;

Changelog

See the monorepo CHANGELOG.md. Latest: 2.0.0meta_data values are now unknown (was any); requires @ferndev/core ^2.0.0.

License

MIT © Tanguy Magnaudet

Links