Skip to content

Commit

Permalink
Initial implementation, tests, readme, types
Browse files Browse the repository at this point in the history
  • Loading branch information
ljharb committed Feb 16, 2024
1 parent cb5f2e5 commit 5a73627
Show file tree
Hide file tree
Showing 18 changed files with 776 additions and 10 deletions.
25 changes: 25 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"root": true,

"extends": "@ljharb",

"rules": {
"complexity": 0,
"id-length": 0,
"max-lines-per-function": 0,
"new-cap": ["error", {
"capIsNewExceptions": [
"GetIntrinsic",
],
}],
},

"overrides": [
{
"files": "test/**",
"rules": {
"max-lines-per-function": "off",
},
},
],
}
12 changes: 12 additions & 0 deletions .github/FUNDING.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# These are supported funding model platforms

github: [ljharb]
patreon: # Replace with a single Patreon username
open_collective: # Replace with a single Open Collective username
ko_fi: # Replace with a single Ko-fi username
tidelift: npm/define-accessor-property
community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
liberapay: # Replace with a single Liberapay username
issuehunt: # Replace with a single IssueHunt username
otechie: # Replace with a single Otechie username
custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
12 changes: 12 additions & 0 deletions .github/workflows/node-aught.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: 'Tests: node.js < 10'

on: [pull_request, push]

jobs:
tests:
uses: ljharb/actions/.github/workflows/node.yml@main
with:
range: '< 10'
type: minors
command: npm run tests-only
skip-ls-check: true # io.js's npm can't handle `@types/*` deps in `npm ls`
10 changes: 10 additions & 0 deletions .github/workflows/node-pretest.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
name: 'Tests: pretest/posttest'

on: [pull_request, push]

permissions:
contents: read

jobs:
tests:
uses: ljharb/actions/.github/workflows/pretest.yml@main
11 changes: 11 additions & 0 deletions .github/workflows/node-tens.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
name: 'Tests: node.js >= 10'

on: [pull_request, push]

jobs:
tests:
uses: ljharb/actions/.github/workflows/node.yml@main
with:
range: '>= 10'
type: minors
command: npm run tests-only
9 changes: 9 additions & 0 deletions .github/workflows/rebase.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
name: Automatic Rebase

on: [pull_request_target]

jobs:
_:
uses: ljharb/actions/.github/workflows/rebase.yml@main
secrets:
token: ${{ secrets.GITHUB_TOKEN }}
12 changes: 12 additions & 0 deletions .github/workflows/require-allow-edits.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
name: Require “Allow Edits”

on: [pull_request_target]

jobs:
_:
name: "Require “Allow Edits”"

runs-on: ubuntu-latest

steps:
- uses: ljharb/require-allow-edits@main
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -133,3 +133,5 @@ dist
npm-shrinkwrap.json
package-lock.json
yarn.lock

.npmignore
2 changes: 2 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
package-lock=false
allow-same-version=true
message=v%s
13 changes: 13 additions & 0 deletions .nycrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"all": true,
"check-coverage": false,
"reporter": ["text-summary", "text", "html", "json"],
"lines": 86,
"statements": 85.93,
"functions": 82.43,
"branches": 76.06,
"exclude": [
"coverage",
"test"
]
}
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Changelog

All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
2 changes: 1 addition & 1 deletion LICENSE
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
MIT License

Copyright (c) 2024 Jordan Harband
Copyright (c) 2023 Jordan Harband

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
Expand Down
82 changes: 80 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1,80 @@
# define-accessor-property
Define an accessor property on an object. Will either throw, or fall back to assignment in loose mode, in an engine without descriptors.
# define-accessor-property <sup>[![Version Badge][npm-version-svg]][package-url]</sup>

[![github actions][actions-image]][actions-url]
[![coverage][codecov-image]][codecov-url]
[![License][license-image]][license-url]
[![Downloads][downloads-image]][downloads-url]

[![npm badge][npm-badge-png]][package-url]

Define an accessor property on an object. In an engine without descriptors, in loose mode, when only a getter is provided, nonEnumerable is false, and nonConfigurable is false, wil fall back to assignment - otherwise, it will throw.

The two `non*` options can also be passed `null`, which will use the existing state if available.

The `loose` option will mean that if you attempt to set a nonconfigurable/nonwritable accessor property with `set`, in an environment without descriptor support, it will fall back to normal assignment (and eagerly evaluate the getter).

## Usage

```javascript
var defineAccessorProperty = require('define-accessor-property');
var assert = require('assert');

var str = 'value';
var strThunk = function () { return str; };
var strSetter = function (v) { str = v; };
var random = function () { return Math.random(); };

var obj = {};
defineAccessorProperty(
obj,
'key',
{
get: strThunk,
set: strSetter,
}
);
defineAccessorProperty(
obj,
'key2',
{
get: random, // at least one of "get" or "set" must be provided
nonConfigurable: true, // optional
nonEnumerable: true, // optional
loose: false, // optional
}
);

assert.deepEqual(
Object.getOwnPropertyDescriptors(obj),
{
key: {
configurable: true,
enumerable: true,
get: strThunk,
set: strSetter,
},
key2: {
configurable: false,
enumerable: false,
get: random,
set: undefined,
},
}
);
```

