### Request Header Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example HTTP GET request for an oEmbed resource.
```http
GET /oembed?url=...&format=json HTTP/1.1
Host: example.com
```
--------------------------------
### Install and Use oembed-providers NPM Package
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Commands to install the oembed-providers NPM package and a basic example of its usage in code.
```bash
# Install
npm install oembed-providers
# Use in code
const providers = require('oembed-providers');
const endpoints = providers.map(p => p.endpoints).flat();
```
--------------------------------
### oEmbed Consumer Request Examples
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
Demonstrates basic and parameterized GET requests a consumer makes to an oEmbed provider's endpoint. Ensure URLs are URL-encoded.
```http
http://flickr.com/services/oembed?url=http%3A//flickr.com/photos/bees/2362225867/
```
```http
http://flickr.com/services/oembed?url=http%3A//flickr.com/photos/bees/2362225867/&maxwidth=300&maxheight=400&format=json
```
--------------------------------
### Install Dependencies
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Install project dependencies, including build-time tools like js-yaml.
```bash
npm install
```
--------------------------------
### Complete HTML Document Example with oEmbed Links
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/discovery-mechanism.md
This example shows a full HTML document including both JSON and XML oEmbed discovery link elements in the head section.
```html
My Video
My Video
```
--------------------------------
### Link Response Example (XML)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
Example of a link oEmbed response in XML format. Provides generic metadata for resources that do not fit other oEmbed types.
```xml
link1.0Article TitleArticle Authorhttp://example.com/users/author/Example Publishing Servicehttp://example.com/86400
```
--------------------------------
### Video Response Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example JSON structure for a video oEmbed response, including an iframe.
```json
{
"type": "video",
"version": "1.0",
"html": "",
"width": 425,
"height": 344,
"title": "Video Title",
"provider_name": "Example"
}
```
--------------------------------
### Video Response Example (XML)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
Example of a video oEmbed response in XML format. Mirrors the JSON structure with similar metadata and embeddable HTML.
```xml
video1.0Amazing VideoVideo Creatorhttp://example.com/users/videocreator/Example Video Servicehttp://example.com/425344
<iframe width="425" height="344" src="http://example.com/embed/abc123" frameborder="0" allowfullscreen></iframe>
http://example.com/thumbs/abc123.jpg32018086400
```
--------------------------------
### Link Response Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example JSON structure for a link oEmbed response.
```json
{
"type": "link",
"version": "1.0",
"title": "Page Title",
"author_name": "Author Name",
"provider_name": "Example"
}
```
--------------------------------
### Example YAML Input for Build Script
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
A sample YAML structure representing a single provider with its endpoints. This is used as input for the build script.
```yaml
---
- provider_name: Example Provider
provider_url: https://example.com
endpoints:
- schemes:
- https://example.com/video/*
url: https://example.com/oembed
docs_url: https://example.com/docs
example_urls:
- https://example.com/oembed?url=https%3A//example.com/video/123
notes: Supports 'video' type only
...
```
--------------------------------
### oEmbed Photo Type Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
Example JSON response for a photo resource. Includes common parameters and type-specific fields like URL, width, and height.
```json
{
"type": "photo",
"version": "1.0",
"url": "http://example.com/image.jpg",
"width": 240,
"height": 160,
"title": "Example Photo",
"provider_name": "Example Provider",
"provider_url": "http://example.com/"
}
```
--------------------------------
### HTTP Link Header for oEmbed Discovery
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example HTTP Link header for oEmbed discovery.
```http
Link: ; rel="alternate"; type="application/json+oembed"; title="..."
```
--------------------------------
### Install oEmbed Providers Package
Source: https://github.com/iamcal/oembed/blob/master/README.md
Install the oembed-providers package using NPM to access the providers.json file in your node_modules directory. This is useful for directly ingesting the provider registry.
```bash
npm install https://github.com/iamcal/oembed
```
--------------------------------
### Multi-Rule oembed-config.xml for Qik
Source: https://github.com/iamcal/oembed/blob/master/www/draft_old.htm
An example oembed-config.xml file for Qik demonstrating multiple match rules for different endpoint types (XML and JSON) and a custom TTL.
```xml
```
--------------------------------
### oEmbed Provider YAML Configuration Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/provider-implementation.md
Defines the structure for a YAML configuration file to register a new oEmbed provider. This includes provider details, endpoint information, supported schemes, and formats.
```yaml
---
- provider_name: Example Provider
provider_url: https://example.com
endpoints:
- schemes:
- https://example.com/video/*
- https://example.com/photo/*
url: https://example.com/oembed
docs_url: https://example.com/api/docs
example_urls:
- https://example.com/oembed?url=https%3A//example.com/video/123&format=json
discovery: true
formats:
- json
- xml
notes: Provider supports video and photo types
...
```
--------------------------------
### Build Script Invocation
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/repository-structure.md
Commands to build the provider registry JSON file from YAML sources. Ensure you have Node.js and npm installed.
```bash
npm run build
```
```bash
node build.js providers/*.yml > providers.json
```
--------------------------------
### Example Provider Entry in YAML
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/providers-registry.md
This is the source format for defining an oEmbed provider, including its name, URL, and endpoint configurations with schemes, URL, discovery, and formats.
```yaml
---
- provider_name: YouTube
provider_url: https://www.youtube.com
endpoints:
- schemes:
- https://www.youtube.com/watch?v=*
- https://www.youtube.com/playlist?list=*
- https://youtu.be/*
url: https://www.youtube.com/oembed
docs_url: https://developers.google.com/youtube/iframe_api_reference
example_urls:
- https://www.youtube.com/oembed?url=https%3A//www.youtube.com/watch%3Fv%3DM3r2XDceM6A&format=json
discovery: true
formats:
- json
notes: Provider supports 'video' and 'rich' types
...
```
--------------------------------
### oEmbed Video Type Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
Example JSON response for a video resource. Includes common parameters and type-specific fields like HTML embed code, width, and height.
```json
{
"type": "video",
"version": "1.0",
"html": "",
"width": 425,
"height": 344,
"title": "Video Title",
"author_name": "Author Name",
"author_url": "http://example.com/user/",
"provider_name": "Example Provider",
"provider_url": "http://example.com/"
}
```
--------------------------------
### oEmbed Link Type Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
Example JSON response for a link resource. Primarily uses common parameters to provide metadata for a linked resource.
```json
{
"type": "link",
"version": "1.0",
"title": "Example Article",
"author_name": "Example Author",
"author_url": "http://example.com/author/",
"provider_name": "Example Provider",
"provider_url": "http://example.com/"
}
```
--------------------------------
### oEmbed Rich Type Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
Example JSON response for a rich content resource. Includes common parameters and type-specific fields for embedding arbitrary HTML.
```json
{
"type": "rich",
"version": "1.0",
"html": "
...
",
"width": 600,
"height": 400,
"title": "Rich Content",
"provider_name": "Example Provider",
"provider_url": "http://example.com/"
}
```
--------------------------------
### Photo Type Example Response (XML)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
Example XML response for an oEmbed photo type. Mirrors the JSON structure with common and type-specific photo fields.
```xml
photo1.0http://example.com/photos/cool-image.jpg500400Cool Image TitleImage Creatorhttp://example.com/users/imagecreator/Example Photo Servicehttp://example.com/604800
```
--------------------------------
### Import oEmbed Providers Registry in Node.js
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/providers-registry.md
Shows two common ways to import the oEmbed providers registry in a Node.js environment after installation.
```javascript
const providers = require('oembed-providers');
```
```javascript
// or
const providers = require('oembed-providers/providers.json');
```
--------------------------------
### Example JSON Output from Build Script
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
The resulting JSON structure after the build script processes the YAML input. Development-specific fields like 'docs_url', 'example_urls', and 'notes' are removed.
```json
[
{
"provider_name": "Example Provider",
"provider_url": "https://example.com",
"endpoints": [
{
"schemes": [
"https://example.com/video/*"
],
"url": "https://example.com/oembed"
}
]
}
]
```
--------------------------------
### Implement Content Security Policy (CSP) Headers
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/security-considerations.md
Shows an example of strict Content Security Policy headers to prevent inline scripts and control resource loading, enhancing security against various web attacks.
```http
Content-Security-Policy:
default-src 'self';
script-src 'self' https://trusted-domains.com;
img-src 'self' data: https:;
frame-src https:;
object-src 'none';
base-uri 'self'
```
--------------------------------
### Implement oEmbed Endpoint (Express.js)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Create an HTTP GET endpoint for your oEmbed provider using a framework like Express.js. Handle requests, validate parameters, fetch resources, and build the response.
```javascript
app.get('/api/oembed', (req, res) => {
const { url, maxwidth, maxheight, format = 'json' } = req.query;
// Validate
if (!url) return res.status(400).json({ error: 'Missing url' });
if (!isSupported(url)) return res.status(404).json({ error: 'Not found' });
// Fetch resource
const resource = getResource(url);
// Build response
const response = {
type: 'video',
version: '1.0',
title: resource.title,
html: buildEmbed(resource, maxwidth, maxheight),
width: maxwidth || 1280,
height: maxheight || 720,
provider_name: 'My Service',
provider_url: 'https://example.com'
};
if (format === 'xml') {
res.type('text/xml').send(toXml(response));
} else {
res.type('application/json').json(response);
}
});
```
--------------------------------
### Single Rule oembed-config.xml for Flickr
Source: https://github.com/iamcal/oembed/blob/master/www/draft_old.htm
An example oembed-config.xml file with a single match rule for Flickr, specifying a pattern and the endpoint URL for oEmbed requests.
```xml
```
--------------------------------
### HTML Link Element for oEmbed Discovery
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example HTML link element used for oEmbed discovery in the page head.
```html
```
--------------------------------
### Constructing and Fetching an oEmbed Request
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/consumer-implementation.md
Builds a URL-encoded HTTP GET request to an oEmbed endpoint, including optional parameters like maxwidth, maxheight, and format. Handles basic HTTP errors by throwing an error. Assumes a fetch API is available.
```javascript
async function fetchOEmbed(url, endpoint, options = {}) {
// Parameters
const params = new URLSearchParams({
url: url,
format: options.format || 'json'
});
if (options.maxwidth) params.append('maxwidth', options.maxwidth);
if (options.maxheight) params.append('maxheight', options.maxheight);
const requestUrl = `${endpoint}?${params.toString()}`;
const response = await fetch(requestUrl);
if (!response.ok) {
throw new Error(`oEmbed request failed: ${response.status}`);
}
return response.json();
}
```
```javascript
const oembed = await fetchOEmbed(
'https://example.com/video/123',
'https://example.com/oembed',
{ maxwidth: 600, maxheight: 400, format: 'json' }
);
```
--------------------------------
### Complete oEmbed Response with All Common Fields (JSON)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
An example of a complete oEmbed response in JSON format for a 'video' type, including optional fields like title, author, provider details, and thumbnail information.
```json
{
"type": "video",
"version": "1.0",
"title": "Video Title",
"author_name": "Author Name",
"author_url": "http://example.com/author/",
"provider_name": "Provider",
"provider_url": "http://example.com/",
"cache_age": 86400,
"thumbnail_url": "http://example.com/thumb.jpg",
"thumbnail_width": 320,
"thumbnail_height": 180,
"html": "",
"width": 640,
"height": 480
}
```
--------------------------------
### oEmbed XML Response Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
A standard XML response from an oEmbed provider, mirroring the JSON structure with a root element. The Content-Type header should be text/xml.
```xml
1.0photo240160Example Photohttp://example.com/image.jpgExample Userhttp://example.com/user/Example Providerhttp://example.com/
```
--------------------------------
### oEmbed JSON Response Example
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/oembed-spec.md
A standard JSON response from an oEmbed provider, containing metadata and embedding information for a photo resource. The Content-Type header should be application/json.
```json
{
"version": "1.0",
"type": "photo",
"width": 240,
"height": 160,
"title": "Example Photo",
"url": "http://example.com/image.jpg",
"author_name": "Example User",
"author_url": "http://example.com/user/",
"provider_name": "Example Provider",
"provider_url": "http://example.com/"
}
```
--------------------------------
### Local Testing Commands
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/repository-structure.md
Commands to set up dependencies, build the provider registry, and validate the JSON output locally. These are useful for development and testing the repository's core functionality.
```bash
# Install dependencies
npm install
# Build provider registry
npm run build
# Validate JSON output
node -e "console.log(JSON.stringify(require('./providers.json'), null, 2))"
# Check provider count
node -e "console.log('Providers:', require('./providers.json').length)"
```
--------------------------------
### Load oEmbed Providers Registry from File
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/providers-registry.md
Demonstrates how to load and parse the oEmbed providers registry directly from its JSON file using Node.js's file system module.
```javascript
const fs = require('fs');
const providers = JSON.parse(fs.readFileSync('node_modules/oembed-providers/providers.json', 'utf8'));
```
--------------------------------
### Add and Commit Changes
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Stage the updated providers.json and package.json, then commit them with a descriptive message.
```bash
git add providers.json package.json
git commit -m "Update providers registry for [date]"
```
--------------------------------
### HTML with Responsive Sizing for oEmbed Rich Content
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
Demonstrates how to embed rich oEmbed content using an iframe with responsive sizing. Includes a script for injecting HTML content.
```html
```
--------------------------------
### XML Response Content-Type Header
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example Content-Type header for an XML oEmbed response.
```http
Content-Type: text/xml; charset=utf-8
```
--------------------------------
### Manual Node.js Build with Specific Files
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Execute the build script with Node.js, providing specific YAML files as arguments. This allows for targeted compilation.
```bash
node build.js providers/YouTube.yml providers/Vimeo.yml > providers.json
```
--------------------------------
### JSON Response Content-Type Header
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Example Content-Type header for a JSON oEmbed response.
```http
Content-Type: application/json; charset=utf-8
```
--------------------------------
### oEmbed Registered Providers JSON Endpoint
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/INDEX.md
This HTTP GET request retrieves a JSON array of all registered oEmbed providers.
```HTTP
GET https://oembed.com/providers.json
→ Array of all registered providers
```
--------------------------------
### Consumer to Provider oEmbed Request
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/INDEX.md
Consumers can request embedding metadata from providers by sending a GET request with URL and optional parameters.
```APIDOC
## GET /oembed
### Description
Requests embedding metadata for a given URL from an oEmbed provider.
### Method
GET
### Endpoint
/oembed
### Parameters
#### Query Parameters
- **url** (string) - Required - The URL to embed.
- **maxwidth** (integer) - Optional - The maximum width of the embed.
- **maxheight** (integer) - Optional - The maximum height of the embed.
- **format** (string) - Optional - The desired response format (e.g., 'json', 'xml'). Defaults to JSON.
### Response
#### Success Response (200)
- **type** (string) - The type of embed (photo, video, link, rich).
- **version** (string) - The oEmbed version.
- **url** (string) - The URL of the photo or video, or HTML for rich embeds.
- **html** (string) - HTML code to embed the content.
- **width** (number) - The width of the embed.
- **height** (number) - The height of the embed.
```
--------------------------------
### NPM Login for Publishing
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Authenticate with the NPM registry before publishing a new version.
```bash
npm login
```
--------------------------------
### Run Build Script via NPM
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Execute the build script using an NPM script defined in package.json. This command compiles all provider YAML files into providers.json.
```bash
npm run build
```
--------------------------------
### oEmbed Consumer to Provider HTTP Endpoint
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/INDEX.md
This is the standard HTTP GET request format for an oEmbed consumer to request embedding metadata from a provider.
```HTTP
GET /oembed?url=&maxwidth=&maxheight=&format=
→ JSON or XML response with embedding metadata
```
--------------------------------
### Get Cache Duration
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/consumer-implementation.md
Determines the cache duration for an oEmbed response. It uses the provider-suggested cache age if available, otherwise defaults to 7 days.
```javascript
function getCacheDuration(oembedResponse) {
// Use provider-suggested cache age if available
if (oembedResponse.cache_age) {
return oembedResponse.cache_age * 1000; // Convert to milliseconds
}
// Default: 7 days
return 7 * 24 * 60 * 60 * 1000;
}
```
--------------------------------
### Define oEmbed Provider URL Schemes (YAML)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Configure the URL schemes that your oEmbed provider will handle. This is typically done in a configuration file.
```yaml
---
- provider_name: My Service
provider_url: https://example.com
endpoints:
- schemes:
- https://example.com/video/*
- https://example.com/photo/*
url: https://example.com/api/oembed
discovery: true
formats: [json, xml]
...
```
--------------------------------
### Build Video oEmbed Response
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/provider-implementation.md
Constructs a video oEmbed response object. It calculates appropriate dimensions based on provided maxwidth and maxheight constraints while maintaining the aspect ratio. Assumes helper functions like `buildEmbedHtml` are available.
```javascript
function buildVideoResponse(resource, options = {}) {
const { maxwidth, maxheight } = options;
// Calculate dimensions
let width = 1280;
let height = 720;
if (maxwidth && maxwidth < width) {
height = Math.round(height * (maxwidth / width));
width = maxwidth;
}
if (maxheight && maxheight < height) {
width = Math.round(width * (maxheight / height));
height = maxheight;
}
return {
type: 'video',
version: '1.0',
title: resource.title,
author_name: resource.authorName,
author_url: resource.authorUrl,
provider_name: 'Example Provider',
provider_url: 'https://example.com',
width,
height,
html: buildEmbedHtml(resource.id, width, height),
cache_age: 86400, // 1 day
thumbnail_url: resource.thumbnailUrl,
thumbnail_width: 320,
thumbnail_height: 180
};
}
function buildEmbedHtml(videoId, width, height) {
return ``;
}
```
--------------------------------
### Minimal oEmbed Endpoint (Node.js Express)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/provider-implementation.md
Sets up a basic oEmbed endpoint using Node.js and Express. It handles URL validation, format checking, and delegates response building to other functions. Requires Express and a way to fetch metadata.
```javascript
const express = require('express');
const app = express();
// Define supported URL schemes
const URL_SCHEMES = [
/^https:\/\/example\.com\/video\/\d+\/?$/,
/^https:\/\/example\.com\/v\/\w+\/?$/
];
// Validate that URL matches supported schemes
function isUrlSupported(url) {
return URL_SCHEMES.some(scheme => scheme.test(url));
}
// Main oEmbed endpoint
app.get('/oembed', async (req, res) => {
const { url, maxwidth, maxheight, format = 'json' } = req.query;
// Validate parameters
if (!url) {
return res.status(400).json({ error: 'Missing url parameter' });
}
// Check URL support
if (!isUrlSupported(url)) {
return res.status(404).json({ error: 'URL not supported' });
}
// Check format support
if (!['json', 'xml'].includes(format)) {
return res.status(501).json({ error: 'Unsupported format' });
}
try {
// Fetch resource metadata
const metadata = await fetchMetadata(url);
if (!metadata) {
return res.status(404).json({ error: 'Resource not found' });
}
// Build oEmbed response
const oembed = buildResponse({
type: 'video',
url,
metadata,
maxwidth,
maxheight,
format
});
// Return response in requested format
if (format === 'xml') {
res.type('text/xml');
res.send(toXml(oembed));
} else {
res.type('application/json');
res.json(oembed);
}
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
app.listen(3000);
```
--------------------------------
### Metadata Caching Implementation
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/provider-implementation.md
Implements a simple in-memory cache for metadata using a Map, including functions to get, set, and fetch metadata with cache support.
```javascript
const metadataCache = new Map();
function getCachedMetadata(url) {
if (metadataCache.has(url)) {
const { data, expiry } = metadataCache.get(url);
if (expiry > Date.now()) {
return data;
}
}
return null;
}
function setCachedMetadata(url, data, ttl = 3600000) { // 1 hour default
metadataCache.set(url, {
data,
expiry: Date.now() + ttl
});
}
async function fetchMetadataWithCache(url) {
const cached = getCachedMetadata(url);
if (cached) return cached;
const data = await fetchMetadata(url);
if (data) {
setCachedMetadata(url, data);
}
return data;
}
```
--------------------------------
### oEmbed Request Format
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/README.md
This is the standard GET request format for oEmbed. It includes the URL of the content to embed and optional parameters for maximum width, height, and response format.
```http
GET /oembed?url={URL}&maxwidth={N}&maxheight={N}&format={json|xml}
```
--------------------------------
### Recommended Sandbox Configuration for Iframes
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/security-considerations.md
Provides a recommended iframe sandbox configuration that balances security and functionality, allowing scripts, same-origin requests, and presentation API usage while disabling potentially risky features.
```html
```
--------------------------------
### Async Loading of oEmbed Content
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/consumer-implementation.md
Implements deferred loading for oEmbed content using progressive enhancement. It fetches and renders oEmbed content for elements with a 'data-oembed-url' attribute, falling back to a simple link on error.
```javascript
// Deferred loading with progressive enhancement
document.querySelectorAll('[data-oembed-url]').forEach(element => {
const url = element.getAttribute('data-oembed-url');
(async () => {
try {
const provider = findProviderForUrl(url);
if (!provider) throw new Error('No provider found');
const oembed = await fetchOEmbedSafe(url, provider.endpoint.url);
if (!oembed) throw new Error('oEmbed request failed');
element.innerHTML = renderOEmbedResponse(oembed, url);
} catch (error) {
element.innerHTML = `${escapeHtml(url)}`;
}
})();
});
```
--------------------------------
### URL Scheme Patterns
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Valid and invalid URL patterns for provider configuration, demonstrating wildcard usage.
```text
http://example.com/photos/* ✓ Path wildcard
http://example.com/photos/*/detail ✓ Path wildcard with suffix
http://*.example.com/photos/* ✓ Subdomain wildcard
http://*.example.com/* ✓ Broad pattern
http://*.com/photos/* ✗ Too broad
*://example.com/photos/* ✗ Scheme wildcard invalid
```
--------------------------------
### Add oEmbed Discovery Link (HTTP Header)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Alternatively, provide the oEmbed discovery link via an HTTP 'Link' header in your responses.
```javascript
res.set('Link',
'; rel="alternate"; type="application/json+oembed"'
);
```
--------------------------------
### Import oembed-providers Registry
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/repository-structure.md
Import the providers registry in your Node.js project.
```javascript
const providers = require('oembed-providers')
```
--------------------------------
### Import oembed-providers in Node.js (ES Modules)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Import the providers registry using the JSON module type in ES Modules.
```javascript
import providers from 'oembed-providers' with { type: 'json' };
```
--------------------------------
### Logging oEmbed Requests
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/security-considerations.md
Implement logging for oEmbed requests to monitor for suspicious activity. Log key details such as timestamp, method, URL, format, IP address, status, and duration.
```javascript
function logOEmbedRequest(req, response) {
console.log({
timestamp: new Date().toISOString(),
method: req.method,
url: req.query.url,
format: req.query.format,
ip: req.ip,
status: response.status,
duration: response.duration
});
}
```
--------------------------------
### Managing Dependencies
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/security-considerations.md
Regularly audit and update dependencies to address known vulnerabilities. Use npm commands to check for and fix security issues.
```bash
npm audit
npm audit fix
npm update
```
--------------------------------
### Add oEmbed Link Headers in PHP
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/discovery-mechanism.md
This PHP code snippet shows how to send `Link` HTTP headers to advertise oEmbed endpoints for JSON and XML formats.
```php
; rel="alternate"; type="application/json+oembed"');
header('Link: ; rel="alternate"; type="text/xml+oembed"');
// Render page
echo renderVideoPage($_GET['id']);
?>
```
--------------------------------
### Publish New Version to NPM
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Upload the new version of the package to the NPM registry.
```bash
npm publish
```
--------------------------------
### Configure Apache .htaccess for oEmbed Links
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/discovery-mechanism.md
This Apache `.htaccess` configuration adds `Link` headers for HTML files to advertise oEmbed endpoints.
```apache
Header add Link '; rel="alternate"; type="application/json+oembed"'
```
--------------------------------
### Build Photo oEmbed Response
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/provider-implementation.md
Generates a photo oEmbed response, adjusting the image dimensions to fit within specified maximum width and height while preserving the aspect ratio. Includes standard photo response fields.
```javascript
function buildPhotoResponse(resource, options = {}) {
const { maxwidth, maxheight } = options;
let width = resource.width;
let height = resource.height;
// Respect constraints while maintaining aspect ratio
if (maxwidth && width > maxwidth) {
height = Math.round(height * (maxwidth / width));
width = maxwidth;
}
if (maxheight && height > maxheight) {
width = Math.round(width * (maxheight / height));
height = maxheight;
}
return {
type: 'photo',
version: '1.0',
url: resource.imageUrl,
width,
height,
title: resource.title,
author_name: resource.authorName,
author_url: resource.authorUrl,
provider_name: 'Example Provider',
provider_url: 'https://example.com',
cache_age: 604800 // 7 days
};
}
```
--------------------------------
### Link Consumer Rendering (Markdown)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/response-types-reference.md
Markdown format for rendering a link oEmbed response. Presents the link with title and author information.
```markdown
[Article Title](http://example.com/article/123) by Article Author
```
--------------------------------
### NPM package.json Build Script
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Defines the 'build' script in package.json to run the Node.js build process. It executes the build script and redirects output to providers.json.
```json
{
"scripts": {
"build": "node ./build.js providers/*.yml > providers.json"
}
}
```
--------------------------------
### Read providers.json from File System
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
Load the providers.json file directly from the file system using Node.js.
```javascript
const fs = require('fs');
const path = require('path');
const providersPath = require.resolve('oembed-providers');
const providers = JSON.parse(fs.readFileSync(providersPath, 'utf8'));
```
--------------------------------
### Handle oEmbed Response by Type
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Process the received oEmbed data based on its 'type' field to render the content appropriately (photo, video, rich, or link).
```javascript
switch (oembed.type) {
case 'photo':
// Display image
html = ``;
break;
case 'video':
case 'rich':
// Display in sandboxed iframe
html = ``;
// Then: iframe.contentDocument.write(oembed.html);
break;
case 'link':
// Display as link
html = `${oembed.title}`;
break;
}
```
--------------------------------
### Render Link oEmbed Response
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/consumer-implementation.md
Formats link oEmbed responses, displaying title, author, and provider information.
```javascript
function renderLinkResponse(data, originalUrl) {
const title = data.title || originalUrl;
return "
" + (data.title ? `${escapeHtml(data.title)} ` : '') + "
" + (data.author_name ? `by ${escapeHtml(data.author_name)} ` : '') + "
${escapeHtml(data.provider_name || 'Link')}
";
}
```
--------------------------------
### NPM package.json Configuration
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/build-system.md
The package.json file configures the NPM package, including its name, versioning scheme, entry point, and distribution files. It also defines build and prepare scripts.
```json
{
"name": "oembed-providers",
"version": "1.0.YYYYMMDD",
"license": "MIT",
"description": "oEmbed providers",
"main": "providers.json",
"files": [
"providers.*"
],
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "node ./build.js providers/*.yml > providers.json",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://github.com/iamcal/oembed.git"
},
"keywords": [
"oembed",
"json",
"providers",
"list"
],
"author": "Cal Henderson ",
"bugs": {
"url": "https://github.com/iamcal/oembed/issues"
},
"devDependencies": {
"js-yaml": "^4.0.0"
}
}
```
--------------------------------
### Find Provider Endpoint via Registry (NPM)
Source: https://github.com/iamcal/oembed/blob/master/_autodocs/quick-reference.md
Search a registry of oEmbed providers to find the correct endpoint URL for a given resource URL. This requires the 'oembed-providers' package.
```javascript
const providers = require('oembed-providers');
function findEndpoint(url) {
for (const provider of providers) {
for (const endpoint of provider.endpoints) {
for (const scheme of endpoint.schemes) {
if (url.match(wildcardToRegex(scheme))) {
return endpoint.url;
}
}
}
}
}
```