Socket
Socket
Sign inDemoInstall

@rygent/spotify

Package Overview
Dependencies
Maintainers
1
Versions
136
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@rygent/spotify - npm Package Compare versions

Comparing version 1.2.0-next.115383d.0 to 1.2.0-next.4557c1f.0

67

dist/index.d.ts

@@ -0,1 +1,46 @@

/**
* Object for search parameters for searching for tracks, playlists, artists or albums.
* See: [Search for an item](https://developer.spotify.com/web-api/search-item/)
*
* `q` and `type` are required in the API. Previous versions of the type declarations marked them
* as optional in order for external libraries to "implement them as function call parameters instead".
* Now, the type declaration shall mark them as required. If necessary, one can consider this to be a
* "breaking change". In that case, one can use TypeScript's built-in utility type `Omit<T, K>`.
* For example, one can remove the `q` and `type` by annotating the type
* as `Omit<SearchForItemParameterObject, "q" | "type">`.
*/
interface SearchForItemParameterObject {
/**
* The search query's keywords (and optional field filters and operators).
*/
q: string;
/**
* A comma-separated list of item types to search across. Valid types are: `album`, `artist`, `playlist`, `track`, `shows`, and `episodes`.
* Search results include hits from all the specified item types.
* For example: `q=name:abacab&type=album,track` returns both albums and tracks with `“abacab”` included in their name.
*/
type: string;
/**
* An [ISO 3166-1 alpha-2 country code](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-2) or the string `from_token`.
* If a country code is specified, only artists, albums, and tracks with content that is playable in that market is returned.
*/
market?: string | undefined;
/**
* The maximum number of results to return.
* Default: `20`. Minimum: `1`. Maximum: `50`.
*/
limit?: number | undefined;
/**
* The index of the first result to return.
* Default: `0` (first result). Maximum offset (including limit): `2,000`.
* Use with limit to get the next page of search results.
*/
offset?: number | undefined;
/**
* Possible values: `audio`.
* If `include_external=audio` is specified, the response will include any relevant audio content that is hosted externally.
* By default external content is filtered out from responses.
*/
include_external?: string | undefined;
}
interface RestrictionsObject {

@@ -590,24 +635,12 @@ reason: string;

}
type SearchType = 'artist' | 'album' | 'track' | 'playlist' | 'show' | 'episode';
declare class Spotify {
private readonly endpoint;
private readonly oauth2;
private clientId;
private clientSecret;
private bearer;
constructor(configuration: {
declare class Client {
private readonly utils;
constructor(options: {
id: string;
secret: string;
});
search(variable: {
type: SearchType;
query: string;
offset?: number;
limit?: number;
}): Promise<SearchResponse>;
private getAccessToken;
private generateBearerToken;
search(options: Omit<SearchForItemParameterObject, 'market'>): Promise<SearchResponse>;
}
export { Spotify };
export { Client as Spotify };

@@ -1,62 +0,34 @@

"use strict";
"use strict";
'use strict';
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
// src/lib/structures/Util.ts
var Util = class {
static {
__name(this, "Util");
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => {
__defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
return value;
};
// src/index.ts
var src_exports = {};
__export(src_exports, {
Spotify: () => Spotify
});
module.exports = __toCommonJS(src_exports);
var import_undici = require("undici");
var _Spotify = class _Spotify {
constructor(configuration) {
__publicField(this, "endpoint", "https://api.spotify.com/v1/");
__publicField(this, "oauth2", "https://accounts.spotify.com/api/token/");
__publicField(this, "clientId");
__publicField(this, "clientSecret");
__publicField(this, "bearer", {
expire: null,
token: null
clientId;
clientSecret;
bearer = {
expire: null,
token: null
};
constructor(options) {
this.clientId = options.id;
this.clientSecret = options.secret;
}
async fetch(options) {
const { endpoint, params } = options;
const response = await fetch(`https://api.spotify.com/v1${endpoint}${params}`, {
method: "GET",
headers: {
Authorization: `Bearer ${await this.getAccessToken()}`
}
});
this.clientId = configuration.id;
this.clientSecret = configuration.secret;
}
async search(variable) {
const { type, query, offset = 0, limit = 10 } = variable;
try {
const { body } = await (0, import_undici.request)(`${this.endpoint}search?q=${encodeURIComponent(query)}&type=${type}&offset=${offset}&limit=${limit}`, {
method: "GET",
headers: {
Authorization: `Bearer ${await this.getAccessToken()}`
}
});
return body.json();
} catch (error) {
throw new Error(
`Received status ${error.status} (${error.message})`
);
if (response.status === 200) {
const result = await response.json();
return result;
}
throw new Error(`Received status ${response.status} (${response.statusText})`);
}

@@ -72,26 +44,38 @@ getAccessToken() {

async generateBearerToken() {
try {
const { body } = await (0, import_undici.request)(this.oauth2, {
method: "POST",
body: `grant_type=client_credentials&client_id=${this.clientId}&client_secret=${this.clientSecret}`,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
const response = await body.json();
this.bearer = { token: response.access_token, expire: Date.now() + response.expires_in * 1e3 };
return response.access_token;
} catch (error) {
throw new Error(
`Received status ${error.status} (${error.message})`
);
const params = `grant_type=client_credentials&client_id=${this.clientId}&client_secret=${this.clientSecret}`;
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
body: params,
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
});
if (response.status === 200) {
const result = await response.json();
this.bearer = { token: result.access_token, expire: Date.now() + result.expires_in * 1e3 };
return result.access_token;
}
throw new Error(`Received status ${response.status} (${response.statusText})`);
}
};
__name(_Spotify, "Spotify");
var Spotify = _Spotify;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
Spotify
});
// src/lib/structures/Client.ts
var Client = class {
static {
__name(this, "Client");
}
utils;
constructor(options) {
this.utils = new Util({ id: options.id, secret: options.secret });
}
async search(options) {
const { type, q, offset = 0, limit = 20 } = options;
const params = `?q=${encodeURIComponent(q)}&type=${type}&offset=${offset}&limit=${limit}`;
const response = await this.utils.fetch({ endpoint: "/search", params });
return response;
}
};
exports.Spotify = Client;
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map
{
"name": "@rygent/spotify",
"version": "1.2.0-next.115383d.0",
"description": "A simple to use API library for the Spotify REST API.",
"version": "1.2.0-next.4557c1f.0",
"description": "An UNOFFICIAL wrapper for Spotify REST API written in typescript.",
"license": "MIT",

@@ -10,10 +10,16 @@ "main": "./dist/index.js",

"exports": {
"require": "./dist/index.js",
"import": "./dist/index.mjs",
"types": "./dist/index.d.ts"
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"scripts": {
"build": "tsup",
"test": "vitest run",
"lint": "eslint src --ext ts --fix -c ../../.eslintrc",
"build": "tsup",
"lint": "eslint src --ext ts",
"format": "prettier . --write",
"prepack": "yarn build",

@@ -23,3 +29,3 @@ "bump": "cliff-jumper"

"devDependencies": {
"@favware/cliff-jumper": "^2.2.0",
"@favware/cliff-jumper": "^2.2.1",
"@vitest/coverage-v8": "^0.34.6",

@@ -30,5 +36,2 @@ "tsup": "^7.2.0",

},
"dependencies": {
"undici": "^5.27.0"
},
"homepage": "https://github.com/Rygent/Utilities/tree/main/packages/spotify",

@@ -51,2 +54,8 @@ "repository": {

},
"keywords": [
"spotify",
"wrapper",
"api",
"spotify-api"
],
"publishConfig": {

@@ -53,0 +62,0 @@ "access": "public"

@@ -1,10 +0,10 @@

# Spotify API
# Spotify Wrapper
A simple to use API library for the Spotify REST API.
Only supports searching for `track | album | artist` however the 2 former ones have not been tested.
An UNOFFICIAL wrapper for Spotify REST API written in typescript.
#### What's Different?
You can visit the official docs for Spotify [here][spotify docs] to find out everything you can do.
- Uses `undici` instead.
- The code base has been completely rewritten to typescript.
> [!IMPORTANT]
>
> This project is still under development, not everything supported yet.

@@ -16,32 +16,31 @@ ## Installation

yarn add @rygent/spotify
pnpm i @rygent/spotify
```
## API
## Usage
### Search
```ts
import { Spotify } from '@rygent/spotify';
import config from './config.js';
```js
<spotify>.search({ type: 'artist|album|track', query: 'My search query', offset: 0, limit: 20 });
const spotify = new Spotify({
id: config.client_id, // Your client_id
secret: config.client_secret // Your client_secret
});
await spotify.search({ type: 'track,album', q: 'Happier Than Ever' });
await spotify.search({ type: 'artist', q: 'Billie Eilish' });
```
#### Example
> [!NOTE]
>
> - **offset**: This property is optional and the default value is `0`.
> - **limit**: This property is optional and the default value is `20`.
```js
const { Spotify } = require('@rygent/spotify');
---
const spotify = new Spotify({
id: 'your client id',
secret: 'your client secret'
});
<i>This project is not affiliated with nor endorsed by Spotify.</i>
// later on ...
await spotify.search({ type: 'track', query: 'I Me Mine' });
await spotify.search({ type: 'album', query: 'Let It Be' });
await spotify.search({ type: 'artist', query: 'The Beatles' });
```
<!-- LINKS -->
> **Note**
> The `offset` property is optional and the search will default to `0` if one is not supplied.
> **Note**
> The `limit` property is optional and the search will default to `20` if one is not supplied.
[spotify docs]: https://developer.spotify.com/documentation/web-api

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc