2
0
mirror of https://github.com/iconify/collections-json.git synced 2024-11-21 20:15:12 +00:00

Merge pull request #17 from userquin/feat/esm-support

feat: add esm support
This commit is contained in:
Vjacheslav Trushkin 2021-09-25 13:16:16 +03:00 committed by GitHub
commit a783e97b0f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
20 changed files with 5048 additions and 55 deletions

10
.editorconfig Normal file
View File

@ -0,0 +1,10 @@
# editorconfig.org
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

2
.eslintignore Normal file
View File

@ -0,0 +1,2 @@
dist
node_modules

3
.eslintrc.json Normal file
View File

@ -0,0 +1,3 @@
{
"extends": "@antfu"
}

4
.gitignore vendored
View File

@ -1,2 +1,4 @@
.idea .idea/
.DS_Store .DS_Store
dist/
node_modules/

5
.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,5 @@
{
"recommendations": [
"dbaeumer.vscode-eslint"
]
}

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"typescript.tsdk": "node_modules/typescript/lib"
}

12
jest.cjs.config.ts Normal file
View File

@ -0,0 +1,12 @@
import { buildConfiguration } from './jest/jest.shared.config'
export default buildConfiguration({
testMatch: [
'**/?(*.)+(cjs).+(spec|test).+(ts|tsx|js)',
],
globals: {
'ts-jest': {
useESM: false,
},
},
})

12
jest.esm.config.ts Normal file
View File

@ -0,0 +1,12 @@
import { buildConfiguration } from './jest/jest.shared.config'
export default buildConfiguration({
testMatch: [
'**/?(*.)+(esm).+(spec|test).+(ts|tsx|js)',
],
globals: {
'ts-jest': {
useESM: true,
},
},
})

View File

@ -0,0 +1,18 @@
import type { Config } from '@jest/types'
// see https://jestjs.io/docs/ecmascript-modules
export const buildConfiguration = (configuration: Partial<Config.InitialOptions>): Config.InitialOptions => {
return Object.assign({}, {
verbose: true,
moduleDirectories: [
'node_modules',
'src',
],
moduleFileExtensions: ['ts', 'js'],
extensionsToTreatAsEsm: ['.ts'],
transform: {
'^.+\\.ts$': 'ts-jest',
},
}, configuration)
}

View File

@ -1,49 +0,0 @@
/**
* This file is part of the iconify.design libraries.
*
* (c) Vjacheslav Trushkin <cyberalien@gmail.com>
*
* @license MIT
*
* For the full copyright and license information, please view the license.txt
* file that is available in this file's directory.
*/
"use strict";
const path = require('path');
const fs = require('fs');
const dir = path.dirname(__dirname);
module.exports = {
/**
* Get root directory of this package
* (not really useful in Node.js because require can do it, but added anyway to match php code)
*
* @returns {string}
*/
rootDir: () => dir,
/**
* Locate JSON file
*
* @param {string} name Collection name
* @returns {string} Path to collection json file
*/
locate: name => dir + '/json/' + name + '.json',
/**
* Get list of collections
*
* @return {object|null}
*/
collections: () => {
try {
let data = fs.readFileSync(dir + '/collections.json', 'utf8');
data = JSON.parse(data);
return data;
} catch (err) {
return null;
}
}
};

View File

@ -1,13 +1,55 @@
{ {
"name": "@iconify/json", "name": "@iconify/json",
"description": "Iconify icons collection in JSON format",
"license": "MIT",
"version": "1.1.401", "version": "1.1.401",
"description": "Iconify icons collection in JSON format",
"homepage": "https://iconify.design/icon-sets/", "homepage": "https://iconify.design/icon-sets/",
"main": "lib/finder.js",
"bugs": "https://github.com/iconify/collections-json/issues", "bugs": "https://github.com/iconify/collections-json/issues",
"repository": { "repository": {
"type": "git", "type": "git",
"url": "git+ssh://git@github.com/iconify/collections-json.git" "url": "git+ssh://git@github.com/iconify/collections-json.git"
},
"license": "MIT",
"exports": {
".": {
"require": "./dist/index.js",
"import": "./dist/index.mjs"
}
},
"files": [
"dist",
"json",
"lib",
"collections.json",
"collections.md",
"composer.md",
"readme.md"
],
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "dist/index.d.ts",
"scripts": {
"build": "rimraf dist && tsup src/index.ts --format cjs,esm --dts",
"test-esm": "jest --clearCache && cross-env NODE_OPTIONS=--experimental-vm-modules npx jest --config=jest.esm.config.ts",
"test-cjs": "yarn build && jest --clearCache && jest --config=jest.cjs.config.ts",
"test-locate-esm": "jest --clearCache && cross-env NODE_OPTIONS=--experimental-vm-modules npx jest --config=jest.esm.config.ts src/locate.esm.test.ts -i",
"test-locate-cjs": "yarn build && jest --clearCache && jest --config=jest.cjs.config.ts src/locate.cjs.test.ts -i"
},
"dependencies": {
"pathe": "^0.0.2"
},
"devDependencies": {
"@antfu/eslint-config": "^0.9.0",
"@types/jest": "^27.0.1",
"@types/node": "^16.9.1",
"@typescript-eslint/eslint-plugin": "^4.31.0",
"cross-env": "^7.0.3",
"eslint": "^7.32.0",
"esno": "^0.9.1",
"jest": "^27.2.0",
"jest-each": "^27.2.0",
"ts-jest": "^27.0.5",
"ts-node": "^10.2.1",
"tsup": "^4.14.0",
"typescript": "^4.4.3"
} }
} }

