Repository: ospfranco/link-preview-js
Branch: main
Commit: 98da401d4066
Files: 22
Total size: 645.8 KB
Directory structure:
gitextract_p10xncbh/
├── .github/
│ ├── FUNDING.yml
│ ├── ISSUE_TEMPLATE/
│ │ ├── bug_report.md
│ │ └── feature_request.md
│ └── workflows/
│ ├── publish.yml
│ └── tests.yml
├── .gitignore
├── .npmignore
├── .prettierignore
├── .prettierrc.json
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── __tests__/
│ ├── __snapshots__/
│ │ └── index.spec.ts.snap
│ ├── index.spec.ts
│ └── sampleResponse.json
├── bump-version.sh
├── constants.ts
├── index.ts
├── jest.config.js
├── mise.toml
├── package.json
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/FUNDING.yml
================================================
# These are supported funding model platforms
github: [ospfranco]
================================================
FILE: .github/ISSUE_TEMPLATE/bug_report.md
================================================
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
**Describe the bug**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Browser [e.g. chrome, safari]
- Version [e.g. 22]
**Smartphone (please complete the following information):**
- Device: [e.g. iPhone6]
- OS: [e.g. iOS8.1]
- Browser [e.g. stock browser, safari]
- Version [e.g. 22]
**Additional context**
Add any other context about the problem here.
================================================
FILE: .github/ISSUE_TEMPLATE/feature_request.md
================================================
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.
================================================
FILE: .github/workflows/publish.yml
================================================
name: "publish"
on:
push:
tags:
- "*"
jobs:
publish:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: "22"
- name: Cache dependencies
id: yarn-cache
uses: actions/cache@v3
with:
path: |
**/node_modules
.yarn/install-state.gz
key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ hashFiles('**/package.json', '!node_modules/**') }}
restore-keys: |
${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
${{ runner.os }}-yarn-
- run: yarn install
- name: Update package.json version
run: |
TAG=${GITHUB_REF#refs/tags/}
jq --arg version "$TAG" '.version = $version' package.json > tmp.$$.json && mv tmp.$$.json package.json
- name: Compile typescript
run: yarn build
- uses: JS-DevTools/npm-publish@v3
with:
token: ${{ secrets.NPM_TOKEN }}
- name: Create a Release
uses: elgohr/Github-Release-Action@v5
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
title: Release ${{ github.ref_name }}
tag: ${{ github.ref_name }}
================================================
FILE: .github/workflows/tests.yml
================================================
name: Tests
on: pull_request
jobs:
tests:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Cache dependencies
id: yarn-cache
uses: actions/cache@v3
with:
path: |
**/node_modules
.yarn/install-state.gz
key: ${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}-${{ hashFiles('**/package.json', '!node_modules/**') }}
restore-keys: |
${{ runner.os }}-yarn-${{ hashFiles('yarn.lock') }}
${{ runner.os }}-yarn-
- name: Install dependencies
run: yarn
- name: Run tests
run: yarn test
================================================
FILE: .gitignore
================================================
node_modules/
.vscode/
build/
.DS_Store
================================================
FILE: .npmignore
================================================
.github
__tests__
.vscode
.eslintrc.js
index.ts
jest.config.js
LICENSE
README.md
tsconfig.json
typings.d.ts
================================================
FILE: .prettierignore
================================================
build
================================================
FILE: .prettierrc.json
================================================
{}
================================================
FILE: CONTRIBUTING.md
================================================
If you add new functionality please make sure you add the appropiate tests and the tests are running.
Please also try to keep the style consistant, linter use is a must.
================================================
FILE: LICENSE
================================================
MIT License
Copyright (c) 2019 Oscar Franco
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================
FILE: README.md
================================================
Link Preview JS
npm i link-preview-js
**Before creating an issue**
It's more than likely there is nothing wrong with the library:
- It's very simple; fetch HTML, parse HTML, and search for OpenGraph HTML tags.
- Unless HTML or the OpenGraph standard change, the library will not break
- If the target website you are trying to preview redirects you to a login page **the preview will fail**, because it will parse the login page
- If the target website does not have OpenGraph tags **the preview will most likely fail**, there are some fallbacks but in general, it will not work
- **You cannot preview (fetch) another web page from YOUR web page. This is an intentional security feature of browsers called CORS**
DO NOT FETCH CONTENT DIRECTLY FROM A USERS DEVICE. ONLY RUN THIS IN YOUR SERVER AND SANDBOX IT IF YOU CAN
Browsers block this via cors, but you might be clever like a fox and run this in React Native. This is a bad idea, you are exposing the device user to potentially malicious links
If you use this library and find it useful please consider [sponsoring me](https://github.com/sponsors/ospfranco), open source takes a lot of time and effort.
# Link Preview
Allows you to extract information from an HTTP URL/link (or parse an HTML string) and retrieve meta information such as title, description, images, videos, etc. via **OpenGraph** tags.
## Discord
Join the Discord
https://discord.gg/W9XmqCQCKP
## GOTCHAs
- You cannot request a different domain from your web app (Browsers block cross-origin-requests). If you don't know how _same-origin-policy_ works, [here is a good intro](https://dev.to/lydiahallie/cs-visualized-cors-5b8h), therefore **this library works on Node.js and certain mobile run-times (Cordova or React-Native)**.
- **This library acts as if the user would visit the page, sites might re-direct you to sign-up pages, consent screens, etc.** You can try to change the user-agent header (try with `google-bot` or with `Twitterbot`), but you need to work around these issues yourself.
## API
`getLinkPreview`: you have to pass a string, doesn't matter if it is just a URL or a piece of text that contains a URL, the library will take care of parsing it and returning the info o the first valid HTTP(S) URL info it finds.
`getPreviewFromContent`: useful for passing a pre-fetched Response object from an existing async/etc. call. Refer to the example below for required object values.
```typescript
import { getLinkPreview, getPreviewFromContent } from "link-preview-js";
// pass the link directly
getLinkPreview("https://www.youtube.com/watch?v=MejbOFk7H6c").then((data) =>
console.debug(data)
);
////////////////////////// OR //////////////////////////
// pass a chunk of text
getLinkPreview(
"This is a text supposed to be parsed and the first link displayed https://www.youtube.com/watch?v=MejbOFk7H6c"
).then((data) => console.debug(data));
////////////////////////// OR //////////////////////////
// pass a pre-fetched response object
// The passed response object should include, at minimum:
// {
// data: '...', // response content
// headers: {
// ...
// // should include content-type
// content-type: "text/html; charset=ISO-8859-1",
// ...
// },
// url: 'https://domain.com/' // resolved url
// }
yourAjaxCall(url, (response) => {
getPreviewFromContent(response).then((data) => console.debug(data));
});
```
## Options
Additionally, you can pass an options object which should add more functionality to the parsing of the link
| Property Name | Result |
| -------------------------------------------------------------------------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
| imagesPropertyType (**optional**) (ex: 'og') | Fetches images only with the specified property, `meta[property='${imagesPropertyType}:image']` |
| headers (**optional**) (ex: { 'user-agent': 'googlebot', 'Accept-Language': 'en-US' }) | Add request headers to fetch call |
| timeout (**optional**) (ex: 1000) | Timeout for the request to fail |
| followRedirects (**optional**) (default 'error') | For security reasons, the library does not automatically follow redirects ('error' value), a malicious agent can exploit redirects to steal data, posible values: ('error', 'follow', 'manual') |
| handleRedirects (**optional**) (with followRedirects 'manual') | When followRedirects is set to 'manual' you need to pass a function that validates if the redirectinon is secure, below you can find an example |
| resolveDNSHost (**optional**) | Function that resolves the final address of the detected/parsed URL to prevent SSRF attacks |
| onResponse (**optional**) | Function that handles the response object to allow for managing special cases |
```javascript
getLinkPreview("https://www.youtube.com/watch?v=MejbOFk7H6c", {
imagesPropertyType: "og", // fetches only open-graph images
headers: {
"user-agent": "googlebot", // fetches with googlebot crawler user agent
"Accept-Language": "fr-CA", // fetches site for French language
// ...other optional HTTP request headers
},
timeout: 1000,
}).then((data) => console.debug(data));
```
## SSRF Concerns
Doing requests on behalf of your users or using user-provided URLs is dangerous. One of such attack is trying to fetch a domain that redirects to localhost so the users get the contents of your server (doesn't affect mobile runtimes). To mitigate this attack you can use the resolveDNSHost option:
```ts
// example how to use node's dns resolver
const dns = require("node:dns");
getLinkPreview("http://maliciousLocalHostRedirection.com", {
resolveDNSHost: async (url: string) => {
return new Promise((resolve, reject) => {
const hostname = new URL(url).hostname;
dns.lookup(hostname, (err, address, family) => {
if (err) {
reject(err);
return;
}
resolve(address); // if address resolves to localhost or '127.0.0.1' library will throw an error
});
});
},
}).catch((e) => {
// will throw a detected redirection to localhost
});
```
This might add some latency to your request but prevents loopback attacks.
## Redirections
Same to SSRF, following redirections is dangerous, the library errors by default when the response tries to redirect the user. There are however some simple redirections that are valid (e.g. HTTP to HTTPS) and you might want to allow them, you can do it via:
```ts
await getLinkPreview(`http://google.com/`, {
followRedirects: `manual`,
handleRedirects: (baseURL: string, forwardedURL: string) => {
const urlObj = new URL(baseURL);
const forwardedURLObj = new URL(forwardedURL);
if (
forwardedURLObj.hostname === urlObj.hostname ||
forwardedURLObj.hostname === "www." + urlObj.hostname ||
"www." + forwardedURLObj.hostname === urlObj.hostname
) {
return true;
} else {
return false;
}
},
});
```
## onResponse
In some cases the website might be missing OpenGraph tags and you might want to provide your own custom logic to try to parse data. For example, if the library is unable to detect a description, you might want to use the text value of the first paragraph instead. This callback gives you access to the Cheerio (the library internally used to parse the HTML) instance, as well as the URL object so you could handle cases on a site-by-site basis, if you need to. This callback must return the modified response object
```javascript
await getLinkPreview(`https://example.com/`, {
onResponse: (response, doc, URL) => {
if (URL.hostname == 'example.com') {
response.siteName = 'Example Website';
}
if (!response.description) {
response.description = doc('p').first().text();
}
return response;
},
});
```
## Response
Returns a Promise that resolves with an object describing the provided link.
The info object returned varies depending on the content type (MIME type) returned
in the HTTP response (see below for variations of response). Rejects with an error if the response can not be parsed or if there was no URL in the text provided.
### Text/HTML URL
```javascript
{
url: "https://www.youtube.com/watch?v=MejbOFk7H6c",
title: "OK Go - Needing/Getting - Official Video - YouTube",
siteName: "YouTube",
description: "Buy the video on iTunes: https://itunes.apple.com/us/album/needing-getting-bundle-ep/id508124847 See more about the guitars at: http://www.gretschguitars.com...",
images: ["https://i.ytimg.com/vi/MejbOFk7H6c/maxresdefault.jpg"],
mediaType: "video.other",
contentType: "text/html",
charset: "utf-8"
videos: [],
favicons:["https://www.youtube.com/yts/img/favicon_32-vflOogEID.png","https://www.youtube.com/yts/img/favicon_48-vflVjB_Qk.png","https://www.youtube.com/yts/img/favicon_96-vflW9Ec0w.png","https://www.youtube.com/yts/img/favicon_144-vfliLAfaB.png","https://s.ytimg.com/yts/img/favicon-vfl8qSV2F.ico"]
}
```
### Image URL
```javascript
{
url: "https://media.npr.org/assets/img/2018/04/27/gettyimages-656523922nunes-4bb9a194ab2986834622983bb2f8fe57728a9e5f-s1100-c15.jpg",
mediaType: "image",
contentType: "image/jpeg",
favicons: [ "https://media.npr.org/favicon.ico" ]
}
```
### Audio URL
```javascript
{
url: "https://ondemand.npr.org/anon.npr-mp3/npr/atc/2007/12/20071231_atc_13.mp3",
mediaType: "audio",
contentType: "audio/mpeg",
favicons: [ "https://ondemand.npr.org/favicon.ico" ]
}
```
### Video URL
```javascript
{
url: "https://www.w3schools.com/html/mov_bbb.mp4",
mediaType: "video",
contentType: "video/mp4",
favicons: [ "https://www.w3schools.com/favicon.ico" ]
}
```
### Application URL
```javascript
{
url: "https://assets.curtmfg.com/masterlibrary/56282/installsheet/CME_56282_INS.pdf",
mediaType: "application",
contentType: "application/pdf",
favicons: [ "https://assets.curtmfg.com/favicon.ico" ]
}
```
## License
MIT license
================================================
FILE: __tests__/__snapshots__/index.spec.ts.snap
================================================
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`#getLinkPreview() no link in text should fail gracefully 1`] = `"link-preview-js did not receive a valid a url or text"`;
exports[`#getLinkPreview() should handle empty strings gracefully 1`] = `"link-preview-js did not receive a valid url or text"`;
exports[`#getLinkPreview() should handle malformed urls gracefully 1`] = `"link-preview-js did not receive a valid a url or text"`;
================================================
FILE: __tests__/index.spec.ts
================================================
import { getLinkPreview, getPreviewFromContent } from "../index";
import prefetchedResponse from "./sampleResponse.json";
describe(`#getLinkPreview()`, () => {
it(`should extract link info from just URL`, async () => {
const linkInfo: any = await getLinkPreview(
`https://www.youtube.com/watch?v=wuClZjOdT30`,
{ headers: { "Accept-Language": `en-US` } }
);
expect(linkInfo.url).toEqual(`https://www.youtube.com/watch?v=wuClZjOdT30`);
expect(linkInfo.siteName).toEqual(`YouTube`);
expect(linkInfo.title).toEqual(`Geography Now! Germany`);
expect(linkInfo.description).toBeTruthy();
expect(linkInfo.mediaType).toEqual(`video.other`);
expect(linkInfo.images.length).toEqual(1);
expect(linkInfo.images[0]).toEqual(
`https://i.ytimg.com/vi/wuClZjOdT30/maxresdefault.jpg`
);
expect(linkInfo.videos.length).toEqual(0);
expect(linkInfo.favicons[0]).not.toBe(``);
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
expect(linkInfo.charset?.toLowerCase()).toEqual(`utf-8`);
});
it("returns charset of website", async () => {
const linkInfo: any = await getLinkPreview(`https://www.pravda.com.ua`);
expect(linkInfo.url).toEqual(`https://www.pravda.com.ua/`);
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
expect(linkInfo.charset?.toLowerCase()).toEqual(`utf-8`);
});
xit("should extract author from news article", async () => {
const linkInfo: any = await getLinkPreview(
`https://www.usatoday.com/story/special/contributor-content/2025/10/15/why-chaos-engineering-is-more-important-than-ever-in-the-ai-era/86712877007/`
);
expect(linkInfo.author).toEqual(`Matt Emma`);
});
it(`should extract link info from a URL with a newline`, async () => {
const linkInfo: any = await getLinkPreview(
`
https://www.youtube.com/watch?v=wuClZjOdT30
`,
{ headers: { "Accept-Language": `en-US` } }
);
expect(linkInfo.url).toEqual(`https://www.youtube.com/watch?v=wuClZjOdT30`);
expect(linkInfo.title).toEqual(`Geography Now! Germany`);
expect(linkInfo.siteName).toBeTruthy();
expect(linkInfo.description).toBeTruthy();
expect(linkInfo.mediaType).toEqual(`video.other`);
expect(linkInfo.images.length).toEqual(1);
expect(linkInfo.images[0]).toEqual(
`https://i.ytimg.com/vi/wuClZjOdT30/maxresdefault.jpg`
);
expect(linkInfo.videos.length).toEqual(0);
expect(linkInfo.favicons[0]).not.toBe(``);
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
});
it(`should extract link info from just text with a URL`, async () => {
const linkInfo: any = await getLinkPreview(
`This is some text blah blah https://www.youtube.com/watch?v=wuClZjOdT30 and more text`,
{ headers: { "Accept-Language": `en-US` } }
);
expect(linkInfo.url).toEqual(`https://www.youtube.com/watch?v=wuClZjOdT30`);
expect(linkInfo.title).toEqual(`Geography Now! Germany`);
expect(linkInfo.siteName).toEqual(`YouTube`);
expect(linkInfo.description).toBeTruthy();
expect(linkInfo.mediaType).toEqual(`video.other`);
expect(linkInfo.images.length).toEqual(1);
expect(linkInfo.images[0]).toEqual(
`https://i.ytimg.com/vi/wuClZjOdT30/maxresdefault.jpg`
);
expect(linkInfo.videos.length).toEqual(0);
expect(linkInfo.favicons[0]).toBeTruthy();
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
});
// it(`should make request with different languages`, async () => {
// let linkInfo: any = await getLinkPreview(`https://www.wikipedia.org/`, {
// headers: { "Accept-Language": `es` },
// followRedirects: `follow`,
// });
// expect(linkInfo.title).toContain(`Wikipedia, la enciclopedia libre`);
// linkInfo = await getLinkPreview(`https://www.wikipedia.org/`);
// expect(linkInfo.title).toContain(`Wikipedia`);
// });
it(`should handle audio urls`, async () => {
const linkInfo = await getLinkPreview(
`https://ondemand.npr.org/anon.npr-mp3/npr/atc/2007/12/20071231_atc_13.mp3`
);
expect(linkInfo.url).toEqual(
`https://ondemand.npr.org/anon.npr-mp3/npr/atc/2007/12/20071231_atc_13.mp3`
);
expect(linkInfo.mediaType).toEqual(`audio`);
expect(linkInfo.contentType?.toLowerCase()).toEqual(`audio/mpeg`);
expect(linkInfo.favicons[0]).toBeTruthy();
});
it(`should handle video urls`, async () => {
const linkInfo = await getLinkPreview(
`https://www.w3schools.com/html/mov_bbb.mp4`
);
expect(linkInfo.url).toEqual(`https://www.w3schools.com/html/mov_bbb.mp4`);
expect(linkInfo.mediaType).toEqual(`video`);
expect(linkInfo.contentType?.toLowerCase()).toEqual(`video/mp4`);
expect(linkInfo.favicons[0]).toBeTruthy();
});
it(`should handle image urls`, async () => {
const linkInfo = await getLinkPreview(
`https://media.npr.org/assets/img/2018/04/27/gettyimages-656523922nunes-4bb9a194ab2986834622983bb2f8fe57728a9e5f-s1100-c15.jpg`
);
expect(linkInfo.url).toEqual(
`https://media.npr.org/assets/img/2018/04/27/gettyimages-656523922nunes-4bb9a194ab2986834622983bb2f8fe57728a9e5f-s1100-c15.jpg`
);
expect(linkInfo.mediaType).toEqual(`image`);
expect(linkInfo.contentType?.toLowerCase()).toEqual(`image/jpeg`);
expect(linkInfo.favicons[0]).toBeTruthy();
});
it(`should handle unknown content type urls`, async () => {
const linkInfo = await getLinkPreview(`https://mjml.io/try-it-live`);
expect(linkInfo.url).toEqual(`https://mjml.io/try-it-live`);
expect(linkInfo.mediaType).toEqual(`website`);
});
// This site changed? it is not returning application any more but rather website
// it.skip(`should handle application urls`, async () => {
// const linkInfo = await getLinkPreview(
// `https://assets.curtmfg.com/masterlibrary/56282/installsheet/CME_56282_INS.pdf`
// );
// expect(linkInfo.url).toEqual(
// `https://assets.curtmfg.com/masterlibrary/56282/installsheet/CME_56282_INS.pdf`
// );
// expect(linkInfo.mediaType).toEqual(`application`);
// expect(linkInfo.contentType?.toLowerCase()).toEqual(`application/pdf`);
// expect(linkInfo.favicons[0]).toBeTruthy();
// });
it(`no link in text should fail gracefully`, async () => {
await expect(
getLinkPreview(`no link`)
).rejects.toThrowErrorMatchingSnapshot();
});
it(`should handle malformed urls gracefully`, async () => {
await expect(
getLinkPreview(
`this is a malformed link: ahttps://www.youtube.com/watch?v=wuClZjOdT30`
)
).rejects.toThrowErrorMatchingSnapshot();
});
it(`should handle empty strings gracefully`, async () => {
await expect(getLinkPreview(``)).rejects.toThrowErrorMatchingSnapshot();
});
it.skip(`should handle a proxy url option`, async () => {
// origin header is required by cors-anywhere
const linkInfo: any = await getLinkPreview(
`https://www.youtube.com/watch?v=wuClZjOdT30`,
{
proxyUrl: `https://cors-anywhere.herokuapp.com/`,
headers: {
Origin: `http://localhost:8000`,
"Accept-Language": `en-US`,
},
}
);
expect(linkInfo.url).toEqual(`https://www.youtube.com/watch?v=wuClZjOdT30`);
expect(linkInfo.siteName).toEqual(`YouTube`);
expect(linkInfo.title).toEqual(`Geography Now! Germany`);
expect(linkInfo.description).toBeTruthy();
expect(linkInfo.mediaType).toEqual(`video.other`);
expect(linkInfo.images.length).toEqual(1);
expect(linkInfo.images[0]).toEqual(
`https://i.ytimg.com/vi/wuClZjOdT30/maxresdefault.jpg`
);
expect(linkInfo.videos.length).toEqual(0);
expect(linkInfo.favicons[0]).not.toBe(``);
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
});
it("should timeout (default 3s) with infinite loading link", async () => {
try {
await getLinkPreview(
`https://www.gamestop.com/video-games/pc-gaming/components/cooling/products/hyper-212-rgb-black-edition-fan/185243.html?gclid=Cj0KCQjwraqHBhDsARIsAKuGZeECDlqkF2cxpcuS0xRxQmrv5BxFawWS_B51kiqehPf64_KlO0oyunsaAhn5EALw_wcB&gclsrc=aw.ds`
);
} catch (e: any) {
expect(e.message).toEqual("Request timeout");
}
});
it("should timeout (custom 1s) with infinite loading link", async () => {
try {
await getLinkPreview(
`https://www.gamestop.com/video-games/pc-gaming/components/cooling/products/hyper-212-rgb-black-edition-fan/185243.html?gclid=Cj0KCQjwraqHBhDsARIsAKuGZeECDlqkF2cxpcuS0xRxQmrv5BxFawWS_B51kiqehPf64_KlO0oyunsaAhn5EALw_wcB&gclsrc=aw.ds`,
{
timeout: 1000,
}
);
} catch (e: any) {
expect(e.message).toEqual("Request timeout");
}
});
it(`should handle followRedirects option is error`, async () => {
try {
await getLinkPreview(`http://google.com/`, { followRedirects: `error` });
} catch (e: any) {
expect(e.message).toEqual(`fetch failed`);
}
});
it(`should handle followRedirects option is manual but handleRedirects was not provided`, async () => {
try {
await getLinkPreview(`http://google.com/`, { followRedirects: `manual` });
} catch (e: any) {
expect(e.message).toEqual(
`link-preview-js followRedirects is set to manual, but no handleRedirects function was provided`
);
}
});
it(`should handle followRedirects option is manual with handleRedirects function`, async () => {
const response = await getLinkPreview(`http://google.com/`, {
followRedirects: `manual`,
handleRedirects: (baseURL: string, forwardedURL: string) => {
if (forwardedURL !== `http://www.google.com/`) {
return false;
}
return true;
},
});
expect(response.contentType).toEqual(`text/html`);
expect(response.url).toEqual(`http://www.google.com/`);
expect(response.mediaType).toEqual(`website`);
});
it("should handle override response body using onResponse option", async () => {
let firstParagraphText;
const res: any = await getLinkPreview(`https://www.example.com/`, {
onResponse: (result, doc) => {
firstParagraphText = doc("p")
.first()
.text()
.split("\n")
.map((x) => x.trim())
.join(" ");
result.siteName = `SiteName has been overridden`;
result.description = firstParagraphText;
return result;
},
});
expect(res.siteName).toEqual("SiteName has been overridden");
expect(res.description).toEqual(firstParagraphText);
});
it("should handle video tags without type or secure_url tags", async () => {
const res: any = await getLinkPreview(
`https://newpathtitle.com/falling-markets-how-to-stop-buyer-from-getting-out/`,
{ followRedirects: `follow` }
);
expect(res.siteName).toEqual(`New Path Title`);
expect(res.title).toEqual(
`Falling Markets: How To Stop A Buyer From Getting Out | New Path Title`
);
expect(res.description).toBeTruthy();
expect(res.mediaType).toEqual(`article`);
expect(res.images.length).toBeGreaterThan(0);
expect(res.videos.length).toBeGreaterThan(0);
expect(res.videos[0].url).toEqual(
`https://www.youtube.com/embed/nqNXjxpAPkU`
);
expect(res.favicons.length).toBeGreaterThan(0);
expect(res.contentType.toLowerCase()).toEqual(`text/html`);
});
});
describe(`#getPreviewFromContent`, () => {
it(`Basic parsing`, async () => {
const linkInfo: any = await getPreviewFromContent(prefetchedResponse);
expect(linkInfo.url).toEqual(`https://www.youtube.com/watch?v=wuClZjOdT30`);
expect(linkInfo.siteName).toEqual(`YouTube`);
expect(linkInfo.title).toEqual(`Geography Now! Germany`);
expect(linkInfo.description).toBeTruthy();
expect(linkInfo.mediaType).toEqual(`video.other`);
expect(linkInfo.images.length).toEqual(1);
expect(linkInfo.images[0]).toEqual(
`https://i.ytimg.com/vi/wuClZjOdT30/maxresdefault.jpg`
);
expect(linkInfo.videos.length).toEqual(0);
expect(linkInfo.favicons[0]).not.toBe(``);
expect(linkInfo.contentType.toLowerCase()).toEqual(`text/html`);
});
});
================================================
FILE: __tests__/sampleResponse.json
================================================
{"url":"https://www.youtube.com/watch?v=wuClZjOdT30","headers":{"alt-svc":"h3-29=\":443\"; ma=2592000,h3-T051=\":443\"; ma=2592000,h3-Q050=\":443\"; ma=2592000,h3-Q046=\":443\"; ma=2592000,h3-Q043=\":443\"; ma=2592000,quic=\":443\"; ma=2592000; v=\"46,43\"","cache-control":"no-cache, no-store, max-age=0, must-revalidate","connection":"close","content-encoding":"gzip","content-type":"text/html; charset=utf-8","date":"Fri, 11 Dec 2020 19:36:56 GMT","expires":"Mon, 01 Jan 1990 00:00:00 GMT","p3p":"CP=\"This is not a P3P policy! See http://support.google.com/accounts/answer/151657?hl=en for more info.\"","pragma":"no-cache","server":"ESF","set-cookie":"YSC=jCz2JZmjRfE; Domain=.youtube.com; Path=/; Secure; HttpOnly; SameSite=none, VISITOR_INFO1_LIVE=oa3D7kCWj44; Domain=.youtube.com; Expires=Wed, 09-Jun-2021 19:36:56 GMT; Path=/; Secure; HttpOnly; SameSite=none","strict-transport-security":"max-age=31536000","transfer-encoding":"chunked","x-content-type-options":"nosniff","x-frame-options":"SAMEORIGIN","x-xss-protection":"0"},"data":"Geography Now! Germany - YouTube