[package-url]: https://npmjs.org/package/define-accessor-property
[npm-version-svg]: https://versionbadg.es/ljharb/define-accessor-property.svg
[deps-svg]: https://david-dm.org/ljharb/define-accessor-property.svg
[deps-url]: https://david-dm.org/ljharb/define-accessor-property
[dev-deps-svg]: https://david-dm.org/ljharb/define-accessor-property/dev-status.svg
[dev-deps-url]: https://david-dm.org/ljharb/define-accessor-property#info=devDependencies
[npm-badge-png]: https://nodei.co/npm/define-accessor-property.png?downloads=true&stars=true
[license-image]: https://img.shields.io/npm/l/define-accessor-property.svg
[license-url]: LICENSE
[downloads-image]: https://img.shields.io/npm/dm/define-accessor-property.svg
[downloads-url]: https://npm-stat.com/charts.html?package=define-accessor-property
[codecov-image]: https://codecov.io/gh/ljharb/define-accessor-property/branch/main/graphs/badge.svg
[codecov-url]: https://app.codecov.io/gh/ljharb/define-accessor-property/
[actions-image]: https://img.shields.io/endpoint?url=https://github-actions-badge-u3jn4tfpocch.runkit.sh/ljharb/define-accessor-property
[actions-url]: https://github.com/ljharb/define-accessor-property/actions
23 changes: 23 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
type Getter<T> = () => T;
type Setter<T> = (value: T) => void;

declare function defineAccessorProperty(
obj: Record<PropertyKey, unknown>,
key: keyof typeof obj,
options: {
loose?: boolean;
nonConfigurable?: boolean | null;
nonEnumerable?: boolean | null;
} & (
| {
get: Getter<typeof obj[typeof key]>,
set?: Setter<typeof obj[typeof key]>,
}
| {
get?: Getter<typeof obj[typeof key]>,
set: Setter<typeof obj[typeof key]>,
}
)
): void;

export = defineAccessorProperty;
65 changes: 65 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
'use strict';

var $defineProperty = require('es-define-property');

var $SyntaxError = require('es-errors/syntax');
var $TypeError = require('es-errors/type');

var gopd = require('gopd');

/** @type {import('.')} */
module.exports = function defineAccessorProperty(obj, property, options) {
if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) {
throw new $TypeError('`obj` must be an object or a function`');
}
if (typeof property !== 'string' && typeof property !== 'symbol') {
throw new $TypeError('`property` must be a string or a symbol`');
}
if (!options || typeof options !== 'object') {
throw new $TypeError('`options` must be an object');
}

var get = options.get;
var set = options.set;
if (
(!get && !set)
|| (typeof get !== 'function' && typeof get !== 'undefined')
|| (typeof set !== 'function' && typeof set !== 'undefined')
) {
throw new $TypeError('At least one of `get` and `set` must be provided, and if provided, must be functions.');
}

if ('loose' in options && typeof options.loose !== 'boolean') {
throw new $TypeError('`loose`, if provided, must be a boolean');
}
if ('nonConfigurable' in options && typeof options.nonConfigurable !== 'boolean' && options.nonConfigurable !== null) {
throw new $TypeError('`nonConfigurable`, if provided, must be a boolean or null');
}
if ('nonEnumerable' in options && typeof options.nonEnumerable !== 'boolean' && options.nonEnumerable !== null) {
throw new $TypeError('`nonEnumerable`, if provided, must be a boolean or null');
}

var nonEnumerable = options.nonEnumerable;
var nonConfigurable = options.nonConfigurable;
var loose = !!options.loose;

/* @type {false | TypedPropertyDescriptor<unknown>} */
var desc = !!gopd
&& $defineProperty
&& (nonConfigurable === null || nonEnumerable === null)
&& gopd(obj, property);

if ($defineProperty) {
$defineProperty(obj, property, {
configurable: nonConfigurable === null && desc ? desc.configurable : !nonConfigurable,
enumerable: nonEnumerable === null && desc ? desc.enumerable : !nonEnumerable,
get: options.get,
set: options.set
});
} else if (loose && options.get && !options.set && !nonEnumerable && !nonConfigurable) {
// must fall back to [[Set]], and was not explicitly asked to make a setter, non-enumerable, or non-configurable
obj[property] = options.get.call(obj); // eslint-disable-line no-param-reassign
} else {
throw new $SyntaxError('This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.');
}
};
Loading

0 comments on commit 5a73627

Please sign in to comment.