@onlyworlds/sdk
Version:
TypeScript SDK for the OnlyWorlds API - build world-building applications with type safety
179 lines (175 loc) • 6.17 kB
JavaScript
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
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 });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
ElementType: () => ElementType,
OnlyWorldsClient: () => OnlyWorldsClient
});
module.exports = __toCommonJS(index_exports);
// src/client.ts
var Resource = class {
constructor(client, elementType) {
this.client = client;
this.elementType = elementType;
}
async list(options) {
return this.client.request("GET", `/${this.elementType}/`, { params: options });
}
async get(id) {
return this.client.request("GET", `/${this.elementType}/${id}/`);
}
async create(data) {
return this.client.request("POST", `/${this.elementType}/`, { body: data });
}
async update(id, data) {
return this.client.request("PATCH", `/${this.elementType}/${id}/`, { body: data });
}
async delete(id) {
return this.client.request("DELETE", `/${this.elementType}/${id}/`);
}
};
var OnlyWorldsClient = class {
constructor(config) {
this.baseUrl = config.baseUrl || "https://www.onlyworlds.com/api/worldapi";
this.headers = {
"Content-Type": "application/json",
"API-Key": config.apiKey,
"API-Pin": config.apiPin
};
this.worlds = new Resource(this, "world");
this.abilities = new Resource(this, "ability");
this.characters = new Resource(this, "character");
this.collectives = new Resource(this, "collective");
this.constructs = new Resource(this, "construct");
this.creatures = new Resource(this, "creature");
this.events = new Resource(this, "event");
this.families = new Resource(this, "family");
this.institutions = new Resource(this, "institution");
this.languages = new Resource(this, "language");
this.laws = new Resource(this, "law");
this.locations = new Resource(this, "location");
this.maps = new Resource(this, "map");
this.markers = new Resource(this, "marker");
this.narratives = new Resource(this, "narrative");
this.objects = new Resource(this, "object");
this.phenomena = new Resource(this, "phenomenon");
this.pins = new Resource(this, "pin");
this.relations = new Resource(this, "relation");
this.species = new Resource(this, "species");
this.titles = new Resource(this, "title");
this.traits = new Resource(this, "trait");
this.zones = new Resource(this, "zone");
}
/**
* Make a request to the OnlyWorlds API
*/
async request(method, path, options) {
const url = new URL(`${this.baseUrl}${path}`);
if (options?.params) {
Object.entries(options.params).forEach(([key, value]) => {
if (value !== void 0 && value !== null) {
url.searchParams.append(key, String(value));
}
});
}
const fetchOptions = {
method,
headers: this.headers
};
if (options?.body && ["POST", "PATCH", "PUT"].includes(method)) {
fetchOptions.body = JSON.stringify(options.body);
}
const response = await fetch(url.toString(), fetchOptions);
if (!response.ok) {
let errorMessage = `API Error ${response.status}`;
try {
const errorText = await response.text();
if (errorText) {
try {
const errorJson = JSON.parse(errorText);
errorMessage += `: ${errorJson.detail || errorJson.error || errorText}`;
} catch {
errorMessage += `: ${errorText}`;
}
}
} catch {
}
throw new Error(errorMessage);
}
if (response.status === 204) {
return void 0;
}
return response.json();
}
/**
* Get all worlds accessible with current credentials
* @deprecated Use client.worlds.list() instead for consistent API
*/
async getWorlds() {
return this.request("GET", "/world/");
}
/**
* Helper to convert nested objects to _id/_ids format
*/
static prepareInput(data) {
const result = { ...data };
for (const [key, value] of Object.entries(result)) {
if (value && typeof value === "object" && "id" in value) {
delete result[key];
result[`${key}_id`] = value.id;
} else if (Array.isArray(value) && value.length > 0 && typeof value[0] === "object" && "id" in value[0]) {
delete result[key];
result[`${key}_ids`] = value.map((item) => item.id);
}
}
return result;
}
};
// src/types.ts
var ElementType = /* @__PURE__ */ ((ElementType2) => {
ElementType2["Ability"] = "ability";
ElementType2["Character"] = "character";
ElementType2["Collective"] = "collective";
ElementType2["Construct"] = "construct";
ElementType2["Creature"] = "creature";
ElementType2["Event"] = "event";
ElementType2["Family"] = "family";
ElementType2["Institution"] = "institution";
ElementType2["Language"] = "language";
ElementType2["Law"] = "law";
ElementType2["Location"] = "location";
ElementType2["Map"] = "map";
ElementType2["Marker"] = "marker";
ElementType2["Narrative"] = "narrative";
ElementType2["Object"] = "object";
ElementType2["Phenomenon"] = "phenomenon";
ElementType2["Pin"] = "pin";
ElementType2["Relation"] = "relation";
ElementType2["Species"] = "species";
ElementType2["Title"] = "title";
ElementType2["Trait"] = "trait";
ElementType2["Zone"] = "zone";
return ElementType2;
})(ElementType || {});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ElementType,
OnlyWorldsClient
});