452
src/index.ts Normal file
View File

@ -0,0 +1,452 @@
/**
* This file is part of the iconify.design libraries.
*
* (c) Vjacheslav Trushkin <cyberalien@gmail.com>
*
* @license MIT
*
* For the full copyright and license information, please view the license.txt
* file that is available in this file's directory.
*/
import { PathLike, promises as fs } from 'fs'
import { fileURLToPath } from 'url'
import { dirname, join } from 'pathe'
/**
* Icon dimensions.
*
* Used in:
* icon (as is)
* alias (overwrite icon's properties)
* root of JSON file (default values)
*/
export interface IconifyDimensions {
/**
* Left position of viewBox.
*
* @default 0
*/
left?: number
/**
* Top position of viewBox.
*
* @default 0
*/
top?: number
/**
* Width of viewBox.
*
* @default 16
*/
width?: number
/**
* height of viewBox.
*
* @default 16
*/
height?: number
}
/**
* Icon transformations.
*
* Used in:
* icon (as is)
* alias (merged with icon's properties)
* root of JSON file (default values)
*/
export interface IconifyTransformations {
/**
* rotation, values: 0 = 0deg, 1 = 90deg, 2 = 180deg, 3 = 270deg
*
* @default 0
*/
rotate?: 0 | 1 | 2 | 3
/**
* horizontal flip
*
* @default false
*/
hFlip?: boolean
/**
* vertical flip
*
* @default false
*/
vFlip?: boolean
}
/**
* Icon alignment.
*/
export interface IconifyAlignment {
/**
* Icon horizontal alignment.
*
* @default 'center'
*/
horizontal: 'center' | 'left' | 'right'
/**
* Icon vertical alignment.
*
* @default 'middle'
*/
vertical: 'middle' | 'top' | 'bottom'
/**
* Slice?
*
* @default false
*/
slice: boolean
}
/**
* Combination of dimensions and transformations.
*/
export interface IconifyOptional extends IconifyDimensions, IconifyTransformations {
}
/**
* Alias.
*/
export interface IconifyAlias extends IconifyOptional {
/**
* Parent icon index without prefix, required.
*/
parent: string
// IconifyOptional properties.
// Alias should have only properties that it overrides.
// Transformations are merged, not overridden. See IconifyTransformations comments.
}
/**
* Icon.
*/
export interface IconifyIcon extends IconifyOptional {
/**
* Icon body: <path d="..." />, required.
*/
body: string
// IconifyOptional properties.
// If property is missing in JSON file, look in root object for default value.
}
/**
* Icon with optional parameters that are provided by API and affect only search
*/
interface APIIconAttributes {
/**
* True if icon is hidden.
*
* Used in icon sets to keep icons that no longer exist, but should still be accessible
* from API, preventing websites from breaking when icon is removed by developer.
*
* @default false
*/
hidden?: boolean
}
export interface ExtendedIconifyIcon extends IconifyIcon, APIIconAttributes {}
export interface ExtendedIconifyAlias extends IconifyAlias, APIIconAttributes {}
/**
* "icons" field of JSON file.
*/
export interface IconifyIcons {
/**
* Index is name of icon, without prefix. Value is ExtendedIconifyIcon object.
*/
[index: string]: ExtendedIconifyIcon
}
/**
* "aliases" field of JSON file.
*/
export interface IconifyAliases {
/**
* Index is name of icon, without prefix. Value is ExtendedIconifyAlias object.
*/
[index: string]: ExtendedIconifyAlias
}
/**
* Iconify collection info.
*/
export interface IconifyInfo {
/**
* Icon set name.
*/
name: string
/**
* Total number of icons.
*/
total?: number
/**
* Version string.
*/
version?: string
/**
* Author information.
*/
author: string | {
/**
* Author name.
*/
name: string
/**
* Link to author's website or icon set website.
*/
url?: string
}
/**
* Link to author's website or icon set website.
*/
url?: string
/**
* License.
*/
license: string | {
/**
* Human readable license.
*/
title: string
/**
* SPDX license identifier.
*/
spdx?: string
/**
* License URL.
*/
url?: string
}
/**
* License URL.
*/
licenseURL?: string
/**
* Array of icons that should be used for samples in icon sets list.
*/
samples: string[]
/**
* Icon grid: number or array of numbers.
*/
height?: number | number[]
/**
* Display height for samples: 16 - 24.
*
* @default 16
*/
displayHeight?: number
/**
* Category on Iconify collections list.
*/
category?: string
/**
* Palette status.
*
* True if icons have predefined color scheme, false if icons use currentColor.
* Icon set should not mix icons with and without palette to simplify search.
*/
palette: string | boolean
}
/**
* Optional themes, old format.
*
* Deprecated because format is unnecessary complicated. Key is meaningless, suffixes and prefixes are mixed together.
*/
export interface LegacyIconifyThemes {
/**
* Key is unique string.
*/
[index: string]: {
/**
* Theme title.
*/
title: string
/**
* Icon prefix or suffix, including dash.
*
* All icons that start with prefix and end with suffix belong to theme.
*
* Example: 'baseline-'
*/
prefix?: string
/**
* Icon suffix or suffix, including dash.
*
* All icons that start with prefix and end with suffix belong to theme.
*
* Example: '-filled'
*/
suffix?: string
}
}
/**
* Characters used in font.
*/
export interface IconifyChars {
/**
* Index is character, such as "f000".
*
* Value is icon name.
*/
[index: string]: string
}
/**
* Icon categories
*/
export interface IconifyCategories {
/**
* Index is category title, such as "Weather".
*
* Value is array of icons that belong to that category.
* Each icon can belong to multiple categories or no categories.
*/
[index: string]: string[]
}
/**
* Meta data stored in JSON file, used for browsing icon set.
*/
export interface IconifyMetaData {
/**
* Icon set information block.
*
* Used for public icon sets, can be skipped for private icon sets.
*/
info?: IconifyInfo
/**
* Characters used in font.
*
* Used for searching by character for icon sets imported from font, exporting icon set to font.
*/
chars?: IconifyChars
/**
* Categories.
*
* Used for filtering icons.
*/
categories?: IconifyCategories
/**
* Optional themes (old format).
*/
themes?: LegacyIconifyThemes
/**
* Optional themes prefixes (new format).
*
* Key is prefix, value is title.
*/
prefixes?: Record<string, string>
/**
* Optional themes suffixes (new format).
*
* Key is suffix, value is title.
*/
suffixes?: Record<string, string>
}
/**
* JSON structure.
*
* All optional values can exist in root of JSON file, used as defaults.
*/
export interface IconifyJSON extends IconifyOptional, IconifyMetaData {
/**
* Prefix for icons in JSON file, required.
*/
prefix: string
/**
* API provider, optional.
*/
provider?: string
/**
* List of icons, required.
*/
icons: IconifyIcons
/**
* Optional aliases.
*/
aliases?: IconifyAliases
/**
* Optional list of missing icons.
*
* Returned by Iconify API when querying for icons that do not exist.
*/
not_found?: string[]
// IconifyOptional properties that are used as default values for icons when icon is missing value.
// If property exists in both icon and root, use value from icon.
// This is used to reduce duplication.
}
/**
* Collection info map
*/
export type IconifyMetaDataCollection = {
[prefix: string]: IconifyMetaData
}
const _dirname = typeof __dirname !== 'undefined'
? __dirname
: dirname(fileURLToPath(import.meta.url))
const dir = join(_dirname, '/..')
// todo@userquin: cleanup
// console.log(`_dirname: ${_dirname}`)
// if (typeof __dirname === 'undefined') {
// if (false/* process.platform === 'win32' */) {
// console.log(`_dirname3: ${dirname(import.meta.url)}`)
// console.log(`_dirname3: ${join(dirname(import.meta.url), '/..')}`)
// console.log(`_dirname3: ${resolve(join(dirname(import.meta.url), '/..'))}`)
// }
// else {
// console.log(`_dirname2: ${dirname(fileURLToPath(import.meta.url))}`)
// console.log(`_dirname2: ${join(fileURLToPath(dirname(import.meta.url)), '/..')}`)
// console.log(`_dirname2: ${normalize(join(dirname(fileURLToPath(import.meta.url)), '/..'))}`)
// }
// }
// console.log(`Normalized _dirname: ${normalize(_dirname)}`)
// console.log(`Resolve _dirname: ${resolve(_dirname, '..')}`)
// console.log(`Normalized _dirname: ${dir}`)
/**
* Locate JSON file
*
* @param {string} name Collection name
* @returns {string} Path to collection json file
*/
export const locate = (name: string): PathLike => join(dir, `./json/${name}.json`)
/**
* Loads a collection.
*
* @param {PathLike} path The path to locate the `json` collection file.
* @return {Promise<IconifyJSON>}
*/
export const loadCollection = async(path: PathLike): Promise<IconifyJSON> => {
return JSON.parse(await fs.readFile(path, 'utf8'))
}
/**
* Get a collection.
*
* @param {string} name The name of the collection
* @return {Promise<IconifyJSON>}
*/
export const lookupCollection = async(name: string): Promise<IconifyJSON> => {
return await loadCollection(locate(name))
}
/**
* Get list of collections info.
*
* @return {Promise<IconifyMetaDataCollection>}
*/
export const lookupCollections = async(): Promise<IconifyMetaDataCollection> => {
return JSON.parse(await fs.readFile(join(dir, './collections.json'), 'utf8'))
}

