This documentation provides a thorough overview of the WebSim API and client-side TypeScript implementation. It is based on the following resources:
The WebSim API provides a comprehensive set of endpoints for interacting with various aspects of the WebSim platform. It is designed to support the creation, management, and discovery of web-based content and projects.
All API requests should be prefixed with the following base URL:
/api/v1/
Most endpoints require authentication. While the specific authentication method is not detailed in the provided schema, it's likely to use one of the following:
API responses are returned in JSON format. Successful responses typically include the requested data, while error responses include an error object with a message and potentially additional details.
While not explicitly mentioned in the schema, it's common for APIs to implement rate limiting. Be prepared to handle 429 (Too Many Requests) responses and implement appropriate backoff strategies.
| Endpoint | Description | Parameters |
|---|---|---|
GET /feed/trending |
Retrieve trending content | range, feed, class, unseen_by |
GET /users/{usernameOrId}/feed |
Get user-specific feed | range, feed, class, unseen_by |
GET /feed/search/{searchQuery} |
Search for content | range, feed, class, unseen_by |
| Endpoint | Description | Parameters |
|---|---|---|
GET /users/{usernameOrId}/following |
Get users followed by the specified user | first, last, before, after, count |
GET /users/{usernameOrId}/followers |
Get followers of the specified user | first, last, before, after, count |
GET /users/{usernameOrId} |
Get user details | N/A |
| Endpoint | Description | Parameters |
|---|---|---|
GET /projects/{project_id} |
Get details of a specific project | N/A |
GET /users/{usernameOrId}/projects |
Get projects of a specific user | first, last, before, after, has_site, posted, sort_by, query, liked_by_owner |
GET /projects |
Get all projects | first, last, before, after, has_site, posted, sort_by, query, liked_by_owner |
GET /projects/{project_id}/descendants |
Get descendants of a project | first, last, before, after, has_site, posted, sort_by, query, liked_by_owner |
| Endpoint | Description | Parameters |
|---|---|---|
GET /sites/{site_id} |
Get details of a specific site | N/A |
GET /users/{usernameOrId}/sites |
Get sites of a specific user | first, last, before, after, state |
| Endpoint | Description | Parameters |
|---|---|---|
GET /users/{usernameOrId}/likes |
Get likes of a specific user | first, last, before, after |
Many endpoints in the WebSim API support cursor-based pagination. Use the following query parameters for pagination:
first: Number of items to return from the beginning of the list.last: Number of items to return from the end of the list.before: Cursor indicating the start of the desired page (moving backwards).after: Cursor indicating the end of the desired page (moving forwards).Paginated responses include a meta object with the following properties:
{
"has_next_page": boolean,
"has_previous_page": boolean,
"start_cursor": string,
"end_cursor": string
}
The client-side TypeScript implementation provides a set of utilities and interfaces for interacting with the WebSim platform. This section details the key components and their functionality.
The window.websim object provides methods for interacting with the WebSim platform:
interface WebSimAPI {
getUser(): Promise;
getColorScheme(): Promise<"light" | "dark">;
experimental: {
v0: {
siteId: string;
save(htmlContent: string): Promise<{ id: string }>;
getHTML(siteId?: string): Promise;
generate(prompt: string, options?: GenerateOptions): Promise<{ id: string }>;
}
};
internal_only_experimental: {
getIsLiked(args: { siteId: string }): Promise;
setIsLiked(args: { siteId: string; isLiked: boolean }): Promise;
sendViewStartEvent(args: { siteId: string }): Promise;
sendViewEndEvent(args: { viewUuid: string }): Promise;
}
}
Retrieves the current user's information.
Retrieves the current color scheme preference (light or dark).
Provides experimental methods for site manipulation:
save(htmlContent: string): Saves HTML content for a site.getHTML(siteId?: string): Retrieves HTML content for a site.generate(prompt: string, options?: GenerateOptions): Generates a new site based on a prompt.Provides internal experimental methods:
getIsLiked(args: { siteId: string }): Checks if a site is liked by the current user.setIsLiked(args: { siteId: string; isLiked: boolean }): Sets the like status for a site.sendViewStartEvent(args: { siteId: string }): Logs the start of a site view.sendViewEndEvent(args: { viewUuid: string }): Logs the end of a site view.Sites represent individual web pages or applications created within the WebSim platform. They have the following key properties:
id: A unique identifier for the site.parent_id: The ID of the parent site, if applicable.created_at: The creation timestamp.state: The current state of the site (e.g., "initial", "generating", "done", "failed").owner: The user who created the site.title: The title of the site.url: The URL of the site.prompt: The prompt used to generate the site, if applicable.Projects are collections of related sites or revisions. They have the following key properties:
id: A unique identifier for the project.created_by: The user who created the project.created_at: The creation timestamp.updated_at: The last update timestamp.title: The title of the project.visibility: The visibility setting of the project (e.g., "public", "private", "unlisted").current_version: The current version number of the project.stats: Statistics about the project, including views and likes.Feeds provide streams of content, which can be trending items, user-specific content, or search results. The feed data typically includes:
The WebsimSocket class provides real-time communication capabilities, enabling collaborative features and live updates. It extends the standard WebSocket interface with additional WebSim-specific functionality.
store propertyconst room = new WebsimSocket();
room.onmessage = (event) => {
const data = event.data;
// Handle incoming messages
};
room.onPeersChanged = (peers) => {
// Update UI with connected peers
};
room.onRecordChanged = (id) => {
// Handle changes to shared store records
};
// Send a message
room.send({
type: "chatMessage",
message: "Hello, world!",
});
// Update shared store
room.store.update({
id: "gameState",
dependencies: { score: 100 },
updateFunction: (currentState) => ({
...currentState,
score: score
})
});
WebsimSocket broadcasts 2 built-in events to all clients:
{ type: "connected", clientId: string, avatarUrl: string, username: string }{ type: "disconnected", clientId: string, avatarUrl: string, username: string }The WebsimSocket provides a shared store for managing state across all connected clients:
// Get a value from the store
const value = await room.store.get('key');
// Update a value in the store
room.store.update({
id: 'key',
dependencies: { newValue: 42 },
updateFunction: (currentValue) => newValue
});
// Reset the entire store
room.store.reset();
// Get all values from the store
const allValues = await room.store.getAll();
WebSim provides simulated APIs that can be used within the WebSim environment. These APIs allow you to interact with the platform and create dynamic content.
The SQL API allows you to create and interact with a simulated database within your WebSim project.
async function createMessageTable() {
let query = `CREATE TABLE if not exists message (id INTEGER PRIMARY KEY, msg TEXT)`;
let results = await fetch('/api/v1/sql/?' + new URLSearchParams({sql: query}));
let data = await results.json();
console.log(data);
}
async function insertMessage(msg) {
let query = `INSERT INTO message (msg) VALUES ('${msg}')`;
let results = await fetch('/api/v1/sql/?' + new URLSearchParams({sql: query}));
let data = await results.json();
console.log(data);
}
async function fetchMessages() {
let query = `SELECT * FROM message ORDER BY id ASC`;
let results = await fetch('/api/v1/sql/?' + new URLSearchParams({sql: query}));
let data = await results.json();
return data;
}
The WebSim global object provides access to various platform features and user information. Here are some key functions:
// Get the current user
const user = await window.websim.getUser();
// Navigate to a different page
window.websim.navigate('/some-page');
// Show a toast notification
window.websim.toast('Hello, World!');
// Get the current project ID
const projectId = window.websim.getProjectId();
// Check if the current user is the owner of the current project
const isOwner = window.websim.isOwner();
// Get the current project's visibility
const visibility = window.websim.getVisibility();
// Get the current user's role (if applicable)
const role = window.websim.getRole();
// Check if the current user has a specific permission
const hasPermission = window.websim.hasPermission('edit_project');
// Get the current project's slug
const slug = window.websim.getSlug();
// Get the current project's version
const version = window.websim.getVersion();
The client-side implementation includes error catching for unhandled rejections and general errors. This helps in identifying and debugging issues in the application.
window.addEventListener('unhandledrejection', (event) => {
const error = {
type: 'unhandledRejection',
message: event.reason?.message || 'Unknown promise rejection',
stack: event.reason?.stack,
};
parentApi.reportError(error);
});
window.addEventListener('error', (event) => {
const error = {
type: 'error',
message: event.message,
stack: event.error?.stack,
};
parentApi.reportError(error);
});
These error handlers report errors to the parent application, allowing for centralized error tracking and analysis.
The implementation patches the global fetch function to handle WebSim-specific API calls and add custom headers. This patching allows for:
window.fetch = async function (a, options = {}) {
const url = new URL(
(a as Request)?.url ? String((a as Request).url) : String(a),
window.location.origin
);
// Custom logic for WebSim API calls
if (isWebSimApiCall(url)) {
// Add custom headers
options.headers = {
...options.headers,
'Websim-Update': `${websimUpdateVersion}`,
};
// Handle request body
if (options.body) {
// Process body based on content type
}
// Make the API call using parentApi
const response = await parentApi.fetchApi({
url: url.toString(),
options,
originalOptions,
});
return new Response(response.body, response);
}
// For non-WebSim API calls, use the original fetch
return originalFetch(url, options);
};
window.websim object for WebSim-specific functionality over direct API calls when possible.