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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@sky-modules/core

v0.20.14

Published

Core utilities - essential TypeScript utilities for modern development

Downloads

55

Readme

mergeNamespace

Продвинутое слияние пространств имён с типобезопасностью

Утилита mergeNamespace предоставляет мощные возможности для слияния объектов, сохраняя поведение функций и добавляя новые свойства. Идеально подходит для объектов конфигурации, систем плагинов и сложных структур данных.

Установка

npm install @sky-modules/core

Использование

import { mergeNamespace } from '@sky-modules/core'

// Базовое использование
const target = { func: () => 'hello' }
const source = { func: { newProp: 'world' } }

mergeNamespace(target, source)

console.log(target.func())         // → 'hello'
console.log(target.func.newProp)   // → 'world'

API

mergeNamespace<T, S>(target: T, source: S): T & S

Сливает свойства из source в target, сохраняя существующую функциональность.

Параметры

  • target - Целевой объект для слияния
  • source - Исходный объект для слияния

Возвращает

Объединённый объект с комбинированным типом T & S

Примеры

Объекты конфигурации

const config = {
    api: () => fetch('/api'),
    database: () => connectDB()
}

const extensions = {
    api: {
        timeout: 5000,
        retries: 3
    },
    database: {
        pool: { min: 1, max: 10 }
    }
}

mergeNamespace(config, extensions)

// Использование как функции
const response = await config.api()

// Использование как объекта
const timeout = config.api.timeout  // → 5000
const pool = config.database.pool   // → { min: 1, max: 10 }

Системы плагинов

class Logger {
    log(message: string) {
        console.log(`[LOG] ${message}`)
    }
}

const logger = new Logger()

// Добавление метаданных к логгеру
mergeNamespace(logger, {
    log: {
        level: 'info',
        timestamp: true,
        format: 'json'
    }
})

// Использование как метода
logger.log('Hello world')

// Использование конфигурации
if (logger.log.timestamp) {
    // Логика добавления временной метки
}

Функциональная конфигурация

const math = {
    add: (a: number, b: number) => a + b,
    multiply: (a: number, b: number) => a * b
}

const mathConfig = {
    add: { precision: 2 },
    multiply: { overflow: 'error' }
}

mergeNamespace(math, mathConfig)

// Функции работают нормально
const sum = math.add(1.234, 2.345)  // → 3.579

// Конфигурация доступна
const precision = math.add.precision  // → 2

Типобезопасность

Утилита предоставляет полную поддержку TypeScript:

interface ApiConfig {
    timeout: number
    retries: number
}

interface Api {
    (): Promise<Response>
    config?: ApiConfig
}

const api: Api = () => fetch('/api')

mergeNamespace(api, {
    config: { timeout: 5000, retries: 3 }
})

// TypeScript знает и о функции, и о свойствах
const response = await api()           // ✓ Вызов функции
const timeout = api.config?.timeout    // ✓ Доступ к свойству

Производительность

  • Нулевые накладные расходы - Без влияния на производительность во время выполнения
  • Эффективность памяти - Свойства добавляются напрямую
  • Оптимизированные типы - Полный вывод типов TypeScript

Обработка ошибок

try {
    mergeNamespace(target, source)
} catch (error) {
    // Обработка конфликтов слияния или проблем с типами
    console.error('Слияние не удалось:', error)
}

Продвинутое использование

Вложенное слияние

const complex = {
    utils: {
        string: () => 'helper',
        number: () => 42
    }
}

const extensions = {
    utils: {
        string: {
            trim: true,
            lowercase: false
        },
        number: {
            precision: 2
        }
    }
}

mergeNamespace(complex, extensions)

// Все комбинации работают
complex.utils.string()                    // → 'helper'
complex.utils.string.trim                 // → true
complex.utils.number()                    // → 42
complex.utils.number.precision            // → 2

Условное слияние

const feature = {
    process: (data: any) => processData(data)
}

const conditionalConfig = {
    process: {
        enabled: process.env.NODE_ENV === 'production',
        debug: process.env.DEBUG === 'true'
    }
}

mergeNamespace(feature, conditionalConfig)

if (feature.process.enabled) {
    feature.process(data)
}

Связанные модули

Этот модуль хорошо работает с другими утилитами Sky для расширенной работы с объектами и управления конфигурацией.

Исходный код

Посмотреть исходный код на GitHub.