946 lines
45 KiB
JavaScript
946 lines
45 KiB
JavaScript
/**
|
|
* مرجع API Hesabix v2 — ایندکس سبک، گروه تگ، صفحهبندی، نمونه کد
|
|
*/
|
|
(function () {
|
|
'use strict';
|
|
|
|
var cfg = typeof hesabixApiDocs !== 'undefined' ? hesabixApiDocs : {};
|
|
var i18n = cfg.i18n || {};
|
|
var HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
|
|
var STORAGE_KEY = 'hesabix2_api_key';
|
|
var STORAGE_SESSION = 'hesabix2_api_key_session';
|
|
var SERVER_KEY = 'hesabix2_api_server';
|
|
var BIZ_KEY = 'hesabix2_api_business_id';
|
|
var PAGE_SIZE = cfg.listPageSize || 60;
|
|
|
|
function $(id) { return document.getElementById(id); }
|
|
|
|
function escHtml(s) {
|
|
if (s == null) return '';
|
|
return String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
}
|
|
|
|
function highlight(text, q) {
|
|
if (!q) return escHtml(text);
|
|
var re = new RegExp('(' + q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') + ')', 'gi');
|
|
return escHtml(text).replace(re, '<mark class="api-docs-mark">$1</mark>');
|
|
}
|
|
|
|
function mdToHtml(md) {
|
|
if (!md) return '';
|
|
var codeSlots = [];
|
|
var slotIdx = 0;
|
|
md = md.replace(/```[\w]*\n([\s\S]*?)```/g, function (_, code) {
|
|
var token = '\x00C' + (slotIdx++) + '\x00';
|
|
codeSlots.push({ token: token, html: '<pre><code>' + escHtml(code.trim()) + '</code></pre>' });
|
|
return token;
|
|
});
|
|
var html = escHtml(md);
|
|
codeSlots.forEach(function (s) { html = html.split(s.token).join(s.html); });
|
|
html = html.replace(/^### (.+)$/gm, '<h3>$1</h3>');
|
|
html = html.replace(/^## (.+)$/gm, '<h2>$1</h2>');
|
|
html = html.replace(/^# (.+)$/gm, '<h1>$1</h1>');
|
|
html = html.replace(/^---$/gm, '<hr>');
|
|
html = html.replace(/`([^`]+)`/g, '<code>$1</code>');
|
|
html = html.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
|
|
html = html.replace(/^\|(.+)\|\s*\n\|[-|\s]+\|\s*\n((?:\|.+\|\s*\n?)*)/gm, function (_, h, rows) {
|
|
var ths = h.split('|').filter(Boolean).map(function (c) { return '<th>' + c.trim() + '</th>'; }).join('');
|
|
var trs = rows.trim().split('\n').map(function (row) {
|
|
return '<tr>' + row.split('|').filter(Boolean).map(function (c) { return '<td>' + c.trim() + '</td>'; }).join('') + '</tr>';
|
|
}).join('');
|
|
return '<table><thead><tr>' + ths + '</tr></thead><tbody>' + trs + '</tbody></table>';
|
|
});
|
|
html = html.replace(/^- (.+)$/gm, '<li>$1</li>');
|
|
html = html.replace(/(<li>[\s\S]*?<\/li>)+/g, function (b) { return '<ul>' + b + '</ul>'; });
|
|
html = html.replace(/\n\n+/g, '</p><p>');
|
|
html = '<p>' + html + '</p>';
|
|
html = html.replace(/<p>\s*<(h[123]|ul|table|pre|hr)/g, '<$2');
|
|
html = html.replace(/<\/(h[123]|ul|table|pre|hr)>\s*<\/p>/g, '</$1>');
|
|
html = html.replace(/<p>\s*<\/p>/g, '');
|
|
return html;
|
|
}
|
|
|
|
function resolveRef(spec, ref, depth) {
|
|
depth = depth || 0;
|
|
if (!ref || ref.indexOf('#/') !== 0 || depth > 8) return null;
|
|
var parts = ref.slice(2).split('/');
|
|
var node = spec;
|
|
for (var i = 0; i < parts.length; i++) {
|
|
if (!node) return null;
|
|
node = node[parts[i]];
|
|
}
|
|
if (node && node.$ref) return resolveRef(spec, node.$ref, depth + 1);
|
|
return node;
|
|
}
|
|
|
|
function schemaTypeName(schema, spec) {
|
|
if (!schema) return '';
|
|
if (schema.$ref) {
|
|
var r = resolveRef(spec, schema.$ref);
|
|
return r && r.title ? r.title : schema.$ref.split('/').pop();
|
|
}
|
|
if (schema.type) return schema.type;
|
|
if (schema.allOf) return 'object';
|
|
return '';
|
|
}
|
|
|
|
function getExampleFromContent(content, spec) {
|
|
if (!content) return '';
|
|
var ct = content['application/json'] || content['application/json; charset=utf-8'];
|
|
if (!ct) return '';
|
|
if (ct.example) return JSON.stringify(ct.example, null, 2);
|
|
if (ct.schema) {
|
|
var schema = ct.schema.$ref ? resolveRef(spec, ct.schema.$ref) : ct.schema;
|
|
if (schema && schema.example) return JSON.stringify(schema.example, null, 2);
|
|
}
|
|
return '{\n \n}';
|
|
}
|
|
|
|
var App = {
|
|
index: null,
|
|
spec: null,
|
|
specLoading: false,
|
|
specReady: false,
|
|
operations: [],
|
|
tagCounts: {},
|
|
activeGroup: 'start',
|
|
activeTag: null,
|
|
activeOpId: null,
|
|
searchQuery: '',
|
|
listOffset: 0,
|
|
serverUrl: '',
|
|
apiKey: '',
|
|
useSessionStorage: false,
|
|
readOnly: false,
|
|
codeLang: 'curl',
|
|
|
|
init: function () {
|
|
this.activeGroup = 'start';
|
|
this.activeTag = cfg.defaultTag || 'احراز هویت';
|
|
this.serverUrl = localStorage.getItem(SERVER_KEY) || cfg.defaultServer || '';
|
|
this.loadApiKey();
|
|
var biz = localStorage.getItem(BIZ_KEY);
|
|
if (biz && $('api-docs-h-business')) $('api-docs-h-business').value = biz;
|
|
this.bindEvents();
|
|
this.updateAuthUi();
|
|
this.loadIndex();
|
|
},
|
|
|
|
loadApiKey: function () {
|
|
this.apiKey = sessionStorage.getItem(STORAGE_SESSION) || localStorage.getItem(STORAGE_KEY) || '';
|
|
this.useSessionStorage = !!sessionStorage.getItem(STORAGE_SESSION);
|
|
},
|
|
|
|
saveApiKey: function (val, sessionOnly) {
|
|
this.apiKey = val;
|
|
if (sessionOnly) {
|
|
sessionStorage.setItem(STORAGE_SESSION, val);
|
|
localStorage.removeItem(STORAGE_KEY);
|
|
} else if (val) {
|
|
localStorage.setItem(STORAGE_KEY, val);
|
|
sessionStorage.removeItem(STORAGE_SESSION);
|
|
} else {
|
|
localStorage.removeItem(STORAGE_KEY);
|
|
sessionStorage.removeItem(STORAGE_SESSION);
|
|
}
|
|
this.updateAuthUi();
|
|
},
|
|
|
|
updateAuthUi: function () {
|
|
var badge = $('api-docs-auth-badge');
|
|
var label = $('api-docs-auth-label');
|
|
var btn = $('api-docs-auth-btn');
|
|
if (!label) return;
|
|
if (this.apiKey) {
|
|
label.textContent = i18n.authorizeActive || 'کلید فعال';
|
|
if (badge) { badge.hidden = false; badge.textContent = '●'; }
|
|
if (btn) btn.classList.add('api-docs-auth-btn--active');
|
|
} else {
|
|
label.textContent = i18n.authorize || 'کلید API';
|
|
if (badge) badge.hidden = true;
|
|
if (btn) btn.classList.remove('api-docs-auth-btn--active');
|
|
}
|
|
},
|
|
|
|
bindEvents: function () {
|
|
var self = this;
|
|
var search = $('api-docs-search');
|
|
var debounce;
|
|
|
|
$('api-docs-retry') && $('api-docs-retry').addEventListener('click', function () { self.loadIndex(true); });
|
|
$('api-docs-admin-refresh') && $('api-docs-admin-refresh').addEventListener('click', function () {
|
|
self.loadIndex(true);
|
|
self.spec = null;
|
|
self.specReady = false;
|
|
});
|
|
|
|
if (search) {
|
|
search.placeholder = i18n.searchPlaceholder || '';
|
|
search.addEventListener('input', function () {
|
|
clearTimeout(debounce);
|
|
debounce = setTimeout(function () {
|
|
self.searchQuery = search.value.trim().toLowerCase();
|
|
self.listOffset = 0;
|
|
self.renderOpList();
|
|
}, 180);
|
|
});
|
|
}
|
|
|
|
document.addEventListener('keydown', function (e) {
|
|
if ((e.metaKey || e.ctrlKey) && e.key === 'k') {
|
|
e.preventDefault();
|
|
if (search) search.focus();
|
|
}
|
|
});
|
|
|
|
$('api-docs-server') && $('api-docs-server').addEventListener('change', function () {
|
|
self.serverUrl = $('api-docs-server').value.replace(/\/$/, '');
|
|
localStorage.setItem(SERVER_KEY, self.serverUrl);
|
|
});
|
|
|
|
$('api-docs-h-business') && $('api-docs-h-business').addEventListener('change', function () {
|
|
localStorage.setItem(BIZ_KEY, $('api-docs-h-business').value.trim());
|
|
});
|
|
|
|
$('api-docs-readonly') && $('api-docs-readonly').addEventListener('change', function () {
|
|
self.readOnly = $('api-docs-readonly').checked;
|
|
var ex = $('api-docs-execute');
|
|
if (ex) ex.disabled = self.readOnly;
|
|
});
|
|
|
|
$('api-docs-auth-btn') && $('api-docs-auth-btn').addEventListener('click', function () {
|
|
var dlg = $('api-docs-auth-dialog');
|
|
if (dlg) {
|
|
$('api-docs-auth-input').value = self.apiKey;
|
|
$('api-docs-auth-session').checked = self.useSessionStorage;
|
|
dlg.showModal();
|
|
}
|
|
});
|
|
|
|
var authForm = $('api-docs-auth-form');
|
|
authForm && authForm.addEventListener('submit', function (e) {
|
|
e.preventDefault();
|
|
var val = $('api-docs-auth-input').value.trim();
|
|
var sess = $('api-docs-auth-session').checked;
|
|
self.saveApiKey(val, sess);
|
|
$('api-docs-auth-dialog').close();
|
|
});
|
|
|
|
document.querySelectorAll('[data-close-dialog]').forEach(function (el) {
|
|
el.addEventListener('click', function () {
|
|
el.closest('dialog').close();
|
|
});
|
|
});
|
|
|
|
$('api-docs-auth-clear') && $('api-docs-auth-clear').addEventListener('click', function () {
|
|
self.saveApiKey('', false);
|
|
$('api-docs-auth-input').value = '';
|
|
});
|
|
|
|
$('api-docs-back') && $('api-docs-back').addEventListener('click', function () { self.closeDetailMobile(); });
|
|
$('api-docs-execute') && $('api-docs-execute').addEventListener('click', function () { self.executeTry(); });
|
|
$('api-docs-copy-curl') && $('api-docs-copy-curl').addEventListener('click', function () { self.copyText(self.buildCurl(), $('api-docs-copy-curl')); });
|
|
$('api-docs-copy-code') && $('api-docs-copy-code').addEventListener('click', function () {
|
|
var pre = $('api-docs-code-block');
|
|
if (pre) self.copyText(pre.textContent, $('api-docs-copy-code'));
|
|
});
|
|
|
|
$('api-docs-load-more') && $('api-docs-load-more').addEventListener('click', function () {
|
|
self.listOffset += PAGE_SIZE;
|
|
self.renderOpList(true);
|
|
});
|
|
|
|
$('api-docs-toggle-schemas') && $('api-docs-toggle-schemas').addEventListener('click', function () {
|
|
var panel = $('api-docs-schemas-panel');
|
|
if (panel) panel.classList.toggle('hidden');
|
|
});
|
|
|
|
var schemaSearch = $('api-docs-schema-search');
|
|
schemaSearch && schemaSearch.addEventListener('input', function () {
|
|
self.renderSchemaList(schemaSearch.value.trim().toLowerCase());
|
|
});
|
|
|
|
document.querySelectorAll('.api-docs-code-tab').forEach(function (tab) {
|
|
tab.addEventListener('click', function () {
|
|
document.querySelectorAll('.api-docs-code-tab').forEach(function (t) { t.classList.remove('is-active'); });
|
|
tab.classList.add('is-active');
|
|
self.codeLang = tab.getAttribute('data-lang');
|
|
self.renderCodeSample();
|
|
});
|
|
});
|
|
|
|
document.querySelectorAll('.api-docs-quickstart__link').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
var tag = btn.getAttribute('data-goto-tag');
|
|
var op = btn.getAttribute('data-goto-op');
|
|
if (tag) self.activeTag = tag;
|
|
self.listOffset = 0;
|
|
self.renderTagNav();
|
|
self.renderOpList();
|
|
document.getElementById('api-docs-explorer').scrollIntoView({ behavior: 'smooth' });
|
|
if (op) setTimeout(function () { self.selectOperation(op); }, 400);
|
|
});
|
|
});
|
|
|
|
window.addEventListener('hashchange', function () { self.applyHash(); });
|
|
},
|
|
|
|
fetchJson: function (url) {
|
|
return fetch(url, { credentials: 'same-origin', headers: { Accept: 'application/json' } })
|
|
.then(function (res) {
|
|
if (!res.ok) throw new Error('HTTP ' + res.status);
|
|
return res.json();
|
|
});
|
|
},
|
|
|
|
loadIndex: function (force) {
|
|
var self = this;
|
|
this.showLoading();
|
|
var url = cfg.indexUrl || '';
|
|
if (force && cfg.canRefresh && cfg.refreshIndexUrl) url = cfg.refreshIndexUrl;
|
|
|
|
this.fetchJson(url)
|
|
.then(function (idx) { self.onIndexLoaded(idx, 'proxy'); self.loadSpecBackground(); })
|
|
.catch(function () {
|
|
return self.fetchJson(cfg.specFallbackUrl).then(function (full) {
|
|
var idx = self.buildIndexFromSpec(full);
|
|
self.onIndexLoaded(idx, 'direct');
|
|
self.spec = full;
|
|
self.specReady = true;
|
|
});
|
|
})
|
|
.catch(function (err) { self.showError(err.message || i18n.loadError); });
|
|
},
|
|
|
|
loadSpecBackground: function () {
|
|
if (this.specLoading || this.specReady) return;
|
|
var self = this;
|
|
this.specLoading = true;
|
|
this.fetchJson(cfg.specUrl)
|
|
.then(function (spec) {
|
|
self.spec = spec;
|
|
self.specReady = true;
|
|
self.specLoading = false;
|
|
if (self.activeOpId) self.enrichDetail(self.activeOpId);
|
|
})
|
|
.catch(function () {
|
|
self.specLoading = false;
|
|
return self.fetchJson(cfg.specFallbackUrl).then(function (spec) {
|
|
self.spec = spec;
|
|
self.specReady = true;
|
|
if (self.activeOpId) self.enrichDetail(self.activeOpId);
|
|
});
|
|
});
|
|
},
|
|
|
|
buildIndexFromSpec: function (spec) {
|
|
var self = this;
|
|
var ops = [];
|
|
var tagCounts = {};
|
|
var globalSec = !!spec.security;
|
|
Object.keys(spec.paths || {}).forEach(function (path) {
|
|
if (path === '/') return;
|
|
var pi = spec.paths[path];
|
|
HTTP_METHODS.forEach(function (method) {
|
|
var op = pi[method];
|
|
if (!op) return;
|
|
var tags = op.tags && op.tags.length ? op.tags : ['other'];
|
|
var id = op.operationId || method + '_' + path.replace(/[^\w]+/g, '_');
|
|
var desc = (op.description || '').replace(/<[^>]+>/g, '').slice(0, 400);
|
|
ops.push({
|
|
id: id, method: method, path: path, summary: op.summary || '',
|
|
tags: tags, groupId: self.resolveGroup(tags), secured: globalSec || !!op.security, desc: desc
|
|
});
|
|
tags.forEach(function (t) { tagCounts[t] = (tagCounts[t] || 0) + 1; });
|
|
});
|
|
});
|
|
return {
|
|
info: spec.info, servers: spec.servers, operations: ops,
|
|
tagCounts: tagCounts, tagGroups: cfg.tagGroups || [], defaultTag: cfg.defaultTag,
|
|
schemaNames: Object.keys(spec.components && spec.components.schemas || {})
|
|
};
|
|
},
|
|
|
|
resolveGroup: function (tags) {
|
|
var groups = cfg.tagGroups || [];
|
|
for (var g = 0; g < groups.length; g++) {
|
|
for (var t = 0; t < groups[g].tags.length; t++) {
|
|
for (var i = 0; i < tags.length; i++) {
|
|
if (tags[i] === groups[g].tags[t] || tags[i].indexOf(groups[g].tags[t]) >= 0) return groups[g].id;
|
|
}
|
|
}
|
|
}
|
|
return 'other';
|
|
},
|
|
|
|
onIndexLoaded: function (idx, source) {
|
|
this.index = idx;
|
|
this.operations = idx.operations || [];
|
|
this.tagCounts = idx.tagCounts || {};
|
|
if (!this.activeTag) this.activeTag = idx.defaultTag || cfg.defaultTag;
|
|
this.hideLoading();
|
|
this.renderHero();
|
|
this.renderIntro();
|
|
this.renderGroupNav();
|
|
this.renderTagNav();
|
|
this.renderOpList();
|
|
this.renderSchemaList('');
|
|
this.renderEmptySuggestions();
|
|
this.setPanelView('empty');
|
|
this.updateSyncStatus(source);
|
|
if ($('api-docs-toggle-schemas')) $('api-docs-toggle-schemas').hidden = !(idx.schemaNames && idx.schemaNames.length);
|
|
if ($('api-docs-admin-refresh') && cfg.canRefresh) $('api-docs-admin-refresh').hidden = false;
|
|
if ($('api-docs-server') && idx.servers && idx.servers[0] && !localStorage.getItem(SERVER_KEY)) {
|
|
this.serverUrl = idx.servers[0].url.replace(/\/$/, '');
|
|
$('api-docs-server').value = this.serverUrl;
|
|
} else if ($('api-docs-server')) {
|
|
$('api-docs-server').value = this.serverUrl;
|
|
}
|
|
this.applyHash();
|
|
},
|
|
|
|
showLoading: function () {
|
|
$('api-docs-loading') && ($('api-docs-loading').hidden = false);
|
|
$('api-docs-error') && ($('api-docs-error').hidden = true);
|
|
$('api-docs-app') && ($('api-docs-app').hidden = true);
|
|
},
|
|
|
|
hideLoading: function () {
|
|
$('api-docs-loading') && ($('api-docs-loading').hidden = true);
|
|
$('api-docs-app') && ($('api-docs-app').hidden = false);
|
|
},
|
|
|
|
showError: function (msg) {
|
|
$('api-docs-loading') && ($('api-docs-loading').hidden = true);
|
|
$('api-docs-app') && ($('api-docs-app').hidden = true);
|
|
if ($('api-docs-error')) {
|
|
$('api-docs-error').hidden = false;
|
|
var el = $('api-docs-error').querySelector('.api-docs-error__msg');
|
|
if (el) el.textContent = msg;
|
|
}
|
|
},
|
|
|
|
renderHero: function () {
|
|
var stats = $('api-docs-hero-stats');
|
|
if (!stats || !this.index) return;
|
|
var info = this.index.info || {};
|
|
stats.innerHTML =
|
|
'<li><strong>' + escHtml(info.version || '—') + '</strong><span>نسخه</span></li>' +
|
|
'<li><strong>' + this.operations.length + '</strong><span>' + escHtml(i18n.endpoints || '') + '</span></li>' +
|
|
'<li><strong>' + Object.keys(this.tagCounts).length + '</strong><span>' + escHtml(i18n.tags || '') + '</span></li>';
|
|
stats.hidden = false;
|
|
},
|
|
|
|
renderIntro: function () {
|
|
var body = $('api-docs-intro-body');
|
|
if (!body || !this.index || !this.index.info) return;
|
|
body.innerHTML = mdToHtml(this.index.info.description || '');
|
|
},
|
|
|
|
updateSyncStatus: function (source) {
|
|
var el = $('api-docs-sync-status');
|
|
if (!el) return;
|
|
var ver = this.index.info && this.index.info.version ? ' · v' + this.index.info.version : '';
|
|
var fetched = this.index.fetchedAt ? ' · ' + new Date(this.index.fetchedAt).toLocaleString('fa-IR') : '';
|
|
el.textContent = (source === 'direct' ? i18n.fromSource : i18n.fromCache) + ver + fetched;
|
|
},
|
|
|
|
renderGroupNav: function () {
|
|
var nav = $('api-docs-group-nav');
|
|
if (!nav) return;
|
|
var self = this;
|
|
var groups = (this.index && this.index.tagGroups) || cfg.tagGroups || [];
|
|
groups.push({ id: 'other', label: i18n.otherTags || 'سایر' });
|
|
var html = '';
|
|
groups.forEach(function (g) {
|
|
html += '<button type="button" class="api-docs-group-btn' + (self.activeGroup === g.id ? ' is-active' : '') + '" data-group="' + escHtml(g.id) + '">' + escHtml(g.label) + '</button>';
|
|
});
|
|
nav.innerHTML = html;
|
|
nav.querySelectorAll('.api-docs-group-btn').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
self.activeGroup = btn.getAttribute('data-group');
|
|
self.listOffset = 0;
|
|
nav.querySelectorAll('.api-docs-group-btn').forEach(function (b) {
|
|
b.classList.toggle('is-active', b === btn);
|
|
});
|
|
self.renderTagNav();
|
|
self.renderOpList();
|
|
});
|
|
});
|
|
},
|
|
|
|
getTagsForGroup: function () {
|
|
var self = this;
|
|
var tags = Object.keys(this.tagCounts);
|
|
if (this.activeGroup === 'other') {
|
|
var known = {};
|
|
(cfg.tagGroups || []).forEach(function (g) {
|
|
g.tags.forEach(function (t) { known[t] = true; });
|
|
});
|
|
return tags.filter(function (t) {
|
|
return !known[t] && self.operations.some(function (op) {
|
|
return op.groupId === 'other' && op.tags.indexOf(t) >= 0;
|
|
});
|
|
}).sort();
|
|
}
|
|
var group = (cfg.tagGroups || []).find(function (g) { return g.id === self.activeGroup; });
|
|
if (!group) return tags.sort();
|
|
return tags.filter(function (t) {
|
|
return group.tags.indexOf(t) >= 0 || self.operations.some(function (op) {
|
|
return op.tags.indexOf(t) >= 0 && op.groupId === self.activeGroup;
|
|
});
|
|
}).sort();
|
|
},
|
|
|
|
renderTagNav: function () {
|
|
var nav = $('api-docs-tag-nav');
|
|
if (!nav) return;
|
|
var self = this;
|
|
var tags = this.getTagsForGroup();
|
|
var html = '<button type="button" class="api-docs-tag-btn' + (!this.activeTag ? ' is-active' : '') + '" data-tag="">' +
|
|
'<span>' + escHtml(i18n.allTags || 'همه') + '</span></button>';
|
|
tags.forEach(function (tag) {
|
|
html += '<button type="button" class="api-docs-tag-btn' + (self.activeTag === tag ? ' is-active' : '') + '" data-tag="' + escHtml(tag) + '">' +
|
|
'<span>' + escHtml(tag) + '</span><span class="api-docs-tag-btn__count">' + (self.tagCounts[tag] || 0) + '</span></button>';
|
|
});
|
|
nav.innerHTML = html;
|
|
nav.querySelectorAll('.api-docs-tag-btn').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
self.activeTag = btn.getAttribute('data-tag') || null;
|
|
self.listOffset = 0;
|
|
nav.querySelectorAll('.api-docs-tag-btn').forEach(function (b) {
|
|
b.classList.toggle('is-active', b === btn);
|
|
});
|
|
self.renderOpList();
|
|
});
|
|
});
|
|
},
|
|
|
|
getFilteredOps: function () {
|
|
var self = this;
|
|
return this.operations.filter(function (op) {
|
|
if (self.activeGroup === 'other' && op.groupId !== 'other') return false;
|
|
if (self.activeGroup && self.activeGroup !== 'other' && op.groupId !== self.activeGroup) return false;
|
|
if (self.activeTag && op.tags.indexOf(self.activeTag) === -1) return false;
|
|
if (self.searchQuery) {
|
|
var hay = (op.method + ' ' + op.path + ' ' + op.summary + ' ' + op.id + ' ' + op.desc).toLowerCase();
|
|
if (hay.indexOf(self.searchQuery) === -1) return false;
|
|
}
|
|
return true;
|
|
});
|
|
},
|
|
|
|
renderOpList: function (append) {
|
|
var list = $('api-docs-op-list');
|
|
var title = $('api-docs-op-list-title');
|
|
var range = $('api-docs-op-list-range');
|
|
var loadMore = $('api-docs-load-more');
|
|
if (!list) return;
|
|
|
|
var all = this.getFilteredOps();
|
|
var slice = all.slice(0, this.listOffset + PAGE_SIZE);
|
|
if (title) {
|
|
title.textContent = (this.activeTag || i18n.allTags) + ' (' + all.length + ')';
|
|
}
|
|
if (range) {
|
|
range.textContent = (i18n.showing || '') + ' ' + slice.length + ' ' + (i18n.of || '') + ' ' + all.length;
|
|
}
|
|
if (loadMore) loadMore.hidden = slice.length >= all.length;
|
|
|
|
if (!all.length) {
|
|
list.innerHTML = '<li class="api-docs-op-item"><span class="p-4 text-slate-500 text-sm">' + escHtml(i18n.noResults) + '</span></li>';
|
|
return;
|
|
}
|
|
|
|
var self = this;
|
|
var html = '';
|
|
slice.forEach(function (op) {
|
|
html += '<li class="api-docs-op-item"><button type="button" class="api-docs-op-link' +
|
|
(self.activeOpId === op.id ? ' is-active' : '') + '" data-op="' + escHtml(op.id) + '">' +
|
|
'<span class="api-docs-method api-docs-method--' + op.method + '">' + op.method.toUpperCase() + '</span>' +
|
|
'<span class="api-docs-op-link__path">' + highlight(op.path, self.searchQuery) + '</span>' +
|
|
(op.secured ? '<span class="api-docs-op-lock" title="' + escHtml(i18n.secured) + '">🔒</span>' : '') +
|
|
'</button></li>';
|
|
});
|
|
list.innerHTML = html;
|
|
list.querySelectorAll('.api-docs-op-link').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
self.selectOperation(btn.getAttribute('data-op'));
|
|
});
|
|
});
|
|
},
|
|
|
|
selectOperation: function (opId) {
|
|
var entry = this.operations.find(function (o) { return o.id === opId; });
|
|
if (!entry) return;
|
|
this.activeOpId = opId;
|
|
history.replaceState(null, '', '#op-' + encodeURIComponent(opId));
|
|
this.renderOpList();
|
|
this.renderDetailFromIndex(entry);
|
|
this.openDetailMobile();
|
|
var det = $('api-docs-detail');
|
|
if (det) det.scrollTop = 0;
|
|
if (!this.specReady) {
|
|
$('api-docs-spec-loading') && ($('api-docs-spec-loading').hidden = false);
|
|
this.loadSpecBackground();
|
|
} else {
|
|
this.enrichDetail(opId);
|
|
}
|
|
},
|
|
|
|
applyHash: function () {
|
|
var hash = decodeURIComponent(location.hash.replace(/^#/, ''));
|
|
if (hash.indexOf('op-') === 0) this.selectOperation(hash.slice(3));
|
|
},
|
|
|
|
setPanelView: function (mode) {
|
|
var ph = $('api-docs-placeholder');
|
|
var det = $('api-docs-detail');
|
|
var col = document.querySelector('.api-docs-detail-column');
|
|
if (mode === 'detail') {
|
|
if (ph) ph.hidden = true;
|
|
if (det) det.hidden = false;
|
|
if (col) col.classList.add('api-docs-detail-column--active');
|
|
} else {
|
|
if (ph) ph.hidden = false;
|
|
if (det) det.hidden = true;
|
|
if (col) col.classList.remove('api-docs-detail-column--active');
|
|
}
|
|
},
|
|
|
|
renderEmptySuggestions: function () {
|
|
var wrap = $('api-docs-empty-suggestions');
|
|
if (!wrap) return;
|
|
var picks = [
|
|
{ id: 'health_api_v1_health_get' },
|
|
{ id: 'generate_captcha_api_v1_auth_captcha_post' },
|
|
{ id: 'login_api_v1_auth_login_post' },
|
|
{ id: 'get_current_user_info_api_v1_auth_me_get' },
|
|
];
|
|
var self = this;
|
|
var html = '';
|
|
picks.forEach(function (p) {
|
|
var op = self.operations.find(function (o) { return o.id === p.id; });
|
|
if (!op) return;
|
|
html += '<button type="button" class="api-docs-empty__chip" data-op="' + escHtml(op.id) + '" data-tag="' + escHtml(op.tags[0] || '') + '">' +
|
|
'<span class="api-docs-method api-docs-method--' + op.method + '">' + op.method.toUpperCase() + '</span>' +
|
|
'<span class="api-docs-empty__chip-path">' + escHtml(op.summary || op.path) + '</span></button>';
|
|
});
|
|
wrap.innerHTML = html;
|
|
wrap.querySelectorAll('.api-docs-empty__chip').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
var tag = btn.getAttribute('data-tag');
|
|
if (tag) {
|
|
self.activeTag = tag;
|
|
self.activeGroup = 'start';
|
|
self.listOffset = 0;
|
|
self.renderGroupNav();
|
|
self.renderTagNav();
|
|
self.renderOpList();
|
|
}
|
|
self.selectOperation(btn.getAttribute('data-op'));
|
|
document.getElementById('api-docs-explorer').scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
|
});
|
|
});
|
|
},
|
|
|
|
openDetailMobile: function () {
|
|
var panel = document.querySelector('.api-docs-panel');
|
|
if (panel) panel.classList.add('api-docs-panel--detail-open');
|
|
},
|
|
|
|
closeDetailMobile: function () {
|
|
var panel = document.querySelector('.api-docs-panel');
|
|
if (panel) panel.classList.remove('api-docs-panel--detail-open');
|
|
this.setPanelView('empty');
|
|
this.activeOpId = null;
|
|
history.replaceState(null, '', location.pathname + location.search);
|
|
this.renderOpList();
|
|
},
|
|
|
|
renderDetailFromIndex: function (entry) {
|
|
this.setPanelView('detail');
|
|
$('api-docs-detail-method').textContent = entry.method.toUpperCase();
|
|
$('api-docs-detail-method').className = 'api-docs-method api-docs-method--' + entry.method;
|
|
$('api-docs-detail-path').textContent = entry.path;
|
|
$('api-docs-detail-summary').textContent = entry.summary || entry.path;
|
|
$('api-docs-detail-desc').innerHTML = mdToHtml(entry.desc || '');
|
|
var badge = $('api-docs-secured-badge');
|
|
if (badge) {
|
|
badge.hidden = false;
|
|
badge.textContent = entry.secured ? (i18n.secured || '') : (i18n.public || '');
|
|
badge.className = 'api-docs-secured-badge ' + (entry.secured ? 'api-docs-secured-badge--yes' : 'api-docs-secured-badge--no');
|
|
}
|
|
$('api-docs-detail-sections').innerHTML = '';
|
|
$('api-docs-code-samples') && ($('api-docs-code-samples').hidden = false);
|
|
this.renderCodeSample(entry);
|
|
this.buildTryPanelBasic(entry);
|
|
},
|
|
|
|
enrichDetail: function (opId) {
|
|
$('api-docs-spec-loading') && ($('api-docs-spec-loading').hidden = true);
|
|
if (!this.spec) return;
|
|
var entry = this.operations.find(function (o) { return o.id === opId; });
|
|
if (!entry) return;
|
|
var pathItem = this.spec.paths[entry.path];
|
|
if (!pathItem) return;
|
|
var op = pathItem[entry.method];
|
|
if (!op) return;
|
|
$('api-docs-detail-desc').innerHTML = mdToHtml(op.description || entry.desc || '');
|
|
$('api-docs-detail-sections').innerHTML = this.buildDetailSections(op);
|
|
this.buildTryPanelFull(entry, op);
|
|
this.renderCodeSample(entry, op);
|
|
},
|
|
|
|
buildDetailSections: function (op) {
|
|
var html = '';
|
|
var spec = this.spec;
|
|
var params = [].concat(op.parameters || []);
|
|
if (params.length) {
|
|
html += '<section><h3 class="api-docs-section-title">' + escHtml(i18n.parameters) + '</h3><table class="api-docs-params-table"><thead><tr><th>نام</th><th>محل</th><th>نوع</th><th>توضیح</th></tr></thead><tbody>';
|
|
params.forEach(function (p) {
|
|
if (p.$ref) p = resolveRef(spec, p.$ref) || p;
|
|
var schema = p.schema || {};
|
|
html += '<tr><td><code>' + escHtml(p.name) + '</code>' + (p.required ? ' *' : '') + '</td><td>' + escHtml(p.in) + '</td><td>' + escHtml(schemaTypeName(schema, spec)) + '</td><td>' + escHtml(p.description || '') + '</td></tr>';
|
|
});
|
|
html += '</tbody></table></section>';
|
|
}
|
|
if (op.requestBody) {
|
|
var rb = op.requestBody.$ref ? resolveRef(spec, op.requestBody.$ref) : op.requestBody;
|
|
html += '<section><h3 class="api-docs-section-title">' + escHtml(i18n.requestBody) + '</h3><pre class="api-docs-result-pre" style="max-height:10rem">' + escHtml(getExampleFromContent(rb.content, spec)) + '</pre></section>';
|
|
}
|
|
if (op.responses) {
|
|
html += '<section><h3 class="api-docs-section-title">' + escHtml(i18n.responses) + '</h3>';
|
|
Object.keys(op.responses).forEach(function (code) {
|
|
var resp = op.responses[code];
|
|
if (resp.$ref) resp = resolveRef(spec, resp.$ref) || resp;
|
|
var ex = resp.content && resp.content['application/json'] && resp.content['application/json'].example
|
|
? JSON.stringify(resp.content['application/json'].example, null, 2) : '';
|
|
html += '<details class="api-docs-response-block"><summary>' + escHtml(code) + ' — ' + escHtml(resp.description || '') + '</summary>';
|
|
if (ex) html += '<pre>' + escHtml(ex) + '</pre>';
|
|
html += '</details>';
|
|
});
|
|
html += '</section>';
|
|
}
|
|
return html;
|
|
},
|
|
|
|
buildTryPanelBasic: function (entry) {
|
|
var wrap = $('api-docs-try-params');
|
|
if (wrap) wrap.innerHTML = '<p class="text-sm text-slate-500">' + escHtml(i18n.loadingSpec || '') + '</p>';
|
|
$('api-docs-try-result') && ($('api-docs-try-result').hidden = true);
|
|
$('api-docs-cors-hint') && ($('api-docs-cors-hint').hidden = true);
|
|
},
|
|
|
|
buildTryPanelFull: function (entry, op) {
|
|
var wrap = $('api-docs-try-params');
|
|
var bodyTa = $('api-docs-try-body');
|
|
var spec = this.spec;
|
|
if (!wrap) return;
|
|
var html = '';
|
|
[].concat(op.parameters || []).forEach(function (p) {
|
|
if (p.$ref) p = resolveRef(spec, p.$ref) || p;
|
|
html += '<label class="api-docs-field api-docs-field--block"><span class="api-docs-field__label">' +
|
|
escHtml(p.name) + ' (' + escHtml(p.in) + ')' + (p.required ? ' *' : '') +
|
|
'</span><input type="text" class="api-docs-input api-docs-try-param" dir="ltr" data-name="' + escHtml(p.name) +
|
|
'" data-in="' + escHtml(p.in) + '" /></label>';
|
|
});
|
|
wrap.innerHTML = html || '<p class="text-sm text-slate-400 m-0">—</p>';
|
|
if (bodyTa) {
|
|
if (op.requestBody) {
|
|
var rb = op.requestBody.$ref ? resolveRef(spec, op.requestBody.$ref) : op.requestBody;
|
|
bodyTa.value = getExampleFromContent(rb.content, spec);
|
|
$('api-docs-try-body-wrap').style.display = '';
|
|
} else {
|
|
bodyTa.value = '';
|
|
$('api-docs-try-body-wrap').style.display = 'none';
|
|
}
|
|
}
|
|
},
|
|
|
|
getHeaders: function () {
|
|
var h = {
|
|
Accept: 'application/json',
|
|
'Accept-Language': ($('api-docs-h-lang') && $('api-docs-h-lang').value) || 'fa',
|
|
'X-Calendar-Type': ($('api-docs-h-calendar') && $('api-docs-h-calendar').value) || 'jalali'
|
|
};
|
|
var biz = $('api-docs-h-business') && $('api-docs-h-business').value.trim();
|
|
if (biz) h['X-Business-ID'] = biz;
|
|
var auth = this.getAuthHeader();
|
|
if (auth) h.Authorization = auth;
|
|
return h;
|
|
},
|
|
|
|
getAuthHeader: function () {
|
|
var key = this.apiKey || '';
|
|
if (!key) return null;
|
|
return key.indexOf('ApiKey ') === 0 ? key : 'ApiKey ' + key;
|
|
},
|
|
|
|
buildRequestUrl: function (entry) {
|
|
var base = (($('api-docs-server') && $('api-docs-server').value) || this.serverUrl).replace(/\/$/, '');
|
|
var path = entry.path;
|
|
var query = [];
|
|
document.querySelectorAll('.api-docs-try-param').forEach(function (input) {
|
|
var val = input.value.trim();
|
|
if (!val) return;
|
|
var name = input.getAttribute('data-name');
|
|
var loc = input.getAttribute('data-in');
|
|
if (loc === 'path') path = path.replace('{' + name + '}', encodeURIComponent(val));
|
|
else if (loc === 'query') query.push(encodeURIComponent(name) + '=' + encodeURIComponent(val));
|
|
});
|
|
var url = base + path;
|
|
if (query.length) url += '?' + query.join('&');
|
|
return url;
|
|
},
|
|
|
|
buildCurl: function () {
|
|
var entry = this.operations.find(function (o) { return o.id === this.activeOpId; }.bind(this));
|
|
if (!entry) return '';
|
|
var url = this.buildRequestUrl(entry);
|
|
var h = this.getHeaders();
|
|
var lines = ['curl -s -X ' + entry.method.toUpperCase() + ' "' + url + '"'];
|
|
Object.keys(h).forEach(function (k) { lines.push(' -H "' + k + ': ' + h[k] + '"'); });
|
|
var bodyTa = $('api-docs-try-body');
|
|
if (bodyTa && bodyTa.value.trim() && ['post', 'put', 'patch'].indexOf(entry.method) >= 0) {
|
|
lines.push(' -H "Content-Type: application/json"');
|
|
lines.push(" -d '" + bodyTa.value.trim().replace(/'/g, "'\\''") + "'");
|
|
}
|
|
return lines.join(' \\\n');
|
|
},
|
|
|
|
renderCodeSample: function (entry, op) {
|
|
entry = entry || this.operations.find(function (o) { return o.id === this.activeOpId; }.bind(this));
|
|
if (!entry) return;
|
|
var block = $('api-docs-code-block');
|
|
if (!block) return;
|
|
var curl = this.buildCurl();
|
|
var url = this.buildRequestUrl(entry);
|
|
var method = entry.method.toUpperCase();
|
|
var h = this.getHeaders();
|
|
var body = ($('api-docs-try-body') && $('api-docs-try-body').value.trim()) || '';
|
|
var code = '';
|
|
if (this.codeLang === 'curl') code = curl;
|
|
else if (this.codeLang === 'javascript') {
|
|
var opts = " method: '" + method + "',\n headers: " + JSON.stringify(h, null, 2).replace(/\n/g, '\n ');
|
|
if (body && ['POST', 'PUT', 'PATCH'].indexOf(method) >= 0) opts += ",\n body: JSON.stringify(" + (body.indexOf('{') === 0 ? body : JSON.stringify(body)) + ")";
|
|
code = "const res = await fetch('" + url + "', {\n" + opts + "\n});\nconst data = await res.json();";
|
|
} else if (this.codeLang === 'python') {
|
|
code = "import requests\n\nheaders = " + JSON.stringify(h, null, 2) + "\n";
|
|
if (body && ['post', 'put', 'patch'].indexOf(entry.method) >= 0) {
|
|
code += "r = requests." + entry.method + "('" + url + "', headers=headers, json=" + body + ")\n";
|
|
} else {
|
|
code += "r = requests." + entry.method + "('" + url + "', headers=headers)\n";
|
|
}
|
|
code += 'print(r.json())';
|
|
} else if (this.codeLang === 'php') {
|
|
code = "<?php\n$ch = curl_init('" + url + "');\ncurl_setopt_array($ch, [\n CURLOPT_CUSTOMREQUEST => '" + method + "',\n CURLOPT_RETURNTRANSFER => true,\n CURLOPT_HTTPHEADER => [\n";
|
|
Object.keys(h).forEach(function (k) { code += " '" + k + ": " + h[k] + "',\n"; });
|
|
code += ' ],\n]);\n$response = curl_exec($ch);\nprint_r(json_decode($response, true));';
|
|
}
|
|
block.textContent = code || curl;
|
|
},
|
|
|
|
executeTry: function () {
|
|
if (this.readOnly) return;
|
|
var entry = this.operations.find(function (o) { return o.id === this.activeOpId; }.bind(this));
|
|
if (!entry) return;
|
|
var url = this.buildRequestUrl(entry);
|
|
var headers = this.getHeaders();
|
|
var opts = { method: entry.method.toUpperCase(), headers: headers };
|
|
var bodyTa = $('api-docs-try-body');
|
|
if (bodyTa && bodyTa.value.trim() && ['post', 'put', 'patch'].indexOf(entry.method) >= 0) {
|
|
headers['Content-Type'] = 'application/json';
|
|
opts.body = bodyTa.value.trim();
|
|
}
|
|
var resultWrap = $('api-docs-try-result');
|
|
var corsHint = $('api-docs-cors-hint');
|
|
var statusEl = $('api-docs-result-status');
|
|
var timeEl = $('api-docs-result-time');
|
|
var bodyEl = $('api-docs-result-body');
|
|
if (corsHint) corsHint.hidden = true;
|
|
if (resultWrap) resultWrap.hidden = false;
|
|
if (statusEl) statusEl.textContent = '…';
|
|
if (bodyEl) bodyEl.textContent = '';
|
|
var t0 = performance.now();
|
|
var self = this;
|
|
fetch(url, opts)
|
|
.then(function (res) {
|
|
if (timeEl) timeEl.textContent = Math.round(performance.now() - t0) + ' ms';
|
|
if (statusEl) {
|
|
statusEl.textContent = res.status + ' ' + res.statusText;
|
|
statusEl.className = 'api-docs-status--' + (res.ok ? 'ok' : 'err');
|
|
}
|
|
return res.text().then(function (text) {
|
|
try { bodyEl.textContent = JSON.stringify(JSON.parse(text), null, 2); }
|
|
catch (e) { bodyEl.textContent = text || '(empty)'; }
|
|
});
|
|
})
|
|
.catch(function (err) {
|
|
if (statusEl) { statusEl.textContent = 'Error'; statusEl.className = 'api-docs-status--err'; }
|
|
var msg = err.message || String(err);
|
|
if (bodyEl) bodyEl.textContent = msg;
|
|
if (corsHint && (msg.indexOf('Failed') >= 0 || msg.indexOf('Network') >= 0 || msg.indexOf('fetch') >= 0)) {
|
|
corsHint.hidden = false;
|
|
corsHint.textContent = (i18n.corsError || '') + ' ' + (cfg.swaggerUrl || '');
|
|
}
|
|
});
|
|
},
|
|
|
|
copyText: function (text, btn) {
|
|
if (!navigator.clipboard || !navigator.clipboard.writeText) return;
|
|
navigator.clipboard.writeText(text).then(function () {
|
|
if (btn) {
|
|
var orig = btn.textContent;
|
|
btn.textContent = i18n.copied || 'Copied';
|
|
setTimeout(function () { btn.textContent = orig; }, 1500);
|
|
}
|
|
});
|
|
},
|
|
|
|
renderSchemaList: function (q) {
|
|
var list = $('api-docs-schema-list');
|
|
if (!list || !this.index) return;
|
|
var names = (this.index.schemaNames || []).filter(function (n) {
|
|
return !q || n.toLowerCase().indexOf(q) >= 0;
|
|
});
|
|
var html = '';
|
|
names.slice(0, 200).forEach(function (n) {
|
|
html += '<li><button type="button" class="api-docs-schema-btn" data-schema="' + escHtml(n) + '">' + escHtml(n) + '</button></li>';
|
|
});
|
|
if (names.length > 200) html += '<li class="text-xs text-slate-500 p-2">+' + (names.length - 200) + '</li>';
|
|
list.innerHTML = html;
|
|
var self = this;
|
|
list.querySelectorAll('.api-docs-schema-btn').forEach(function (btn) {
|
|
btn.addEventListener('click', function () {
|
|
self.showSchema(btn.getAttribute('data-schema'));
|
|
});
|
|
});
|
|
},
|
|
|
|
showSchema: function (name) {
|
|
var pre = $('api-docs-schema-detail');
|
|
if (!pre) return;
|
|
if (!this.specReady) {
|
|
pre.hidden = false;
|
|
pre.textContent = i18n.loadingSpec || 'Loading…';
|
|
var self = this;
|
|
this.loadSpecBackground();
|
|
var wait = setInterval(function () {
|
|
if (self.specReady) { clearInterval(wait); self.showSchema(name); }
|
|
}, 300);
|
|
return;
|
|
}
|
|
var schema = this.spec.components.schemas[name];
|
|
if (schema && schema.$ref) schema = resolveRef(this.spec, schema.$ref);
|
|
pre.hidden = false;
|
|
pre.textContent = JSON.stringify(schema, null, 2);
|
|
}
|
|
};
|
|
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', function () { App.init(); });
|
|
} else {
|
|
App.init();
|
|
}
|
|
})();
|