View File

@ -0,0 +1,4 @@
import { lookupCollection, lookupCollections } from '../dist'
import { lookupCollectionTest } from './loadCollection.test'
lookupCollectionTest(lookupCollection, lookupCollections)

View File

@ -0,0 +1,4 @@
import { lookupCollectionTest } from './loadCollection.test'
import { lookupCollection, lookupCollections } from '.'
lookupCollectionTest(lookupCollection, lookupCollections)

View File

@ -0,0 +1,32 @@
import type { IconifyMetaDataCollection } from '.'
import { IconifyJSON } from '.'
export const lookupCollectionTest = (
lookupCollection: (name: string) => Promise<IconifyJSON>,
lookupCollections: () => Promise<IconifyMetaDataCollection>,
) => {
let collections: IconifyMetaDataCollection
describe('lookupCollection and lookupCollections', () => {
beforeAll(() => {
return lookupCollections().then((c) => {
collections = c
return Promise.resolve(c)
})
})
test('lookupCollections has data', () => {
expect(collections ? Object.keys(collections).length : 0).toBeGreaterThan(0)
})
test('mdi collection has prefix mdi', async() => {
const collection = await lookupCollection('mdi')
expect(collection.prefix).toBe('mdi')
})
test('websymbol collection has prefix websymbol', async() => {
const collection = await lookupCollection('websymbol')
expect(collection.prefix).toBe('websymbol')
})
test('fa collection has prefix fa', async() => {
const collection = await lookupCollection('fa')
expect(collection.prefix).toBe('fa')
})
})
}

