package/index.js000644 0000011111 3560116604 010720 0ustar00000000 000000 'use strict' class FiggyPudding { constructor (specs, opts, providers) { this.__specs = specs || {} Object.keys(this.__specs).forEach(alias => { if (typeof this.__specs[alias] === 'string') { const key = this.__specs[alias] const realSpec = this.__specs[key] if (realSpec) { const aliasArr = realSpec.aliases || [] aliasArr.push(alias, key) realSpec.aliases = [...(new Set(aliasArr))] this.__specs[alias] = realSpec } else { throw new Error(`Alias refers to invalid key: ${key} -> ${alias}`) } } }) this.__opts = opts || {} this.__providers = reverse((providers).filter( x => x != null && typeof x === 'object' )) this.__isFiggyPudding = true } get (key) { return pudGet(this, key, true) } get [Symbol.toStringTag] () { return 'FiggyPudding' } forEach (fn, thisArg = this) { for (let [key, value] of this.entries()) { fn.call(thisArg, value, key, this) } } toJSON () { const obj = {} this.forEach((val, key) => { obj[key] = val }) return obj } * entries (_matcher) { for (let key of Object.keys(this.__specs)) { yield [key, this.get(key)] } const matcher = _matcher || this.__opts.other if (matcher) { const seen = new Set() for (let p of this.__providers) { const iter = p.entries ? p.entries(matcher) : entries(p) for (let [key, val] of iter) { if (matcher(key) && !seen.has(key)) { seen.add(key) yield [key, val] } } } } } * [Symbol.iterator] () { for (let [key, value] of this.entries()) { yield [key, value] } } * keys () { for (let [key] of this.entries()) { yield key } } * values () { for (let [, value] of this.entries()) { yield value } } concat (...moreConfig) { return new Proxy(new FiggyPudding( this.__specs, this.__opts, reverse(this.__providers).concat(moreConfig) ), proxyHandler) } } try { const util = require('util') FiggyPudding.prototype[util.inspect.custom] = function (depth, opts) { return ( this[Symbol.toStringTag] + ' ' ) + util.inspect(this.toJSON(), opts) } } catch (e) {} function BadKeyError (key) { throw Object.assign(new Error( `invalid config key requested: ${key}` ), {code: 'EBADKEY'}) } function pudGet (pud, key, validate) { let spec = pud.__specs[key] if (validate && !spec && (!pud.__opts.other || !pud.__opts.other(key))) { BadKeyError(key) } else { if (!spec) { spec = {} } let ret for (let p of pud.__providers) { ret = tryGet(key, p) if (ret === undefined && spec.aliases && spec.aliases.length) { for (let alias of spec.aliases) { if (alias === key) { continue } ret = tryGet(alias, p) if (ret !== undefined) { break } } } if (ret !== undefined) { break } } if (ret === undefined && spec.default !== undefined) { if (typeof spec.default === 'function') { return spec.default(pud) } else { return spec.default } } else { return ret } } } function tryGet (key, p) { let ret if (p.__isFiggyPudding) { ret = pudGet(p, key, false) } else if (typeof p.get === 'function') { ret = p.get(key) } else { ret = p[key] } return ret } const proxyHandler = { has (obj, prop) { return prop in obj.__specs && pudGet(obj, prop, false) !== undefined }, ownKeys (obj) { return Object.keys(obj.__specs) }, get (obj, prop) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' || prop in FiggyPudding.prototype ) { return obj[prop] } return obj.get(prop) }, set (obj, prop, value) { if ( typeof prop === 'symbol' || prop.slice(0, 2) === '__' ) { obj[prop] = value return true } else { throw new Error('figgyPudding options cannot be modified. Use .concat() instead.') } }, deleteProperty () { throw new Error('figgyPudding options cannot be deleted. Use .concat() and shadow them instead.') } } module.exports = figgyPudding function figgyPudding (specs, opts) { function factory (...providers) { return new Proxy(new FiggyPudding( specs, opts, providers ), proxyHandler) } return factory } function reverse (arr) { const ret = [] arr.forEach(x => ret.unshift(x)) return ret } function entries (obj) { return Object.keys(obj).map(k => [k, obj[k]]) } package/package.json000644 0000001330 3560116604 011543 0ustar00000000 000000 { "name": "figgy-pudding", "version": "3.5.2", "description": "Delicious, festive, cascading config/opts definitions", "main": "index.js", "files": [ "*.js", "lib" ], "scripts": { "prerelease": "npm t", "postrelease": "npm publish && git push --follow-tags", "pretest": "standard", "release": "standard-version -s", "test": "tap -J --100 --coverage test/*.js" }, "repository": "https://github.com/npm/figgy-pudding", "keywords": [ "config", "options", "yummy" ], "author": "Kat Marchán ", "license": "ISC", "dependencies": {}, "devDependencies": { "standard": "^11.0.1", "standard-version": "^4.4.0", "tap": "^12.0.1" } } package/CHANGELOG.md000644 0000011002 3560116604 011063 0ustar00000000 000000 # Change Log All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ## [3.5.2](https://github.com/npm/figgy-pudding/compare/v3.5.1...v3.5.2) (2020-03-24) ## [3.5.1](https://github.com/npm/figgy-pudding/compare/v3.5.0...v3.5.1) (2018-08-25) # [3.5.0](https://github.com/npm/figgy-pudding/compare/v3.4.1...v3.5.0) (2018-08-25) ### Bug Fixes * **node:** get rid of Object.entries to add node6 support back ([074f779](https://github.com/npm/figgy-pudding/commit/074f779)) ### Features * **node:** add node@10 to CI config ([78b8937](https://github.com/npm/figgy-pudding/commit/78b8937)) ## [3.4.1](https://github.com/npm/figgy-pudding/compare/v3.4.0...v3.4.1) (2018-08-16) ### Bug Fixes * **forEach:** get forEach to behave like a normal forEach ([c064755](https://github.com/npm/figgy-pudding/commit/c064755)) * **has:** get `in` keyword working right ([fafc5a8](https://github.com/npm/figgy-pudding/commit/fafc5a8)) * **iteration:** fix and test iteration of opts.other keys ([7a76217](https://github.com/npm/figgy-pudding/commit/7a76217)) * **iteration:** use proper args for forEach/toJSON ([974e879](https://github.com/npm/figgy-pudding/commit/974e879)) * **proxy:** make sure proxy corner-cases work ok ([8c66e45](https://github.com/npm/figgy-pudding/commit/8c66e45)) * **set:** fix and test the exceptions to writing ([206793b](https://github.com/npm/figgy-pudding/commit/206793b)) # [3.4.0](https://github.com/npm/figgy-pudding/compare/v3.3.0...v3.4.0) (2018-08-16) ### Features * **iterator:** allow iteration over "other" keys ([3c53323](https://github.com/npm/figgy-pudding/commit/3c53323)) # [3.3.0](https://github.com/npm/figgy-pudding/compare/v3.2.1...v3.3.0) (2018-08-16) ### Bug Fixes * **props:** allow symbols to pass through ([97b3464](https://github.com/npm/figgy-pudding/commit/97b3464)) ### Features * **pudding:** iteration and serialization support ([0aaa50d](https://github.com/npm/figgy-pudding/commit/0aaa50d)) ## [3.2.1](https://github.com/npm/figgy-pudding/compare/v3.2.0...v3.2.1) (2018-08-15) ### Bug Fixes * **aliases:** make reverse aliases work correctly ([76a255e](https://github.com/npm/figgy-pudding/commit/76a255e)) # [3.2.0](https://github.com/npm/figgy-pudding/compare/v3.1.0...v3.2.0) (2018-07-26) ### Bug Fixes * **concat:** have concat spit out a proxy, too ([64e3495](https://github.com/npm/figgy-pudding/commit/64e3495)) ### Features * **default:** pass the pudding itself to default fns ([d9d9e09](https://github.com/npm/figgy-pudding/commit/d9d9e09)) # [3.1.0](https://github.com/npm/figgy-pudding/compare/v3.0.0...v3.1.0) (2018-04-08) ### Features * **opts:** allow direct option fetching without .get() ([ca77aad](https://github.com/npm/figgy-pudding/commit/ca77aad)) # [3.0.0](https://github.com/npm/figgy-pudding/compare/v2.0.1...v3.0.0) (2018-04-06) ### Bug Fixes * **ci:** oops -- forgot to update CI config ([7a40563](https://github.com/npm/figgy-pudding/commit/7a40563)) * **get:** make provider lookup order like Object.assign ([33ff89b](https://github.com/npm/figgy-pudding/commit/33ff89b)) ### Features * **concat:** add .concat() method to opts ([d310fce](https://github.com/npm/figgy-pudding/commit/d310fce)) ### meta * drop support for node@4 and node@7 ([9f8a61c](https://github.com/npm/figgy-pudding/commit/9f8a61c)) ### BREAKING CHANGES * node@4 and node@7 are no longer supported * **get:** shadow order for properties in providers is reversed ## [2.0.1](https://github.com/npm/figgy-pudding/compare/v2.0.0...v2.0.1) (2018-03-16) ### Bug Fixes * **opts:** ignore non-object providers ([7b9c0f8](https://github.com/npm/figgy-pudding/commit/7b9c0f8)) # [2.0.0](https://github.com/npm/figgy-pudding/compare/v1.0.0...v2.0.0) (2018-03-16) ### Features * **api:** overhauled API with new opt handling concept ([e6cc929](https://github.com/npm/figgy-pudding/commit/e6cc929)) * **license:** relicense to ISC ([87479aa](https://github.com/npm/figgy-pudding/commit/87479aa)) ### BREAKING CHANGES * **license:** the license has been changed from CC0-1.0 to ISC. * **api:** this is a completely different approach than previously used by this library. See the readme for the new API and an explanation. package/LICENSE.md000644 0000001363 3560116604 010667 0ustar00000000 000000 ISC License Copyright (c) npm, Inc. Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. package/README.md000644 0000016754 3560116604 010554 0ustar00000000 000000 # Note: pending imminent deprecation **This module will be deprecated once npm v7 is released. Please do not rely on it more than absolutely necessary (ie, only if you are depending on it for use with npm v6 internal dependencies).** ---- # figgy-pudding [![npm version](https://img.shields.io/npm/v/figgy-pudding.svg)](https://npm.im/figgy-pudding) [![license](https://img.shields.io/npm/l/figgy-pudding.svg)](https://npm.im/figgy-pudding) [![Travis](https://img.shields.io/travis/npm/figgy-pudding.svg)](https://travis-ci.org/npm/figgy-pudding) [![Coverage Status](https://coveralls.io/repos/github/npm/figgy-pudding/badge.svg?branch=latest)](https://coveralls.io/github/npm/figgy-pudding?branch=latest) [`figgy-pudding`](https://github.com/npm/figgy-pudding) is a small JavaScript library for managing and composing cascading options objects -- hiding what needs to be hidden from each layer, without having to do a lot of manual munging and passing of options. ### The God Object is Dead! ### Now Bring Us Some Figgy Pudding! ## Install `$ npm install figgy-pudding` ## Table of Contents * [Example](#example) * [Features](#features) * [API](#api) * [`figgyPudding(spec)`](#figgy-pudding) * [`PuddingFactory(values)`](#pudding-factory) * [`opts.get()`](#opts-get) * [`opts.concat()`](#opts-concat) * [`opts.toJSON()`](#opts-to-json) * [`opts.forEach()`](#opts-for-each) * [`opts[Symbol.iterator]()`](#opts-symbol-iterator) * [`opts.entries()`](#opts-entries) * [`opts.keys()`](#opts-keys) * [`opts.value()`](#opts-values) ### Example ```javascript // print-package.js const fetch = require('./fetch.js') const puddin = require('figgy-pudding') const PrintOpts = puddin({ json: { default: false } }) async function printPkg (name, opts) { // Expected pattern is to call this in every interface function. If `opts` is // not passed in, it will automatically create an (empty) object for it. opts = PrintOpts(opts) const uri = `https://registry.npmjs.com/${name}` const res = await fetch(uri, opts.concat({ // Add or override any passed-in configs and pass them down. log: customLogger })) // The following would throw an error, because it's not in PrintOpts: // console.log(opts.log) if (opts.json) { return res.json() } else { return res.text() } } console.log(await printPkg('figgy', { // Pass in *all* configs at the toplevel, as a regular object. json: true, cache: './tmp-cache' })) ``` ```javascript // fetch.js const puddin = require('figgy-pudding') const FetchOpts = puddin({ log: { default: require('npmlog') }, cache: {} }) module.exports = async function (..., opts) { opts = FetchOpts(opts) } ``` ### Features * hide options from layer that didn't ask for it * shared multi-layer options * make sure `opts` argument is available * transparent key access like normal keys, through a Proxy. No need for`.get()`! * default values * key aliases * arbitrary key filter functions * key/value iteration * serialization * 100% test coverage using `tap --100` ### API #### `> figgyPudding({ key: { default: val } | String }, [opts]) -> PuddingFactory` Defines an Options constructor that can be used to collect only the needed options. An optional `default` property for specs can be used to specify default values if nothing was passed in. If the value for a spec is a string, it will be treated as an alias to that other key. ##### Example ```javascript const MyAppOpts = figgyPudding({ lg: 'log', log: { default: () => require('npmlog') }, cache: {} }) ``` #### `> PuddingFactory(...providers) -> FiggyPudding{}` Instantiates an options object defined by `figgyPudding()`, which uses `providers`, in order, to find requested properties. Each provider can be either a plain object, a `Map`-like object (that is, one with a `.get()` method) or another figgyPudding `Opts` object. When nesting `Opts` objects, their properties will not become available to the new object, but any further nested `Opts` that reference that property _will_ be able to read from their grandparent, as long as they define that key. Default values for nested `Opts` parents will be used, if found. ##### Example ```javascript const ReqOpts = figgyPudding({ follow: {} }) const opts = ReqOpts({ follow: true, log: require('npmlog') }) opts.follow // => true opts.log // => Error: ReqOpts does not define `log` const MoreOpts = figgyPudding({ log: {} }) MoreOpts(opts).log // => npmlog object (passed in from original plain obj) MoreOpts(opts).follow // => Error: MoreOpts does not define `follow` ``` #### `> opts.get(key) -> Value` Gets a value from the options object. ##### Example ```js const opts = MyOpts(config) opts.get('foo') // value of `foo` opts.foo // Proxy-based access through `.get()` ``` #### `> opts.concat(...moreProviders) -> FiggyPudding{}` Creates a new opts object of the same type as `opts` with additional providers. Providers further to the right shadow providers to the left, with properties in the original `opts` being shadows by the new providers. ##### Example ```js const opts = MyOpts({x: 1}) opts.get('x') // 1 opts.concat({x: 2}).get('x') // 2 opts.get('x') // 1 (original opts object left intact) ``` #### `> opts.toJSON() -> Value` Converts `opts` to a plain, JSON-stringifiable JavaScript value. Used internally by JavaScript to get `JSON.stringify()` working. Only keys that are readable by the current pudding type will be serialized. ##### Example ```js const opts = MyOpts({x: 1}) opts.toJSON() // {x: 1} JSON.stringify(opts) // '{"x":1}' ``` #### `> opts.forEach((value, key, opts) => {}, thisArg) -> undefined` Iterates over the values of `opts`, limited to the keys readable by the current pudding type. `thisArg` will be used to set the `this` argument when calling the `fn`. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) opts.forEach((value, key) => console.log(key, '=', value)) ``` #### `> opts.entries() -> Iterator<[[key, value], ...]>` Returns an iterator that iterates over the keys and values in `opts`, limited to the keys readable by the current pudding type. Each iteration returns an array of `[key, value]`. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).entries()] // [['x', 1], ['y', 2]] ``` #### `> opts[Symbol.iterator]() -> Iterator<[[key, value], ...]>` Returns an iterator that iterates over the keys and values in `opts`, limited to the keys readable by the current pudding type. Each iteration returns an array of `[key, value]`. Makes puddings work natively with JS iteration mechanisms. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2})] // [['x', 1], ['y', 2]] for (let [key, value] of opts({x: 1, y: 2})) { console.log(key, '=', value) } ``` #### `> opts.keys() -> Iterator<[key, ...]>` Returns an iterator that iterates over the keys in `opts`, limited to the keys readable by the current pudding type. ##### Example ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).keys()] // ['x', 'y'] ``` #### `> opts.values() -> Iterator<[value, ...]>` Returns an iterator that iterates over the values in `opts`, limited to the keys readable by the current pudding type. ##### Example ' ```js const opts = MyOpts({x: 1, y: 2}) [...opts({x: 1, y: 2}).values()] // [1, 2] ```