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

coreless-lib

v0.0.11

Published

Headless CMS Framework Agnostic Library

Readme

Coreless Lib - Документация для начинающих

Библиотека для управления контентом вашего сайта без сложностей. Представьте: весь текст, картинки и меню вашего сайта хранятся на сервере, а вы просто "заказываете" их по имени.


🟢 1. Чистый JavaScript (Без сборщиков)

Самый простой способ — подключить библиотеку прямо в HTML-файл через CDN.

Шаг 1. Создайте index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Мой сайт</title>
</head>
<body>
    <h1 id="title">Загрузка...</h1>
    <p id="desc"></p>
    <img id="image" src="" style="display:none; width: 200px;">

    <!-- Подключаем библиотеку как модуль -->
    <script type="module">
        // Импортируем класс Coreless прямо из сети (или локально ./dist/index.js)
        import { Coreless } from 'https://unpkg.com/coreless-lib/core?module';

        // 1. Настройка: куда стучаться за данными?
        const cms = new Coreless({
            apiHost: 'http://localhost:8080', // Адрес вашего API
            projectSlug: '123'                // ID вашего проекта
        });

        async function start() {
            try {
                // 2. Получаем страницу "home"
                const page = await cms.getPage('home');

                // 3. Используем данные
                // text() - для текста
                document.getElementById('title').innerText = page.text('hero/title');
                document.getElementById('desc').innerText = page.text('hero/description');

                // image() - для картинок
                const photo = page.image('photo1');
                if (photo) {
                    const img = document.getElementById('image');
                    img.src = photo.url;
                    img.style.display = 'block';
                }

            } catch (error) {
                console.error('Ошибка:', error);
                document.getElementById('title').innerText = 'Ошибка загрузки';
            }
        }

        start();
    </script>
</body>
</html>

🔵 2. React (Client Side Rendering)

Если вы делаете стандартное React-приложение (Create React App, Vite).

Установка:

npm install coreless-lib

Шаг 1. Настройте провайдер в App.tsx (или main.tsx) Это нужно сделать один раз на самом верху приложения.

import { CorelessProvider, HttpContentFetcher } from 'coreless-lib';

// Создаем "связиста"
const fetcher = new HttpContentFetcher({
  apiHost: 'http://localhost:8080',
  projectSlug: '123'
});

function App() {
  return (
    // Оборачиваем все приложение
    <CorelessProvider fetcher={fetcher}>
       <HomePage />
    </CorelessProvider>
  );
}

Шаг 2. Используйте хук useContent в компонентах В любом компоненте внутри провайдера.

import { useContent } from 'coreless-lib';

export const HomePage = () => {
  // Просим данные страницы "home"
  const content = useContent('home');

  // Пока грузится — показываем спиннер
  if (content.loading) return <div>Загрузка...</div>;
  
  // Если ошибка — показываем сообщение
  if (content.error) return <div>Ошибка: {content.error.message}</div>;

  return (
    <main>
      {/* Текст */}
      <h1>{content.text('header/title')}</h1>

      {/* Картинка */}
      <img src={content.image('header/logo')?.url} alt="Logo" />

      {/* Список (например, блог) */}
      {content.list('blog').map(post => (
        <article key={post.slug}>
           <h2>{post.data.title}</h2>
        </article>
      ))}
    </main>
  );
};

⚫ 3. Next.js (Server Side Rendering / App Router)

Самый современный подход. Данные грузятся на сервере, а пользователь получает готовый HTML. Это супер быстро и полезно для SEO.

Шаг 1. Создайте файл lib/cms.ts Чтобы не создавать подключение каждый раз, сделаем его один раз.

// lib/cms.ts
import { Coreless } from 'coreless-lib';

export const cms = new Coreless({
  apiHost: process.env.CMS_API_HOST || 'http://localhost:8080',
  projectSlug: '123'
});

Шаг 2. Используйте на странице app/page.tsx Заметьте: тут нет useEffect или loading. Функция async сама всё подождет.

// app/page.tsx
import { cms } from '@/lib/cms';

// Компонент должен быть async!
export default async function Page() {
  // Грузим данные прямо на сервере
  const page = await cms.getPage('home');

  return (
    <main>
      <h1>{page.text('hero/title')}</h1>
      <p>{page.text('hero/description')}</p>

      {/* Таблица */}
      {(() => {
        const table = page.table('methods');
        if (!table) return null;
        
        return (
          <table>
            <thead>
              <tr>
                {table.fields.map(f => <th key={f.slug}>{f.name}</th>)}
              </tr>
            </thead>
            <tbody>
              {table.rows.map((row: any) => (
                <tr key={row._id}>
                  <td>{row.title}</td>
                  <td>{row.description}</td>
                </tr>
              ))}
            </tbody>
          </table>
        );
      })()}
    </main>
  );
}

📚 Шпаргалка по методам (API Reference)

Какой метод выбрать?

| Тип данных | Метод | Что возвращает | Пример использования | | :--- | :--- | :--- | :--- | | Текст | content.text('path') | string | Заголовки, описания, имена | | Картинка | content.image('path') | { url, width, height... } | <img src={...} /> | | Видео | content.video('path') | { url, duration... } | <video src={...} /> | | Файл | content.file('path') | { url, size, name... } | Скачать PDF, отчет | | Список | content.list('path') | Array<ContentNode> | Список новостей, меню, слайдер | | Таблица | content.table('path') | { fields, rows } | Таблицы цен, характеристик | | Сырые данные | content.field('path') | any | Если нужно что-то специфичное (настройки, цвета) |

Важно:

  • Все методы (кроме list и table) могут вернуть undefined, если данных нет.
  • Используйте ?. (optional chaining) в JS: content.image('logo')?.url.