4
src/locate.cjs.test.ts Normal file
View File

@ -0,0 +1,4 @@
import { locate } from '../dist'
import { locateTest } from './locate.test'
locateTest(locate)

4
src/locate.esm.test.ts Normal file
View File

@ -0,0 +1,4 @@
import { locateTest } from './locate.test'
import { locate } from '.'
locateTest(locate)

10
src/locate.test.ts Normal file
View File

@ -0,0 +1,10 @@
import { PathLike } from 'fs'
import { resolve, normalize } from 'pathe'
export const locateTest = (locate: (name: string) => PathLike) => {
test('mdi resolves the json collection', () => {
const received = locate('mdi') as string
const expected = normalize(resolve('./json/mdi.json'))
expect(received).toBe(expected)
})
}

19
tsconfig.json Normal file
View File

@ -0,0 +1,19 @@
{
"compilerOptions": {
"target": "es2017",
"module": "ESNext",
"lib": ["ESNext"],
"esModuleInterop": true,
"strict": true,
"strictNullChecks": true,
"moduleResolution": "Node",
"resolveJsonModule": true,
"skipLibCheck": true,
},
"exclude": [
"**/dist",
"**/node_modules",
"**/test",
"dist"
]
}

4404
yarn.lock Normal file

File diff suppressed because it is too large Load Diff