3786 lines
137 KiB
HTML
3786 lines
137 KiB
HTML
<!doctype html>
|
||
<html lang="fa" dir="rtl">
|
||
<head>
|
||
<meta charset="UTF-8" />
|
||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||
<title>XFramework Backend SDK Manager</title>
|
||
<style>
|
||
@import url("https://fonts.googleapis.com/css2?family=Vazirmatn:wght@300;400;500;600;700;800&display=swap");
|
||
@import url("https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500;600&display=swap");
|
||
:root {
|
||
--primary: #1a365d;
|
||
--primary-light: #2c5282;
|
||
--primary-dark: #0f2341;
|
||
--accent: #c9a961;
|
||
--accent-dark: #a8893f;
|
||
--accent-light: #e0c789;
|
||
--bg: #f5f7fa;
|
||
--board-bg: #e2e8f0;
|
||
--card-bg: #ffffff;
|
||
--column-bg: #edf2f7;
|
||
--panel-bg: #ffffff;
|
||
--text: #1a202c;
|
||
--text-muted: #4a5568;
|
||
--text-light: #718096;
|
||
--border: #cbd5e0;
|
||
--border-light: #e2e8f0;
|
||
--success: #38a169;
|
||
--danger: #e53e3e;
|
||
--warning: #dd6b20;
|
||
--info: #3182ce;
|
||
--shadow:
|
||
0 4px 6px rgba(0, 0, 0, 0.08), 0 10px 20px rgba(26, 54, 93, 0.1);
|
||
--shadow-sm: 0 2px 4px rgba(0, 0, 0, 0.06);
|
||
--shadow-lg: 0 10px 30px rgba(0, 0, 0, 0.15);
|
||
--radius: 10px;
|
||
--radius-sm: 6px;
|
||
--sidebar-width: 300px;
|
||
--header-height: 64px;
|
||
--footer-height: 36px;
|
||
}
|
||
[data-theme="dark"] {
|
||
--primary: #2c5282;
|
||
--primary-light: #3b6fb5;
|
||
--primary-dark: #1a365d;
|
||
--accent: #e0c789;
|
||
--accent-dark: #c9a961;
|
||
--accent-light: #f0d9a0;
|
||
--bg: #1a202c;
|
||
--board-bg: #2d3748;
|
||
--card-bg: #2d3748;
|
||
--column-bg: #374151;
|
||
--panel-bg: #1f2937;
|
||
--text: #e2e8f0;
|
||
--text-muted: #cbd5e0;
|
||
--text-light: #a0aec0;
|
||
--border: #4a5568;
|
||
--border-light: #374151;
|
||
}
|
||
* {
|
||
box-sizing: border-box;
|
||
margin: 0;
|
||
padding: 0;
|
||
}
|
||
body {
|
||
font-family: "Vazirmatn", Tahoma, sans-serif;
|
||
background: var(--bg);
|
||
color: var(--text);
|
||
height: 100vh;
|
||
overflow: hidden;
|
||
font-size: 14px;
|
||
display: flex;
|
||
flex-direction: column;
|
||
transition:
|
||
background 0.3s,
|
||
color 0.3s;
|
||
}
|
||
.app-header {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary) 0%,
|
||
var(--primary-light) 100%
|
||
);
|
||
color: white;
|
||
padding: 0 20px;
|
||
height: var(--header-height);
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
box-shadow: var(--shadow);
|
||
z-index: 100;
|
||
flex-shrink: 0;
|
||
}
|
||
.app-brand {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 14px;
|
||
}
|
||
.app-logo {
|
||
width: 44px;
|
||
height: 44px;
|
||
background: var(--accent);
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 22px;
|
||
font-weight: 800;
|
||
color: var(--primary-dark);
|
||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.25);
|
||
flex-shrink: 0;
|
||
}
|
||
.app-brand-text {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 2px;
|
||
}
|
||
.app-title {
|
||
font-size: 16px;
|
||
font-weight: 800;
|
||
color: white;
|
||
}
|
||
.app-subtitle {
|
||
font-size: 11px;
|
||
opacity: 0.85;
|
||
color: rgba(255, 255, 255, 0.9);
|
||
}
|
||
.header-actions {
|
||
display: flex;
|
||
gap: 10px;
|
||
align-items: center;
|
||
}
|
||
.btn {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary-light),
|
||
var(--primary)
|
||
);
|
||
color: white;
|
||
border: none;
|
||
padding: 8px 14px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
transition: all 0.2s;
|
||
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.15);
|
||
white-space: nowrap;
|
||
}
|
||
.btn:hover {
|
||
transform: translateY(-1px);
|
||
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
|
||
filter: brightness(1.1);
|
||
}
|
||
.btn:active {
|
||
transform: translateY(0);
|
||
}
|
||
.btn:disabled {
|
||
opacity: 0.5;
|
||
cursor: not-allowed;
|
||
}
|
||
.btn-accent {
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
font-weight: 700;
|
||
}
|
||
.btn-ghost {
|
||
background: rgba(255, 255, 255, 0.1);
|
||
border: 1px solid rgba(255, 255, 255, 0.25);
|
||
color: white;
|
||
font-weight: 600;
|
||
}
|
||
.btn-ghost:hover {
|
||
background: rgba(255, 255, 255, 0.2);
|
||
}
|
||
.btn-success {
|
||
background: linear-gradient(135deg, #48bb78, var(--success));
|
||
}
|
||
.btn-danger {
|
||
background: linear-gradient(135deg, #f56565, var(--danger));
|
||
}
|
||
.btn-warning {
|
||
background: linear-gradient(135deg, #f6ad55, var(--warning));
|
||
color: white;
|
||
}
|
||
.btn-info {
|
||
background: linear-gradient(135deg, #63b3ed, var(--info));
|
||
}
|
||
.btn-sm {
|
||
padding: 6px 10px;
|
||
font-size: 12px;
|
||
}
|
||
.btn-xs {
|
||
padding: 4px 8px;
|
||
font-size: 11px;
|
||
}
|
||
.app-main {
|
||
flex: 1;
|
||
display: flex;
|
||
overflow: hidden;
|
||
flex-direction: row;
|
||
}
|
||
.sidebar {
|
||
order: -1;
|
||
width: var(--sidebar-width);
|
||
background: var(--panel-bg);
|
||
border-right: 1px solid var(--border);
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: var(--shadow);
|
||
flex-shrink: 0;
|
||
z-index: 50;
|
||
}
|
||
.sidebar-header {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
padding: 12px;
|
||
border-bottom: 2px solid var(--accent);
|
||
min-height: 48px;
|
||
display: flex;
|
||
align-items: center;
|
||
}
|
||
.sidebar-title {
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
}
|
||
.sidebar-body {
|
||
flex: 1;
|
||
overflow-y: auto;
|
||
padding: 8px;
|
||
}
|
||
.search-input-wrapper {
|
||
position: relative;
|
||
margin-bottom: 8px;
|
||
}
|
||
.search-input {
|
||
width: 100%;
|
||
padding: 8px 12px 8px 32px;
|
||
border: 1px solid var(--border);
|
||
border-radius: var(--radius-sm);
|
||
font-family: inherit;
|
||
font-size: 12px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
}
|
||
.search-input:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
box-shadow: 0 0 0 3px rgba(201, 169, 97, 0.15);
|
||
}
|
||
.search-icon {
|
||
position: absolute;
|
||
left: 10px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
font-size: 14px;
|
||
opacity: 0.5;
|
||
pointer-events: none;
|
||
}
|
||
.search-clear {
|
||
position: absolute;
|
||
right: 8px;
|
||
top: 50%;
|
||
transform: translateY(-50%);
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
cursor: pointer;
|
||
font-size: 14px;
|
||
display: none;
|
||
}
|
||
.search-clear.visible {
|
||
display: block;
|
||
}
|
||
.controller-item {
|
||
background: var(--card-bg);
|
||
border: 1px solid var(--border-light);
|
||
color: var(--text);
|
||
padding: 10px 12px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 500;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
transition: all 0.2s;
|
||
width: 100%;
|
||
margin-bottom: 4px;
|
||
}
|
||
.controller-item:hover {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
transform: translateX(-2px);
|
||
}
|
||
.controller-item.active {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
border-color: var(--accent);
|
||
}
|
||
.controller-item .ctrl-icon {
|
||
font-size: 18px;
|
||
flex-shrink: 0;
|
||
}
|
||
.controller-item .ctrl-name {
|
||
flex: 1;
|
||
font-weight: 600;
|
||
}
|
||
.controller-item .ctrl-badge {
|
||
font-size: 10px;
|
||
background: rgba(201, 169, 97, 0.2);
|
||
color: var(--accent-dark);
|
||
padding: 2px 7px;
|
||
border-radius: 10px;
|
||
font-weight: 700;
|
||
}
|
||
.controller-item.active .ctrl-badge {
|
||
background: rgba(255, 255, 255, 0.25);
|
||
color: white;
|
||
}
|
||
.board-area {
|
||
flex: 1;
|
||
overflow: auto;
|
||
padding: 20px;
|
||
background: var(--board-bg);
|
||
}
|
||
.upload-zone {
|
||
background: var(--card-bg);
|
||
border: 3px dashed var(--border);
|
||
border-radius: var(--radius);
|
||
padding: 60px 40px;
|
||
text-align: center;
|
||
cursor: pointer;
|
||
max-width: 700px;
|
||
margin: 40px auto;
|
||
}
|
||
.upload-zone:hover,
|
||
.upload-zone.dragover {
|
||
border-color: var(--accent);
|
||
transform: translateY(-2px);
|
||
}
|
||
.upload-zone-icon {
|
||
font-size: 70px;
|
||
margin-bottom: 20px;
|
||
opacity: 0.7;
|
||
}
|
||
.upload-zone h2 {
|
||
color: var(--primary);
|
||
font-size: 22px;
|
||
margin-bottom: 10px;
|
||
}
|
||
[data-theme="dark"] .upload-zone h2 {
|
||
color: var(--accent);
|
||
}
|
||
.upload-zone p {
|
||
color: var(--text-muted);
|
||
margin-bottom: 20px;
|
||
}
|
||
.controller-tabs {
|
||
display: flex;
|
||
gap: 4px;
|
||
background: var(--card-bg);
|
||
padding: 6px;
|
||
border-radius: var(--radius);
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
flex-wrap: wrap;
|
||
}
|
||
.controller-tab {
|
||
background: transparent;
|
||
border: none;
|
||
color: var(--text-muted);
|
||
padding: 10px 16px;
|
||
border-radius: var(--radius-sm);
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
}
|
||
.controller-tab:hover {
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
}
|
||
.controller-tab.active {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
}
|
||
.content-section {
|
||
background: var(--card-bg);
|
||
border-radius: var(--radius);
|
||
padding: 24px;
|
||
margin-bottom: 20px;
|
||
box-shadow: var(--shadow-sm);
|
||
}
|
||
.section-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 12px;
|
||
padding-bottom: 14px;
|
||
border-bottom: 2px solid var(--border-light);
|
||
margin-bottom: 18px;
|
||
}
|
||
.section-icon {
|
||
width: 44px;
|
||
height: 44px;
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
border-radius: 10px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 20px;
|
||
flex-shrink: 0;
|
||
box-shadow: 0 4px 10px rgba(26, 54, 93, 0.2);
|
||
}
|
||
.section-title {
|
||
flex: 1;
|
||
}
|
||
.section-title h3 {
|
||
font-size: 17px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
}
|
||
[data-theme="dark"] .section-title h3 {
|
||
color: var(--accent);
|
||
}
|
||
.section-title .subtitle {
|
||
font-size: 12px;
|
||
color: var(--text-muted);
|
||
}
|
||
.models-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
|
||
gap: 12px;
|
||
}
|
||
.model-card {
|
||
background: var(--column-bg);
|
||
border: 2px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
cursor: pointer;
|
||
transition: all 0.2s;
|
||
}
|
||
.model-card:hover {
|
||
border-color: var(--accent);
|
||
transform: translateY(-2px);
|
||
}
|
||
.model-card-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
margin-bottom: 8px;
|
||
}
|
||
.model-card-icon {
|
||
width: 32px;
|
||
height: 32px;
|
||
background: linear-gradient(135deg, var(--accent), var(--accent-dark));
|
||
color: var(--primary-dark);
|
||
border-radius: 8px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: center;
|
||
font-size: 14px;
|
||
font-weight: 800;
|
||
flex-shrink: 0;
|
||
}
|
||
.model-card-name {
|
||
font-size: 14px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
flex: 1;
|
||
overflow: hidden;
|
||
text-overflow: ellipsis;
|
||
white-space: nowrap;
|
||
}
|
||
[data-theme="dark"] .model-card-name {
|
||
color: var(--accent);
|
||
}
|
||
.model-card-meta {
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
display: flex;
|
||
gap: 10px;
|
||
margin-top: 6px;
|
||
}
|
||
.endpoints-table {
|
||
width: 100%;
|
||
border-collapse: collapse;
|
||
background: var(--card-bg);
|
||
border-radius: 8px;
|
||
overflow: hidden;
|
||
}
|
||
.endpoints-table thead {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
}
|
||
.endpoints-table th {
|
||
padding: 12px 14px;
|
||
text-align: right;
|
||
font-weight: 600;
|
||
font-size: 12px;
|
||
}
|
||
.endpoints-table td {
|
||
padding: 11px 14px;
|
||
border-bottom: 1px solid var(--border-light);
|
||
font-size: 12px;
|
||
}
|
||
.endpoints-table tbody tr:nth-child(even) {
|
||
background: var(--column-bg);
|
||
}
|
||
.method-badge {
|
||
display: inline-block;
|
||
padding: 3px 10px;
|
||
border-radius: 4px;
|
||
font-size: 10px;
|
||
font-weight: 800;
|
||
color: white;
|
||
font-family: "Fira Code", monospace;
|
||
}
|
||
.method-get {
|
||
background: var(--info);
|
||
}
|
||
.method-post {
|
||
background: var(--success);
|
||
}
|
||
.method-put {
|
||
background: var(--warning);
|
||
}
|
||
.method-delete {
|
||
background: var(--danger);
|
||
}
|
||
.method-patch {
|
||
background: #805ad5;
|
||
}
|
||
.endpoint-path {
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
.test-btn {
|
||
background: linear-gradient(135deg, var(--success), #2f855a);
|
||
color: white;
|
||
border: none;
|
||
padding: 5px 10px;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 4px;
|
||
}
|
||
.test-btn:hover {
|
||
transform: translateY(-1px);
|
||
box-shadow: 0 2px 6px rgba(56, 161, 105, 0.4);
|
||
}
|
||
.modal-overlay {
|
||
position: fixed;
|
||
inset: 0;
|
||
background: rgba(26, 54, 93, 0.6);
|
||
backdrop-filter: blur(3px);
|
||
display: none;
|
||
align-items: center;
|
||
justify-content: center;
|
||
z-index: 1000;
|
||
padding: 20px;
|
||
}
|
||
.modal-overlay.active {
|
||
display: flex;
|
||
}
|
||
.modal {
|
||
background: var(--panel-bg);
|
||
color: var(--text);
|
||
border-radius: 12px;
|
||
width: 100%;
|
||
max-width: 1100px;
|
||
max-height: 90vh;
|
||
overflow: hidden;
|
||
display: flex;
|
||
flex-direction: column;
|
||
box-shadow: var(--shadow-lg);
|
||
}
|
||
.modal-header {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
padding: 16px 20px;
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
border-bottom: 3px solid var(--accent);
|
||
}
|
||
.modal-title {
|
||
font-size: 16px;
|
||
font-weight: 700;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
}
|
||
.modal-close {
|
||
background: rgba(255, 255, 255, 0.15);
|
||
border: none;
|
||
color: white;
|
||
width: 30px;
|
||
height: 30px;
|
||
border-radius: 50%;
|
||
cursor: pointer;
|
||
font-size: 16px;
|
||
}
|
||
.modal-close:hover {
|
||
background: var(--danger);
|
||
}
|
||
.modal-body {
|
||
padding: 20px;
|
||
overflow-y: auto;
|
||
flex: 1;
|
||
}
|
||
.modal-footer {
|
||
padding: 14px 20px;
|
||
border-top: 1px solid var(--border);
|
||
display: flex;
|
||
gap: 8px;
|
||
background: var(--border-light);
|
||
}
|
||
.code-block {
|
||
background: #1e1e1e;
|
||
color: #d4d4d4;
|
||
border-radius: 8px;
|
||
padding: 16px;
|
||
font-family: "Fira Code", "Courier New", monospace;
|
||
font-size: 12px;
|
||
line-height: 1.7;
|
||
overflow-x: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
max-height: 600px;
|
||
overflow-y: auto;
|
||
white-space: pre;
|
||
}
|
||
.code-block-header {
|
||
display: flex;
|
||
justify-content: space-between;
|
||
background: #2d2d2d;
|
||
padding: 8px 14px;
|
||
border-radius: 8px 8px 0 0;
|
||
color: #d4d4d4;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
}
|
||
.code-keyword {
|
||
color: #569cd6;
|
||
}
|
||
.code-type {
|
||
color: #4ec9b0;
|
||
}
|
||
.code-string {
|
||
color: #ce9178;
|
||
}
|
||
.code-comment {
|
||
color: #6a9955;
|
||
font-style: italic;
|
||
}
|
||
.code-number {
|
||
color: #b5cea8;
|
||
}
|
||
.toast-container {
|
||
position: fixed;
|
||
bottom: 20px;
|
||
left: 20px;
|
||
z-index: 2000;
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 8px;
|
||
}
|
||
.toast {
|
||
background: var(--primary);
|
||
color: white;
|
||
padding: 12px 18px;
|
||
border-radius: 8px;
|
||
box-shadow: var(--shadow-lg);
|
||
font-size: 13px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
animation: slideInLeft 0.3s;
|
||
min-width: 250px;
|
||
}
|
||
.toast.success {
|
||
background: var(--success);
|
||
}
|
||
.toast.error {
|
||
background: var(--danger);
|
||
}
|
||
.toast.warning {
|
||
background: var(--warning);
|
||
}
|
||
@keyframes slideInLeft {
|
||
from {
|
||
opacity: 0;
|
||
transform: translateX(-30px);
|
||
}
|
||
to {
|
||
opacity: 1;
|
||
transform: translateX(0);
|
||
}
|
||
}
|
||
.stats-grid {
|
||
display: grid;
|
||
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
|
||
gap: 14px;
|
||
margin-bottom: 20px;
|
||
}
|
||
.stat-card {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
padding: 18px;
|
||
border-radius: var(--radius);
|
||
text-align: center;
|
||
}
|
||
.stat-card .stat-value {
|
||
font-size: 28px;
|
||
font-weight: 800;
|
||
color: var(--accent);
|
||
}
|
||
.stat-card .stat-label {
|
||
font-size: 12px;
|
||
opacity: 0.9;
|
||
}
|
||
.app-footer {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary),
|
||
var(--primary-light)
|
||
);
|
||
color: white;
|
||
padding: 8px 20px;
|
||
font-size: 11px;
|
||
display: flex;
|
||
justify-content: space-between;
|
||
border-top: 2px solid var(--accent);
|
||
flex-shrink: 0;
|
||
}
|
||
.footer-brand {
|
||
color: var(--accent);
|
||
font-weight: 700;
|
||
}
|
||
.global-settings-panel {
|
||
background: linear-gradient(
|
||
135deg,
|
||
var(--primary-dark),
|
||
var(--primary)
|
||
);
|
||
color: white;
|
||
padding: 10px 20px;
|
||
border-bottom: 2px solid var(--accent);
|
||
display: flex;
|
||
flex-wrap: wrap;
|
||
gap: 10px;
|
||
align-items: center;
|
||
font-size: 12px;
|
||
}
|
||
.global-setting-item {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
background: rgba(255, 255, 255, 0.08);
|
||
padding: 5px 10px;
|
||
border-radius: 6px;
|
||
border: 1px solid rgba(255, 255, 255, 0.15);
|
||
}
|
||
.global-setting-item label {
|
||
font-weight: 600;
|
||
color: var(--accent-light);
|
||
font-size: 11px;
|
||
white-space: nowrap;
|
||
}
|
||
.global-setting-item input {
|
||
background: rgba(255, 255, 255, 0.1);
|
||
border: 1px solid rgba(255, 255, 255, 0.2);
|
||
color: white;
|
||
padding: 4px 8px;
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
width: 180px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
.global-setting-item input:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
}
|
||
.global-setting-item input.short {
|
||
width: 80px;
|
||
}
|
||
.global-setting-item input.medium {
|
||
width: 280px;
|
||
}
|
||
.auth-status {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
padding: 5px 12px;
|
||
border-radius: 6px;
|
||
font-size: 11px;
|
||
font-weight: 700;
|
||
}
|
||
.auth-status.authenticated {
|
||
background: rgba(56, 161, 105, 0.2);
|
||
color: #9ae6b4;
|
||
border: 1px solid rgba(56, 161, 105, 0.4);
|
||
}
|
||
.auth-status.unauthenticated {
|
||
background: rgba(229, 62, 62, 0.2);
|
||
color: #feb2b2;
|
||
border: 1px solid rgba(229, 62, 62, 0.4);
|
||
}
|
||
.auth-status-dot {
|
||
width: 8px;
|
||
height: 8px;
|
||
border-radius: 50%;
|
||
background: currentColor;
|
||
animation: pulse 2s infinite;
|
||
}
|
||
@keyframes pulse {
|
||
0%,
|
||
100% {
|
||
opacity: 1;
|
||
}
|
||
50% {
|
||
opacity: 0.4;
|
||
}
|
||
}
|
||
.test-form {
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 16px;
|
||
margin-bottom: 16px;
|
||
}
|
||
.test-form-section {
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
}
|
||
.test-form-section.full-width {
|
||
grid-column: 1 / -1;
|
||
}
|
||
.test-form-section-title {
|
||
font-size: 12px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 10px;
|
||
padding-bottom: 8px;
|
||
border-bottom: 1px solid var(--border-light);
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
}
|
||
[data-theme="dark"] .test-form-section-title {
|
||
color: var(--accent);
|
||
}
|
||
.test-field {
|
||
margin-bottom: 10px;
|
||
}
|
||
.test-field:last-child {
|
||
margin-bottom: 0;
|
||
}
|
||
.test-field label {
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
.test-field label .required {
|
||
color: var(--danger);
|
||
}
|
||
.test-field input,
|
||
.test-field textarea,
|
||
.test-field select {
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
}
|
||
.test-field textarea {
|
||
min-height: 100px;
|
||
resize: vertical;
|
||
line-height: 1.5;
|
||
}
|
||
.test-field input:focus,
|
||
.test-field textarea:focus {
|
||
outline: none;
|
||
border-color: var(--accent);
|
||
}
|
||
.test-actions {
|
||
display: flex;
|
||
gap: 8px;
|
||
margin-bottom: 16px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.response-panel {
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 14px;
|
||
margin-top: 16px;
|
||
}
|
||
.response-header {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 10px;
|
||
margin-bottom: 12px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.response-status {
|
||
padding: 4px 12px;
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 12px;
|
||
font-weight: 700;
|
||
color: white;
|
||
}
|
||
.response-status.success {
|
||
background: var(--success);
|
||
}
|
||
.response-status.error {
|
||
background: var(--danger);
|
||
}
|
||
.response-status.redirect {
|
||
background: var(--warning);
|
||
}
|
||
.response-status.info {
|
||
background: var(--info);
|
||
}
|
||
.response-time,
|
||
.response-size {
|
||
font-size: 11px;
|
||
color: var(--text-muted);
|
||
font-family: "Fira Code", monospace;
|
||
}
|
||
.response-tabs {
|
||
display: flex;
|
||
gap: 4px;
|
||
margin-bottom: 10px;
|
||
flex-wrap: wrap;
|
||
}
|
||
.response-tab {
|
||
background: transparent;
|
||
border: 1px solid var(--border);
|
||
color: var(--text-muted);
|
||
padding: 5px 12px;
|
||
border-radius: 4px;
|
||
cursor: pointer;
|
||
font-family: inherit;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
}
|
||
.response-tab.active {
|
||
background: var(--primary);
|
||
color: white;
|
||
border-color: var(--primary);
|
||
}
|
||
.response-body {
|
||
background: #1e1e1e;
|
||
color: #d4d4d4;
|
||
padding: 14px;
|
||
border-radius: 6px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
line-height: 1.6;
|
||
max-height: 400px;
|
||
overflow: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
white-space: pre-wrap;
|
||
word-break: break-word;
|
||
}
|
||
.json-key {
|
||
color: #9cdcfe;
|
||
}
|
||
.json-string {
|
||
color: #ce9178;
|
||
}
|
||
.json-number {
|
||
color: #b5cea8;
|
||
}
|
||
.json-boolean {
|
||
color: #569cd6;
|
||
}
|
||
.json-null {
|
||
color: #569cd6;
|
||
}
|
||
.debug-log {
|
||
background: #0d1117;
|
||
color: #c9d1d9;
|
||
border-radius: 6px;
|
||
padding: 12px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 10px;
|
||
line-height: 1.6;
|
||
max-height: 200px;
|
||
overflow: auto;
|
||
direction: ltr;
|
||
text-align: left;
|
||
margin-top: 10px;
|
||
white-space: pre-wrap;
|
||
word-break: break-all;
|
||
}
|
||
.debug-log .log-request {
|
||
color: #79c0ff;
|
||
}
|
||
.debug-log .log-response {
|
||
color: #7ee787;
|
||
}
|
||
.debug-log .log-error {
|
||
color: #ff7b72;
|
||
}
|
||
.debug-log .log-info {
|
||
color: #d2a8ff;
|
||
}
|
||
.cors-info-box {
|
||
background: linear-gradient(to left, #fffaf0, #fef5e7);
|
||
border: 1px solid #f6e05e;
|
||
border-right: 4px solid var(--warning);
|
||
padding: 14px 18px;
|
||
border-radius: 8px;
|
||
margin-bottom: 16px;
|
||
font-size: 12px;
|
||
color: var(--text);
|
||
}
|
||
[data-theme="dark"] .cors-info-box {
|
||
background: rgba(221, 107, 32, 0.1);
|
||
border-color: rgba(221, 107, 32, 0.3);
|
||
}
|
||
.cors-info-box strong {
|
||
color: var(--warning);
|
||
}
|
||
.cors-info-box code {
|
||
background: rgba(0, 0, 0, 0.08);
|
||
padding: 2px 6px;
|
||
border-radius: 3px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
display: inline-block;
|
||
}
|
||
.hidden-input {
|
||
display: none;
|
||
}
|
||
.empty-state {
|
||
text-align: center;
|
||
padding: 40px 20px;
|
||
color: var(--text-muted);
|
||
}
|
||
.empty-state-icon {
|
||
font-size: 60px;
|
||
opacity: 0.3;
|
||
margin-bottom: 14px;
|
||
}
|
||
@media (max-width: 768px) {
|
||
.sidebar {
|
||
position: absolute;
|
||
height: 100%;
|
||
z-index: 200;
|
||
}
|
||
.models-grid {
|
||
grid-template-columns: 1fr;
|
||
}
|
||
.stats-grid {
|
||
grid-template-columns: 1fr 1fr;
|
||
}
|
||
.test-form {
|
||
grid-template-columns: 1fr;
|
||
}
|
||
.global-settings-panel {
|
||
flex-direction: column;
|
||
align-items: stretch;
|
||
}
|
||
.global-setting-item input {
|
||
width: 100%;
|
||
}
|
||
}
|
||
</style>
|
||
</head>
|
||
<body>
|
||
<header class="app-header">
|
||
<div class="app-brand">
|
||
<div class="app-logo">⚡</div>
|
||
<div class="app-brand-text">
|
||
<div class="app-title">XFramework Backend SDK Manager</div>
|
||
<div class="app-subtitle">تولید سرویس های فراخوانی سرویس دهنده</div>
|
||
</div>
|
||
</div>
|
||
<div class="header-actions">
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost btn-sm"
|
||
id="themeToggle"
|
||
title="تغییر تم"
|
||
>
|
||
<span id="themeIcon">☀️</span>
|
||
</button>
|
||
<button type="button" class="btn btn-accent btn-sm" id="loadFileBtn">
|
||
<span>📂</span><span>بارگذاری Swagger</span>
|
||
</button>
|
||
</div>
|
||
</header>
|
||
<div class="global-settings-panel" id="globalSettingsPanel">
|
||
<div class="global-setting-item">
|
||
<label>🌐 Base URL:</label>
|
||
<input type="text" id="gBaseUrl" value="https://localhost:5001" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>🔀 CORS Proxy:</label>
|
||
<input
|
||
type="text"
|
||
id="gCorsProxy"
|
||
class="medium"
|
||
placeholder="مثال: https://corsproxy.io/?"
|
||
/>
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>⚡ X-PoweredBy:</label>
|
||
<input type="text" id="gXPoweredBy" value="SaherElmITCenter" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>🗝️ X-Api-Key:</label>
|
||
<input type="text" id="gXApiKey" />
|
||
</div>
|
||
<div class="global-setting-item">
|
||
<label>📌 Version:</label>
|
||
<input type="text" id="gVersion" class="short" value="1.0" />
|
||
</div>
|
||
<div class="global-setting-item" id="authStatusContainer">
|
||
<div class="auth-status unauthenticated" id="authStatus">
|
||
<span class="auth-status-dot"></span>
|
||
<span>غیرفعال</span>
|
||
</div>
|
||
</div>
|
||
<button type="button" class="btn btn-info btn-sm" id="openAuthBtn">
|
||
<span>🔐</span><span>احراز هویت</span>
|
||
</button>
|
||
</div>
|
||
<div class="app-main">
|
||
<aside class="sidebar" id="sidebar">
|
||
<div class="sidebar-header">
|
||
<div class="sidebar-title">🎛️ کنترلرها</div>
|
||
</div>
|
||
<div class="sidebar-body" id="controllersList">
|
||
<div class="empty-state">
|
||
<div class="empty-state-icon">📭</div>
|
||
<p>ابتدا فایل Swagger را بارگذاری کنید</p>
|
||
</div>
|
||
</div>
|
||
</aside>
|
||
<main class="board-area" id="boardArea">
|
||
<div id="uploadZone" class="upload-zone">
|
||
<div class="upload-zone-icon">📄</div>
|
||
<h2>فایل Swagger JSON را بارگذاری کنید</h2>
|
||
<p>فایل را اینجا بکشید و رها کنید یا روی این ناحیه کلیک کنید</p>
|
||
<button type="button" class="btn btn-accent">
|
||
<span>📁</span><span>انتخاب فایل</span>
|
||
</button>
|
||
</div>
|
||
<div id="loadedContent" style="display: none">
|
||
<div class="stats-grid" id="statsGrid"></div>
|
||
<div class="controller-tabs" id="controllerTabs"></div>
|
||
<div id="controllerContent"></div>
|
||
</div>
|
||
</main>
|
||
</div>
|
||
<footer class="app-footer">
|
||
<div>
|
||
<span class="footer-brand">طراح و توسعهدهنده:</span> هادی خزاعی اصل
|
||
<span style="margin: 0 10px">|</span>
|
||
<span class="footer-brand">شرکت:</span> فن آوران ساحر علم
|
||
</div>
|
||
<div><span class="footer-brand">نسخه:</span> 1.6.0</div>
|
||
</footer>
|
||
<!-- Model Modal -->
|
||
<div class="modal-overlay" id="modelModal">
|
||
<div class="modal">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>📦</span><span id="modelModalTitle">جزئیات مدل</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-modal>✕</button>
|
||
</div>
|
||
<div class="modal-body" id="modelModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-success" id="downloadDtoBtn">
|
||
<span>💾</span><span>دانلود DTO</span>
|
||
</button>
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost"
|
||
style="
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
border: 1px solid var(--border);
|
||
"
|
||
id="copyCodeBtn"
|
||
>
|
||
<span>📋</span><span>کپی</span>
|
||
</button>
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost"
|
||
style="
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
border: 1px solid var(--border);
|
||
"
|
||
data-close-modal
|
||
>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- Provider Modal -->
|
||
<div class="modal-overlay" id="providerModal">
|
||
<div class="modal" style="max-width: 1200px">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>🔌</span><span id="providerModalTitle">Service</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-provider>
|
||
✕
|
||
</button>
|
||
</div>
|
||
<div class="modal-body" id="providerModalBody"></div>
|
||
<div class="modal-footer">
|
||
<button
|
||
type="button"
|
||
class="btn btn-success"
|
||
id="downloadProviderBtn"
|
||
>
|
||
<span>💾</span><span>دانلود</span>
|
||
</button>
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost"
|
||
style="
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
border: 1px solid var(--border);
|
||
"
|
||
id="copyProviderCodeBtn"
|
||
>
|
||
<span>📋</span><span>کپی</span>
|
||
</button>
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost"
|
||
style="
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
border: 1px solid var(--border);
|
||
"
|
||
data-close-provider
|
||
>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<!-- Auth Modal -->
|
||
<div class="modal-overlay" id="authModal">
|
||
<div class="modal" style="max-width: 700px">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span>🔐</span><span>احراز هویت - /Account/Authenticate</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-auth>✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
<div
|
||
style="
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 16px;
|
||
margin-bottom: 16px;
|
||
"
|
||
>
|
||
<div
|
||
style="
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
"
|
||
>
|
||
<span>🔑</span><span>ورود از طریق /Account/Authenticate</span>
|
||
</div>
|
||
<div
|
||
style="
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 12px;
|
||
margin-bottom: 12px;
|
||
"
|
||
>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>userSelectBy (Username/Email/Mobile)</label
|
||
>
|
||
<input
|
||
type="text"
|
||
id="loginUserSelectBy"
|
||
placeholder="username or email"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>password</label
|
||
>
|
||
<input
|
||
type="password"
|
||
id="loginPassword"
|
||
placeholder="password"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 12px;
|
||
margin-bottom: 12px;
|
||
"
|
||
>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>language</label
|
||
>
|
||
<input
|
||
type="text"
|
||
id="loginLanguage"
|
||
value="fa-IR"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
<div style="display: flex; align-items: flex-end">
|
||
<button
|
||
type="button"
|
||
class="btn btn-success"
|
||
id="doLoginBtn"
|
||
style="width: 100%"
|
||
>
|
||
<span>🚀</span><span>ورود به سیستم</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 16px;
|
||
margin-bottom: 16px;
|
||
"
|
||
>
|
||
<div
|
||
style="
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
"
|
||
>
|
||
<span>📝</span><span>ثبت دستی توکنها</span>
|
||
</div>
|
||
<div
|
||
style="
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 12px;
|
||
margin-bottom: 12px;
|
||
"
|
||
>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>accessToken</label
|
||
>
|
||
<input
|
||
type="text"
|
||
id="manualAccessToken"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>refreshToken</label
|
||
>
|
||
<input
|
||
type="text"
|
||
id="manualRefreshToken"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="
|
||
display: grid;
|
||
grid-template-columns: 1fr 1fr;
|
||
gap: 12px;
|
||
margin-bottom: 12px;
|
||
"
|
||
>
|
||
<div>
|
||
<label
|
||
style="
|
||
display: block;
|
||
font-size: 11px;
|
||
font-weight: 600;
|
||
color: var(--text-muted);
|
||
margin-bottom: 4px;
|
||
"
|
||
>expiresAt (Unix Timestamp)</label
|
||
>
|
||
<input
|
||
type="number"
|
||
id="manualExpiresAt"
|
||
style="
|
||
width: 100%;
|
||
padding: 7px 10px;
|
||
border: 1px solid var(--border);
|
||
border-radius: 4px;
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
background: var(--card-bg);
|
||
color: var(--text);
|
||
direction: ltr;
|
||
text-align: left;
|
||
"
|
||
/>
|
||
</div>
|
||
<div style="display: flex; align-items: flex-end">
|
||
<button
|
||
type="button"
|
||
class="btn btn-info"
|
||
id="saveManualTokenBtn"
|
||
style="width: 100%"
|
||
>
|
||
<span>💾</span><span>ذخیره دستی</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<div
|
||
style="
|
||
background: var(--column-bg);
|
||
border: 1px solid var(--border-light);
|
||
border-radius: var(--radius-sm);
|
||
padding: 16px;
|
||
margin-bottom: 16px;
|
||
"
|
||
>
|
||
<div
|
||
style="
|
||
font-size: 13px;
|
||
font-weight: 700;
|
||
color: var(--primary);
|
||
margin-bottom: 12px;
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 8px;
|
||
"
|
||
>
|
||
<span>📊</span><span>وضعیت فعلی</span>
|
||
</div>
|
||
<div
|
||
id="currentTokenInfo"
|
||
style="
|
||
font-family: "Fira Code", monospace;
|
||
font-size: 11px;
|
||
direction: ltr;
|
||
text-align: left;
|
||
color: var(--text-muted);
|
||
"
|
||
></div>
|
||
<button
|
||
type="button"
|
||
class="btn btn-danger btn-sm"
|
||
id="clearTokenBtn"
|
||
style="margin-top: 10px"
|
||
>
|
||
<span>🗑️</span><span>پاک کردن توکنها</span>
|
||
</button>
|
||
</div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button
|
||
type="button"
|
||
class="btn btn-ghost"
|
||
style="
|
||
background: var(--column-bg);
|
||
color: var(--text);
|
||
border: 1px solid var(--border);
|
||
"
|
||
data-close-auth
|
||
>
|
||
بستن
|
||
</button>
|
||
</div>
|
||
</div>
|
||
</div>
|
||
<input
|
||
type="file"
|
||
id="fileInput"
|
||
class="hidden-input"
|
||
accept=".json,application/json"
|
||
/>
|
||
<div class="toast-container" id="toastContainer"></div>
|
||
<script>
|
||
/* =========================================================================
|
||
Global State
|
||
========================================================================= */
|
||
const AppState = {
|
||
swagger: null,
|
||
controllers: {},
|
||
allSchemas: {},
|
||
activeController: null,
|
||
selectedModel: null,
|
||
generatedCode: "",
|
||
generatedProviderCode: "",
|
||
generatedProviderFilename: "",
|
||
searchTerms: { controllers: "", models: "", endpoints: "" },
|
||
};
|
||
|
||
const GlobalSettings = {
|
||
baseUrl: "https://localhost:5001",
|
||
corsProxy: "",
|
||
xPoweredBy: "SaherElmITCenter",
|
||
xApiKey: "",
|
||
version: "1.0",
|
||
accessToken: "",
|
||
refreshToken: "",
|
||
expiresAt: 0,
|
||
load() {
|
||
try {
|
||
const saved = localStorage.getItem("xfw-sdk-settings-v2");
|
||
if (saved) Object.assign(this, JSON.parse(saved));
|
||
} catch (e) {}
|
||
},
|
||
save() {
|
||
try {
|
||
localStorage.setItem(
|
||
"xfw-sdk-settings-v2",
|
||
JSON.stringify({
|
||
baseUrl: this.baseUrl,
|
||
corsProxy: this.corsProxy,
|
||
xPoweredBy: this.xPoweredBy,
|
||
xApiKey: this.xApiKey,
|
||
version: this.version,
|
||
accessToken: this.accessToken,
|
||
refreshToken: this.refreshToken,
|
||
expiresAt: this.expiresAt,
|
||
}),
|
||
);
|
||
} catch (e) {}
|
||
},
|
||
isAuthenticated() {
|
||
return !!this.accessToken;
|
||
},
|
||
isTokenExpired() {
|
||
if (!this.expiresAt) return false;
|
||
return Math.floor(Date.now() / 1000) >= this.expiresAt;
|
||
},
|
||
buildHeaders(extraHeaders = {}) {
|
||
const headers = {
|
||
Accept: "application/json",
|
||
"X-PoweredBy": this.xPoweredBy || "SaherElmITCenter",
|
||
};
|
||
if (this.xApiKey) headers["X-Api-Key"] = this.xApiKey;
|
||
if (this.isAuthenticated()) {
|
||
headers["Authorization"] = `Bearer ${this.accessToken}`;
|
||
headers["refresh_token"] = this.refreshToken;
|
||
headers["expires_at"] = String(this.expiresAt);
|
||
}
|
||
return { ...headers, ...extraHeaders };
|
||
},
|
||
buildUrl(url) {
|
||
if (this.corsProxy && this.corsProxy.trim()) {
|
||
let proxy = this.corsProxy.trim();
|
||
if (
|
||
!proxy.endsWith("/") &&
|
||
!proxy.endsWith("?") &&
|
||
!proxy.endsWith("=")
|
||
)
|
||
proxy += "/";
|
||
return proxy + url;
|
||
}
|
||
return url;
|
||
},
|
||
};
|
||
|
||
/* =========================================================================
|
||
Utility Functions
|
||
========================================================================= */
|
||
function showToast(message, type = "info", duration = 3000) {
|
||
const container = document.getElementById("toastContainer");
|
||
const toast = document.createElement("div");
|
||
toast.className = `toast ${type}`;
|
||
const icons = { success: "✅", error: "❌", warning: "⚠️", info: "ℹ️" };
|
||
toast.innerHTML = `<span>${icons[type] || "ℹ️"}</span><span>${message}</span>`;
|
||
container.appendChild(toast);
|
||
setTimeout(() => {
|
||
toast.style.opacity = "0";
|
||
toast.style.transform = "translateX(-30px)";
|
||
setTimeout(() => toast.remove(), 300);
|
||
}, duration);
|
||
}
|
||
|
||
function escapeHtml(text) {
|
||
if (text === undefined || text === null) return "";
|
||
const div = document.createElement("div");
|
||
div.textContent = String(text);
|
||
return div.innerHTML;
|
||
}
|
||
|
||
function formatBytes(bytes) {
|
||
if (bytes === 0) return "0 B";
|
||
const k = 1024;
|
||
const sizes = ["B", "KB", "MB", "GB"];
|
||
const i = Math.floor(Math.log(bytes) / Math.log(k));
|
||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
|
||
}
|
||
|
||
function syntaxHighlightJson(json) {
|
||
if (!json) return "";
|
||
json = escapeHtml(json);
|
||
return json.replace(
|
||
/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,
|
||
(match) => {
|
||
let cls = "json-number";
|
||
if (/^"/.test(match))
|
||
cls = /:$/.test(match) ? "json-key" : "json-string";
|
||
else if (/true|false/.test(match)) cls = "json-boolean";
|
||
else if (/null/.test(match)) cls = "json-null";
|
||
return `<span class="${cls}">${match}</span>`;
|
||
},
|
||
);
|
||
}
|
||
|
||
function toKebabCase(str) {
|
||
return str
|
||
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
||
.replace(/([A-Z]+)([A-Z][a-z])/g, "$1-$2")
|
||
.toLowerCase();
|
||
}
|
||
|
||
function toCamelCase(str) {
|
||
if (!str) return str;
|
||
return str.charAt(0).toLowerCase() + str.slice(1);
|
||
}
|
||
|
||
function normalizeSwaggerKeys(obj) {
|
||
if (obj === null || typeof obj !== "object") return obj;
|
||
if (Array.isArray(obj)) return obj.map(normalizeSwaggerKeys);
|
||
const normalized = {};
|
||
for (const key in obj)
|
||
normalized[key.trim()] = normalizeSwaggerKeys(obj[key]);
|
||
return normalized;
|
||
}
|
||
|
||
/* =========================================================================
|
||
Theme
|
||
========================================================================= */
|
||
const themeToggle = document.getElementById("themeToggle");
|
||
const themeIcon = document.getElementById("themeIcon");
|
||
const html = document.documentElement;
|
||
const savedTheme = localStorage.getItem("swagger-sdk-theme") || "dark";
|
||
html.setAttribute("data-theme", savedTheme);
|
||
themeIcon.textContent = savedTheme === "dark" ? "☀️" : "🌙";
|
||
themeToggle.addEventListener("click", () => {
|
||
const currentTheme = html.getAttribute("data-theme");
|
||
const newTheme = currentTheme === "dark" ? "light" : "dark";
|
||
html.setAttribute("data-theme", newTheme);
|
||
localStorage.setItem("swagger-sdk-theme", newTheme);
|
||
themeIcon.textContent = newTheme === "dark" ? "☀️" : "🌙";
|
||
});
|
||
|
||
/* =========================================================================
|
||
Global Settings Bindings
|
||
========================================================================= */
|
||
function initGlobalSettings() {
|
||
GlobalSettings.load();
|
||
const bindings = [
|
||
{ id: "gBaseUrl", key: "baseUrl" },
|
||
{ id: "gCorsProxy", key: "corsProxy" },
|
||
{ id: "gXPoweredBy", key: "xPoweredBy" },
|
||
{ id: "gXApiKey", key: "xApiKey" },
|
||
{ id: "gVersion", key: "version" },
|
||
];
|
||
bindings.forEach(({ id, key }) => {
|
||
const el = document.getElementById(id);
|
||
el.value = GlobalSettings[key] || "";
|
||
el.addEventListener("input", () => {
|
||
GlobalSettings[key] = el.value;
|
||
GlobalSettings.save();
|
||
});
|
||
});
|
||
updateAuthStatusUI();
|
||
}
|
||
|
||
function updateAuthStatusUI() {
|
||
const statusEl = document.getElementById("authStatus");
|
||
if (!statusEl) return;
|
||
if (GlobalSettings.isAuthenticated()) {
|
||
if (GlobalSettings.isTokenExpired()) {
|
||
statusEl.className = "auth-status unauthenticated";
|
||
statusEl.innerHTML =
|
||
'<span class="auth-status-dot"></span><span>منقضی شده</span>';
|
||
} else {
|
||
statusEl.className = "auth-status authenticated";
|
||
statusEl.innerHTML =
|
||
'<span class="auth-status-dot"></span><span>احراز شده ✓</span>';
|
||
}
|
||
} else {
|
||
statusEl.className = "auth-status unauthenticated";
|
||
statusEl.innerHTML =
|
||
'<span class="auth-status-dot"></span><span>غیرفعال</span>';
|
||
}
|
||
updateCurrentTokenInfo();
|
||
}
|
||
|
||
function updateCurrentTokenInfo() {
|
||
const infoEl = document.getElementById("currentTokenInfo");
|
||
if (!infoEl) return;
|
||
if (!GlobalSettings.isAuthenticated()) {
|
||
infoEl.innerHTML =
|
||
'<span style="color: var(--danger);">❌ هیچ توکنی ثبت نشده است.</span>';
|
||
return;
|
||
}
|
||
const expiresAt = GlobalSettings.expiresAt;
|
||
const expiresDate = expiresAt
|
||
? new Date(expiresAt * 1000).toLocaleString("fa-IR")
|
||
: "N/A";
|
||
const isExpired = GlobalSettings.isTokenExpired();
|
||
infoEl.innerHTML = `
|
||
<div style="margin-bottom: 6px;"><span class="json-key">accessToken:</span> <span class="json-string">"${escapeHtml(GlobalSettings.accessToken.substring(0, 30))}..."</span></div>
|
||
<div style="margin-bottom: 6px;"><span class="json-key">refreshToken:</span> <span class="json-string">"${escapeHtml(GlobalSettings.refreshToken.substring(0, 30))}..."</span></div>
|
||
<div style="margin-bottom: 6px;"><span class="json-key">expiresAt:</span> <span class="json-number">${expiresAt}</span> <span class="json-comment">(${expiresDate})</span></div>
|
||
<div style="margin-top: 10px; padding: 8px; background: ${isExpired ? "rgba(229,62,62,0.1)" : "rgba(56,161,105,0.1)"}; border-radius: 4px; color: ${isExpired ? "var(--danger)" : "var(--success)"}; font-weight: 700;">
|
||
${isExpired ? "⚠️ توکن منقضی شده است" : "✅ توکن معتبر است"}
|
||
</div>`;
|
||
}
|
||
|
||
/* =========================================================================
|
||
File Upload
|
||
========================================================================= */
|
||
const fileInput = document.getElementById("fileInput");
|
||
const uploadZone = document.getElementById("uploadZone");
|
||
const loadFileBtn = document.getElementById("loadFileBtn");
|
||
loadFileBtn.addEventListener("click", () => fileInput.click());
|
||
uploadZone.addEventListener("click", () => fileInput.click());
|
||
uploadZone.addEventListener("dragover", (e) => {
|
||
e.preventDefault();
|
||
uploadZone.classList.add("dragover");
|
||
});
|
||
uploadZone.addEventListener("dragleave", () =>
|
||
uploadZone.classList.remove("dragover"),
|
||
);
|
||
uploadZone.addEventListener("drop", (e) => {
|
||
e.preventDefault();
|
||
uploadZone.classList.remove("dragover");
|
||
const file = e.dataTransfer.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
fileInput.addEventListener("change", (e) => {
|
||
const file = e.target.files[0];
|
||
if (file) handleFile(file);
|
||
});
|
||
|
||
function handleFile(file) {
|
||
const reader = new FileReader();
|
||
reader.onload = (e) => {
|
||
try {
|
||
const json = JSON.parse(e.target.result);
|
||
processSwagger(normalizeSwaggerKeys(json));
|
||
showToast("فایل Swagger با موفقیت بارگذاری شد", "success");
|
||
} catch (err) {
|
||
showToast("خطا: " + err.message, "error");
|
||
}
|
||
};
|
||
reader.readAsText(file);
|
||
}
|
||
|
||
/* =========================================================================
|
||
Swagger Parser
|
||
========================================================================= */
|
||
function processSwagger(swagger) {
|
||
AppState.swagger = swagger;
|
||
AppState.allSchemas = swagger.components?.schemas || {};
|
||
AppState.controllers = extractControllers(swagger);
|
||
renderStats();
|
||
renderControllersList();
|
||
renderControllerTabs();
|
||
uploadZone.style.display = "none";
|
||
document.getElementById("loadedContent").style.display = "block";
|
||
const firstCtrl = Object.keys(AppState.controllers)[0];
|
||
if (firstCtrl) selectController(firstCtrl);
|
||
}
|
||
|
||
function extractControllers(swagger) {
|
||
const controllers = {};
|
||
const paths = swagger.paths || {};
|
||
Object.keys(paths).forEach((path) => {
|
||
const pathItem = paths[path];
|
||
Object.keys(pathItem).forEach((method) => {
|
||
if (!["get", "post", "put", "delete", "patch"].includes(method))
|
||
return;
|
||
const operation = pathItem[method];
|
||
const tags = operation.tags || ["Default"];
|
||
tags.forEach((tag) => {
|
||
if (!controllers[tag])
|
||
controllers[tag] = {
|
||
name: tag,
|
||
endpoints: [],
|
||
models: new Set(),
|
||
};
|
||
controllers[tag].endpoints.push({
|
||
path,
|
||
method,
|
||
operation,
|
||
summary: operation.summary || "",
|
||
});
|
||
const reqBody = operation.requestBody;
|
||
if (reqBody?.content)
|
||
Object.values(reqBody.content).forEach((ct) => {
|
||
if (ct.schema)
|
||
extractModelsFromSchema(ct.schema, controllers[tag].models);
|
||
});
|
||
Object.values(operation.responses || {}).forEach((resp) => {
|
||
if (resp.content)
|
||
Object.values(resp.content).forEach((ct) => {
|
||
if (ct.schema)
|
||
extractModelsFromSchema(
|
||
ct.schema,
|
||
controllers[tag].models,
|
||
);
|
||
});
|
||
});
|
||
});
|
||
});
|
||
});
|
||
return controllers;
|
||
}
|
||
|
||
function extractModelsFromSchema(schema, modelSet) {
|
||
if (!schema) return;
|
||
if (schema.$ref) {
|
||
const refName = schema.$ref.replace("#/components/schemas/", "");
|
||
if (!modelSet.has(refName) && AppState.allSchemas[refName]) {
|
||
modelSet.add(refName);
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema.properties)
|
||
Object.values(refSchema.properties).forEach((p) =>
|
||
extractModelsFromSchema(p, modelSet),
|
||
);
|
||
if (refSchema.items)
|
||
extractModelsFromSchema(refSchema.items, modelSet);
|
||
}
|
||
} else if (schema.items) {
|
||
extractModelsFromSchema(schema.items, modelSet);
|
||
} else if (schema.properties) {
|
||
Object.values(schema.properties).forEach((p) =>
|
||
extractModelsFromSchema(p, modelSet),
|
||
);
|
||
}
|
||
}
|
||
|
||
/* =========================================================================
|
||
Render Functions
|
||
========================================================================= */
|
||
function renderStats() {
|
||
const grid = document.getElementById("statsGrid");
|
||
const totalControllers = Object.keys(AppState.controllers).length;
|
||
const totalEndpoints = Object.values(AppState.controllers).reduce(
|
||
(sum, c) => sum + c.endpoints.length,
|
||
0,
|
||
);
|
||
const totalModels = Object.keys(AppState.allSchemas).length;
|
||
const usedModels = new Set();
|
||
Object.values(AppState.controllers).forEach((c) =>
|
||
c.models.forEach((m) => usedModels.add(m)),
|
||
);
|
||
grid.innerHTML = `
|
||
<div class="stat-card"><div class="stat-value">${totalControllers}</div><div class="stat-label">کنترلرها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${totalEndpoints}</div><div class="stat-label">اندپوینتها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${totalModels}</div><div class="stat-label">کل مدلها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${usedModels.size}</div><div class="stat-label">مدلهای استفاده شده</div></div>`;
|
||
}
|
||
|
||
function renderControllersList() {
|
||
const list = document.getElementById("controllersList");
|
||
list.innerHTML = "";
|
||
const searchWrapper = document.createElement("div");
|
||
searchWrapper.className = "search-input-wrapper";
|
||
searchWrapper.innerHTML = `<input type="text" class="search-input" id="controllerSearch" placeholder="جستجوی کنترلر..."><span class="search-icon">🔍</span><button type="button" class="search-clear" id="controllerSearchClear">✕</button>`;
|
||
list.appendChild(searchWrapper);
|
||
const ctrlIcons = {
|
||
Account: "👤",
|
||
FileProvider: "📁",
|
||
StringProvider: "🔤",
|
||
TagProvider: "🏷️",
|
||
ContentProvider: "📝",
|
||
CategoryProvider: "📂",
|
||
SubCategoryProvider: "📑",
|
||
TermsAndConditionsProvider: "📜",
|
||
TestProvider: "🧪",
|
||
TestIdentity: "🔐",
|
||
TestFeatures: "⚙️",
|
||
Startup: "🚀",
|
||
Default: "📦",
|
||
};
|
||
const container = document.createElement("div");
|
||
container.id = "controllersContainer";
|
||
list.appendChild(container);
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
document
|
||
.getElementById("controllerSearch")
|
||
.addEventListener("input", (e) => {
|
||
AppState.searchTerms.controllers = e.target.value;
|
||
document
|
||
.getElementById("controllerSearchClear")
|
||
.classList.toggle("visible", e.target.value.length > 0);
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
});
|
||
document
|
||
.getElementById("controllerSearchClear")
|
||
.addEventListener("click", () => {
|
||
document.getElementById("controllerSearch").value = "";
|
||
AppState.searchTerms.controllers = "";
|
||
document
|
||
.getElementById("controllerSearchClear")
|
||
.classList.remove("visible");
|
||
renderFilteredControllers(container, ctrlIcons);
|
||
});
|
||
}
|
||
|
||
function renderFilteredControllers(container, ctrlIcons) {
|
||
container.innerHTML = "";
|
||
const searchTerm = AppState.searchTerms.controllers.toLowerCase();
|
||
Object.keys(AppState.controllers)
|
||
.sort()
|
||
.forEach((name) => {
|
||
if (searchTerm && !name.toLowerCase().includes(searchTerm)) return;
|
||
const ctrl = AppState.controllers[name];
|
||
const btn = document.createElement("button");
|
||
btn.type = "button";
|
||
btn.className =
|
||
"controller-item" +
|
||
(AppState.activeController === name ? " active" : "");
|
||
btn.innerHTML = `<span class="ctrl-icon">${ctrlIcons[name] || "📦"}</span><span class="ctrl-name">${name}</span><span class="ctrl-badge">${ctrl.endpoints.length}</span>`;
|
||
btn.addEventListener("click", () => selectController(name));
|
||
container.appendChild(btn);
|
||
});
|
||
}
|
||
|
||
function renderControllerTabs() {
|
||
const tabs = document.getElementById("controllerTabs");
|
||
tabs.innerHTML = "";
|
||
const tabIcons = {
|
||
overview: "📊",
|
||
models: "📦",
|
||
endpoints: "🔌",
|
||
provider: "⚙️",
|
||
};
|
||
const tabNames = {
|
||
overview: "نمای کلی",
|
||
models: "مدلها",
|
||
endpoints: "اندپوینتها",
|
||
provider: "Service",
|
||
};
|
||
["overview", "models", "endpoints", "provider"].forEach((tab) => {
|
||
const btn = document.createElement("button");
|
||
btn.type = "button";
|
||
btn.className =
|
||
"controller-tab" + (tab === "overview" ? " active" : "");
|
||
btn.dataset.tab = tab;
|
||
btn.innerHTML = `<span>${tabIcons[tab]}</span><span>${tabNames[tab]}</span>`;
|
||
btn.addEventListener("click", () => switchTab(tab));
|
||
tabs.appendChild(btn);
|
||
});
|
||
}
|
||
|
||
function switchTab(tabName) {
|
||
document
|
||
.querySelectorAll(".controller-tab")
|
||
.forEach((t) =>
|
||
t.classList.toggle("active", t.dataset.tab === tabName),
|
||
);
|
||
renderControllerContent(tabName);
|
||
}
|
||
|
||
function selectController(name) {
|
||
AppState.activeController = name;
|
||
document
|
||
.querySelectorAll(".controller-item")
|
||
.forEach((item) =>
|
||
item.classList.toggle("active", item.dataset.controller === name),
|
||
);
|
||
const activeTab =
|
||
document.querySelector(".controller-tab.active")?.dataset.tab ||
|
||
"overview";
|
||
renderControllerContent(activeTab);
|
||
}
|
||
|
||
function renderControllerContent(tabName) {
|
||
const content = document.getElementById("controllerContent");
|
||
const ctrl = AppState.controllers[AppState.activeController];
|
||
if (!ctrl) return;
|
||
if (tabName === "overview") renderOverview(ctrl, content);
|
||
else if (tabName === "models") renderModels(ctrl, content);
|
||
else if (tabName === "endpoints") renderEndpoints(ctrl, content);
|
||
else if (tabName === "provider") renderProviderService(ctrl, content);
|
||
}
|
||
|
||
function renderOverview(ctrl, container) {
|
||
const methodCounts = { get: 0, post: 0, put: 0, delete: 0 };
|
||
ctrl.endpoints.forEach((e) => {
|
||
if (methodCounts[e.method] !== undefined) methodCounts[e.method]++;
|
||
});
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">📊</div><div class="section-title"><h3>کنترلر ${ctrl.name}</h3><div class="subtitle">نمای کلی</div></div></div>
|
||
<div class="stats-grid">
|
||
<div class="stat-card"><div class="stat-value">${ctrl.endpoints.length}</div><div class="stat-label">اندپوینتها</div></div>
|
||
<div class="stat-card"><div class="stat-value">${ctrl.models.size}</div><div class="stat-label">مدلها</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#63b3ed">${methodCounts.get}</div><div class="stat-label">GET</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#68d391">${methodCounts.post}</div><div class="stat-label">POST</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#f6ad55">${methodCounts.put}</div><div class="stat-label">PUT</div></div>
|
||
<div class="stat-card"><div class="stat-value" style="color:#fc8181">${methodCounts.delete}</div><div class="stat-label">DELETE</div></div>
|
||
</div>
|
||
</div>
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">🔌</div><div class="section-title"><h3>اندپوینتهای اخیر</h3></div></div>
|
||
${renderEndpointsTable(ctrl.endpoints.slice(0, 5), true)}
|
||
</div>`;
|
||
attachTestButtonHandlers();
|
||
}
|
||
|
||
function renderModels(ctrl, container) {
|
||
const models = Array.from(ctrl.models).sort();
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">📦</div><div class="section-title"><h3>مدلهای کنترلر ${ctrl.name}</h3></div></div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="modelSearch" placeholder="جستجوی مدل...">
|
||
<span class="search-icon">🔍</span>
|
||
<button type="button" class="search-clear" id="modelSearchClear">✕</button>
|
||
</div>
|
||
<div class="models-grid" id="modelsGrid"></div>
|
||
</div>`;
|
||
renderFilteredModels(models);
|
||
document
|
||
.getElementById("modelSearch")
|
||
.addEventListener("input", (e) => {
|
||
AppState.searchTerms.models = e.target.value;
|
||
document
|
||
.getElementById("modelSearchClear")
|
||
.classList.toggle("visible", e.target.value.length > 0);
|
||
renderFilteredModels(models);
|
||
});
|
||
document
|
||
.getElementById("modelSearchClear")
|
||
.addEventListener("click", () => {
|
||
document.getElementById("modelSearch").value = "";
|
||
AppState.searchTerms.models = "";
|
||
document
|
||
.getElementById("modelSearchClear")
|
||
.classList.remove("visible");
|
||
renderFilteredModels(models);
|
||
});
|
||
}
|
||
|
||
function renderFilteredModels(allModels) {
|
||
const grid = document.getElementById("modelsGrid");
|
||
if (!grid) return;
|
||
const searchTerm = AppState.searchTerms.models.toLowerCase();
|
||
const filtered = allModels.filter(
|
||
(n) => !searchTerm || n.toLowerCase().includes(searchTerm),
|
||
);
|
||
if (filtered.length === 0) {
|
||
grid.innerHTML =
|
||
'<div class="empty-state" style="grid-column: 1/-1;"><p>مدلی یافت نشد</p></div>';
|
||
return;
|
||
}
|
||
grid.innerHTML = filtered
|
||
.map((name) => {
|
||
const schema = AppState.allSchemas[name];
|
||
const propsCount = schema?.properties
|
||
? Object.keys(schema.properties).length
|
||
: 0;
|
||
const type = schema?.enum ? "Enum" : "DTO";
|
||
const icon = type === "Enum" ? "🔢" : "📦";
|
||
return `<div class="model-card" data-model="${name}"><div class="model-card-header"><div class="model-card-icon">${icon}</div><div class="model-card-name" title="${name}">${name}</div></div><div class="model-card-meta"><span>🔹 ${type}</span><span>📐 ${propsCount} فیلد</span></div></div>`;
|
||
})
|
||
.join("");
|
||
grid
|
||
.querySelectorAll(".model-card")
|
||
.forEach((card) =>
|
||
card.addEventListener("click", () =>
|
||
openModelModal(card.dataset.model),
|
||
),
|
||
);
|
||
}
|
||
|
||
function renderEndpoints(ctrl, container) {
|
||
container.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">🔌</div><div class="section-title"><h3>اندپوینتهای کنترلر ${ctrl.name}</h3><div class="subtitle">برای تست هر اندپوینت روی دکمه 🧪 کلیک کنید</div></div></div>
|
||
<div class="search-input-wrapper" style="max-width: 400px; margin-bottom: 16px;">
|
||
<input type="text" class="search-input" id="endpointSearch" placeholder="جستجوی اندپوینت...">
|
||
<span class="search-icon">🔍</span>
|
||
<button type="button" class="search-clear" id="endpointSearchClear">✕</button>
|
||
</div>
|
||
<div id="endpointsTable"></div>
|
||
</div>`;
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
document
|
||
.getElementById("endpointSearch")
|
||
.addEventListener("input", (e) => {
|
||
AppState.searchTerms.endpoints = e.target.value;
|
||
document
|
||
.getElementById("endpointSearchClear")
|
||
.classList.toggle("visible", e.target.value.length > 0);
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
document
|
||
.getElementById("endpointSearchClear")
|
||
.addEventListener("click", () => {
|
||
document.getElementById("endpointSearch").value = "";
|
||
AppState.searchTerms.endpoints = "";
|
||
document
|
||
.getElementById("endpointSearchClear")
|
||
.classList.remove("visible");
|
||
renderFilteredEndpoints(ctrl.endpoints);
|
||
});
|
||
}
|
||
|
||
function renderFilteredEndpoints(allEndpoints) {
|
||
const tableContainer = document.getElementById("endpointsTable");
|
||
if (!tableContainer) return;
|
||
const searchTerm = AppState.searchTerms.endpoints.toLowerCase();
|
||
const filtered = allEndpoints.filter(
|
||
(e) =>
|
||
!searchTerm ||
|
||
e.path.toLowerCase().includes(searchTerm) ||
|
||
(e.summary || "").toLowerCase().includes(searchTerm),
|
||
);
|
||
if (filtered.length === 0) {
|
||
tableContainer.innerHTML =
|
||
'<div class="empty-state"><p>اندپوینتی یافت نشد</p></div>';
|
||
return;
|
||
}
|
||
tableContainer.innerHTML = renderEndpointsTable(filtered, true);
|
||
attachTestButtonHandlers();
|
||
}
|
||
|
||
function renderEndpointsTable(endpoints, showTestBtn = false) {
|
||
const rows = endpoints
|
||
.map((e, idx) => {
|
||
const endpointKey = `${e.method}:${e.path}`;
|
||
const testBtn = showTestBtn
|
||
? `<button type="button" class="test-btn" data-endpoint-key="${encodeURIComponent(endpointKey)}">🧪 تست</button>`
|
||
: "";
|
||
return `<tr><td><span class="method-badge method-${e.method}">${e.method.toUpperCase()}</span></td><td class="endpoint-path">${e.path}</td><td>${e.summary || "-"}</td><td style="text-align: center;">${testBtn}</td></tr>`;
|
||
})
|
||
.join("");
|
||
return `<table class="endpoints-table"><thead><tr><th>متد</th><th>مسیر</th><th>توضیحات</th><th style="text-align: center; width: 80px;">عملیات</th></tr></thead><tbody>${rows}</tbody></table>`;
|
||
}
|
||
|
||
function attachTestButtonHandlers() {
|
||
document.querySelectorAll(".test-btn").forEach((btn) => {
|
||
btn.addEventListener("click", (e) => {
|
||
e.stopPropagation();
|
||
const endpointKey = decodeURIComponent(btn.dataset.endpointKey);
|
||
const [method, path] = endpointKey.split(/:(.+)/);
|
||
const ctrl = AppState.controllers[AppState.activeController];
|
||
if (!ctrl) return;
|
||
const endpoint = ctrl.endpoints.find(
|
||
(ep) => ep.method === method && ep.path === path,
|
||
);
|
||
if (endpoint) openEndpointTestModal(endpoint);
|
||
});
|
||
});
|
||
}
|
||
|
||
/* =========================================================================
|
||
ENDPOINT TEST MODAL
|
||
========================================================================= */
|
||
function openEndpointTestModal(endpoint) {
|
||
const modalId =
|
||
"testModal_" +
|
||
btoa(endpoint.method + ":" + endpoint.path).replace(
|
||
/[^a-zA-Z0-9]/g,
|
||
"",
|
||
);
|
||
let existingModal = document.getElementById(modalId);
|
||
if (existingModal) {
|
||
existingModal.style.zIndex =
|
||
1000 + document.querySelectorAll(".modal-overlay.active").length;
|
||
existingModal.classList.add("active");
|
||
return;
|
||
}
|
||
const modalOverlay = document.createElement("div");
|
||
modalOverlay.className = "modal-overlay active";
|
||
modalOverlay.id = modalId;
|
||
modalOverlay.style.zIndex =
|
||
1000 + document.querySelectorAll(".modal-overlay.active").length;
|
||
const parameters = endpoint.operation.parameters || [];
|
||
const pathParams = parameters.filter(
|
||
(p) => p.in === "path" && p.name !== "version",
|
||
);
|
||
const queryParams = parameters.filter((p) => p.in === "query");
|
||
let bodySchema = null,
|
||
isFormData = false;
|
||
const requestBody = endpoint.operation.requestBody;
|
||
if (requestBody?.content) {
|
||
if (requestBody.content["multipart/form-data"]) {
|
||
isFormData = true;
|
||
bodySchema = requestBody.content["multipart/form-data"].schema;
|
||
} else if (requestBody.content["application/json"]) {
|
||
bodySchema = requestBody.content["application/json"].schema;
|
||
} else if (requestBody.content["application/json-patch+json"]) {
|
||
bodySchema =
|
||
requestBody.content["application/json-patch+json"].schema;
|
||
}
|
||
}
|
||
const displayPath = endpoint.path.replace(
|
||
"{version}",
|
||
GlobalSettings.version || "1.0",
|
||
);
|
||
let html = `
|
||
<div class="modal" style="max-width: 1100px;">
|
||
<div class="modal-header">
|
||
<div class="modal-title">
|
||
<span class="method-badge method-${endpoint.method}" style="font-size: 12px; padding: 4px 12px;">${endpoint.method.toUpperCase()}</span>
|
||
<span style="font-family: 'Fira Code', monospace; direction: ltr; font-size: 13px;">${escapeHtml(displayPath)}</span>
|
||
</div>
|
||
<button type="button" class="modal-close" data-close-test-modal>✕</button>
|
||
</div>
|
||
<div class="modal-body">
|
||
${endpoint.summary ? `<div style="margin-bottom: 14px; padding: 10px; background: var(--column-bg); border-radius: 6px; font-size: 12px; color: var(--text-muted);">📝 ${escapeHtml(endpoint.summary)}</div>` : ""}
|
||
<div class="cors-info-box">
|
||
<strong>💡 نکته CORS:</strong> اگر با خطای CORS مواجه شدید، در نوار تنظیمات بالا فیلد <strong>CORS Proxy</strong> را با یکی از مقادیر زیر پر کنید:
|
||
<br><code>https://corsproxy.io/?</code> یا <code>https://api.allorigins.win/raw?url=</code>
|
||
<br>یا سرور خود را با هدرهای CORS مناسب پیکربندی کنید.
|
||
</div>
|
||
<div class="test-form">`;
|
||
if (pathParams.length > 0) {
|
||
html += `<div class="test-form-section"><div class="test-form-section-title">📍 Path Parameters</div>
|
||
${pathParams.map((p) => `<div class="test-field"><label>${p.name} ${p.required ? '<span class="required">*</span>' : ""}</label><input type="text" data-param-type="path" data-param-name="${p.name}" placeholder="${p.description || p.name}" value="${p.schema?.default || ""}"></div>`).join("")}</div>`;
|
||
}
|
||
if (queryParams.length > 0) {
|
||
html += `<div class="test-form-section"><div class="test-form-section-title">🔎 Query Parameters</div>
|
||
${queryParams
|
||
.map((p) => {
|
||
const inputType =
|
||
p.schema?.type === "boolean"
|
||
? "select"
|
||
: p.schema?.type === "integer" || p.schema?.type === "number"
|
||
? "number"
|
||
: "text";
|
||
let inputHtml =
|
||
inputType === "select"
|
||
? `<select data-param-type="query" data-param-name="${p.name}"><option value="">-- انتخاب --</option><option value="true">true</option><option value="false">false</option></select>`
|
||
: `<input type="${inputType}" data-param-type="query" data-param-name="${p.name}" placeholder="${p.description || p.name}" value="${p.schema?.default ?? ""}">`;
|
||
return `<div class="test-field"><label>${p.name} ${p.required ? '<span class="required">*</span>' : ""}</label>${inputHtml}</div>`;
|
||
})
|
||
.join("")}</div>`;
|
||
}
|
||
if (bodySchema) {
|
||
if (isFormData) {
|
||
html += `<div class="test-form-section full-width"><div class="test-form-section-title">📎 Form Data (multipart/form-data)</div><div class="test-field"><label>files (File Upload)</label><input type="file" data-param-type="file" data-param-name="files" multiple></div></div>`;
|
||
} else {
|
||
const exampleBody = generateExampleBody(bodySchema);
|
||
html += `<div class="test-form-section full-width"><div class="test-form-section-title">📦 Request Body (application/json)</div><div class="test-field"><label>Body (JSON)</label><textarea data-param-type="body" data-param-name="body" rows="10">${escapeHtml(JSON.stringify(exampleBody, null, 2))}</textarea></div></div>`;
|
||
}
|
||
}
|
||
html += `</div>
|
||
<div class="test-actions">
|
||
<button type="button" class="btn btn-success" id="${modalId}_executeBtn"><span>🚀</span><span>اجرای درخواست</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="${modalId}_curlBtn"><span>📋</span><span>کپی cURL</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" id="${modalId}_toggleDebugBtn"><span>🔍</span><span>نمایش/مخفی Debug Log</span></button>
|
||
</div>
|
||
<div id="${modalId}_debugLog" class="debug-log" style="display: none;"></div>
|
||
<div id="${modalId}_responseArea"></div>
|
||
</div>
|
||
<div class="modal-footer">
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" data-close-test-modal>بستن</button>
|
||
</div>
|
||
</div>`;
|
||
modalOverlay.innerHTML = html;
|
||
document.body.appendChild(modalOverlay);
|
||
modalOverlay
|
||
.querySelectorAll("[data-close-test-modal]")
|
||
.forEach((btn) => {
|
||
btn.addEventListener("click", () => {
|
||
modalOverlay.classList.remove("active");
|
||
setTimeout(() => {
|
||
modalOverlay.remove();
|
||
}, 200);
|
||
});
|
||
});
|
||
modalOverlay.addEventListener("click", (e) => {
|
||
if (e.target === modalOverlay) {
|
||
modalOverlay.classList.remove("active");
|
||
setTimeout(() => {
|
||
modalOverlay.remove();
|
||
}, 200);
|
||
}
|
||
});
|
||
document
|
||
.getElementById(`${modalId}_executeBtn`)
|
||
.addEventListener("click", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
executeEndpointRequest(endpoint, modalId);
|
||
});
|
||
document
|
||
.getElementById(`${modalId}_curlBtn`)
|
||
.addEventListener("click", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
copyCurlCommand(endpoint, modalId);
|
||
});
|
||
document
|
||
.getElementById(`${modalId}_toggleDebugBtn`)
|
||
.addEventListener("click", () => {
|
||
const debugLog = document.getElementById(`${modalId}_debugLog`);
|
||
debugLog.style.display =
|
||
debugLog.style.display === "none" ? "block" : "none";
|
||
});
|
||
}
|
||
|
||
function generateExampleBody(schema) {
|
||
if (!schema) return {};
|
||
if (schema.$ref) {
|
||
const refName = schema.$ref.replace("#/components/schemas/", "");
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema) return generateExampleFromSchema(refSchema);
|
||
return {};
|
||
}
|
||
return generateExampleFromSchema(schema);
|
||
}
|
||
|
||
function generateExampleFromSchema(schema) {
|
||
if (!schema || !schema.properties) return {};
|
||
const example = {};
|
||
for (const [key, prop] of Object.entries(schema.properties))
|
||
example[key] = generateExampleValue(prop);
|
||
return example;
|
||
}
|
||
|
||
function generateExampleValue(prop) {
|
||
if (!prop) return null;
|
||
if (prop.$ref) {
|
||
const refName = prop.$ref.replace("#/components/schemas/", "");
|
||
const refSchema = AppState.allSchemas[refName];
|
||
if (refSchema?.properties)
|
||
return generateExampleFromSchema(refSchema);
|
||
return {};
|
||
}
|
||
if (prop.type === "array") {
|
||
if (prop.items) return [generateExampleValue(prop.items)];
|
||
return [];
|
||
}
|
||
if (prop.enum && prop.enum.length > 0) return prop.enum[0];
|
||
switch (prop.type) {
|
||
case "string":
|
||
if (prop.format === "date-time") return new Date().toISOString();
|
||
if (prop.format === "uuid")
|
||
return "00000000-0000-0000-0000-000000000000";
|
||
return "";
|
||
case "integer":
|
||
case "number":
|
||
return prop.default ?? 0;
|
||
case "boolean":
|
||
return prop.default ?? false;
|
||
default:
|
||
return null;
|
||
}
|
||
}
|
||
|
||
/* =========================================================================
|
||
Execute Request
|
||
========================================================================= */
|
||
async function executeEndpointRequest(endpoint, modalId) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const executeBtn = document.getElementById(`${modalId}_executeBtn`);
|
||
const debugLog = document.getElementById(`${modalId}_debugLog`);
|
||
executeBtn.disabled = true;
|
||
executeBtn.innerHTML =
|
||
'<span class="loading-spinner"></span><span>در حال ارسال...</span>';
|
||
debugLog.innerHTML = `<span class="log-info">[${new Date().toLocaleTimeString()}] شروع اجرای درخواست...</span>\n`;
|
||
responseArea.innerHTML = `<div class="response-panel"><div class="response-header"><span class="response-status info">⏳ در انتظار...</span></div></div>`;
|
||
try {
|
||
let url = endpoint.path.replace(
|
||
"{version}",
|
||
GlobalSettings.version || "1.0",
|
||
);
|
||
const modal = document.getElementById(modalId);
|
||
modal
|
||
.querySelectorAll('[data-param-type="path"]')
|
||
.forEach((input) => {
|
||
const name = input.dataset.paramName;
|
||
const value = input.value;
|
||
if (!value) throw new Error(`پارامتر مسیر {${name}} خالی است`);
|
||
url = url.replace(`{${name}}`, encodeURIComponent(value));
|
||
});
|
||
if (url.includes("{") && url.includes("}"))
|
||
throw new Error("لطفاً تمام پارامترهای مسیر را پر کنید");
|
||
const queryParams = new URLSearchParams();
|
||
modal
|
||
.querySelectorAll('[data-param-type="query"]')
|
||
.forEach((input) => {
|
||
if (
|
||
input.value !== "" &&
|
||
input.value !== null &&
|
||
input.value !== undefined
|
||
)
|
||
queryParams.append(input.dataset.paramName, input.value);
|
||
});
|
||
const queryString = queryParams.toString();
|
||
if (queryString) url += "?" + queryString;
|
||
let fullUrl = GlobalSettings.baseUrl.replace(/\/$/, "") + url;
|
||
const proxiedUrl = GlobalSettings.buildUrl(fullUrl);
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] URL: ${escapeHtml(fullUrl)}</span>\n`;
|
||
if (GlobalSettings.corsProxy) {
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] CORS Proxy: ${escapeHtml(GlobalSettings.corsProxy)}</span>\n`;
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] Proxied URL: ${escapeHtml(proxiedUrl)}</span>\n`;
|
||
}
|
||
const headers = GlobalSettings.buildHeaders();
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] Headers:</span>\n`;
|
||
for (const [k, v] of Object.entries(headers))
|
||
debugLog.innerHTML += ` <span class="log-info">${escapeHtml(k)}: ${escapeHtml(String(v).substring(0, 50))}${String(v).length > 50 ? "..." : ""}</span>\n`;
|
||
const options = {
|
||
method: endpoint.method.toUpperCase(),
|
||
headers: headers,
|
||
};
|
||
const bodyInput = modal.querySelector('[data-param-type="body"]');
|
||
const fileInput = modal.querySelector('[data-param-type="file"]');
|
||
if (bodyInput && bodyInput.value.trim()) {
|
||
headers["Content-Type"] = "application/json";
|
||
try {
|
||
const bodyStr = bodyInput.value;
|
||
JSON.parse(bodyStr);
|
||
options.body = bodyStr;
|
||
debugLog.innerHTML += `<span class="log-request">[${new Date().toLocaleTimeString()}] Body (JSON): ${escapeHtml(bodyStr.substring(0, 200))}${bodyStr.length > 200 ? "..." : ""}</span>\n`;
|
||
} catch (e) {
|
||
throw new Error("JSON نامعتبر است: " + e.message);
|
||
}
|
||
} else if (fileInput && fileInput.files.length > 0) {
|
||
const formData = new FormData();
|
||
for (const file of fileInput.files)
|
||
formData.append("files", file, file.name);
|
||
options.body = formData;
|
||
delete headers["Content-Type"];
|
||
debugLog.innerHTML += `<span class="log-request">[${new Date().toLocaleTimeString()}] Body: FormData با ${fileInput.files.length} فایل</span>\n`;
|
||
}
|
||
debugLog.innerHTML += `<span class="log-info">[${new Date().toLocaleTimeString()}] ارسال درخواست ${endpoint.method.toUpperCase()}...</span>\n`;
|
||
const startTime = performance.now();
|
||
const response = await fetch(proxiedUrl, options);
|
||
const endTime = performance.now();
|
||
const duration = Math.round(endTime - startTime);
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] پاسخ دریافت شد - Status: ${response.status}</span>\n`;
|
||
const contentType = response.headers.get("content-type") || "";
|
||
let responseBody, responseText;
|
||
if (contentType.includes("application/json")) {
|
||
responseText = await response.text();
|
||
try {
|
||
responseBody = JSON.parse(responseText);
|
||
} catch (e) {
|
||
responseBody = responseText;
|
||
}
|
||
} else {
|
||
responseText = await response.text();
|
||
responseBody = responseText;
|
||
}
|
||
const responseHeaders = {};
|
||
response.headers.forEach((value, key) => {
|
||
responseHeaders[key] = value;
|
||
});
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] Response Size: ${formatBytes(responseText.length)}</span>\n`;
|
||
debugLog.innerHTML += `<span class="log-response">[${new Date().toLocaleTimeString()}] Duration: ${duration}ms</span>\n`;
|
||
|
||
// Store last response for clipboard copy
|
||
window._lastResponseData = {
|
||
method: endpoint.method,
|
||
path: endpoint.path,
|
||
status: response.status,
|
||
statusText: response.statusText,
|
||
headers: responseHeaders,
|
||
body: responseBody,
|
||
bodyText: responseText,
|
||
duration: duration,
|
||
url: fullUrl,
|
||
timestamp: new Date().toISOString(),
|
||
};
|
||
|
||
renderResponse(
|
||
response,
|
||
responseBody,
|
||
responseText,
|
||
responseHeaders,
|
||
duration,
|
||
modalId,
|
||
);
|
||
} catch (error) {
|
||
debugLog.innerHTML += `<span class="log-error">[${new Date().toLocaleTimeString()}] ❌ خطا: ${escapeHtml(error.message)}</span>\n`;
|
||
renderErrorResponse(error, modalId);
|
||
} finally {
|
||
executeBtn.disabled = false;
|
||
executeBtn.innerHTML = "<span>🚀</span><span>اجرای درخواست</span>";
|
||
}
|
||
}
|
||
|
||
function renderResponse(
|
||
response,
|
||
body,
|
||
bodyText,
|
||
headers,
|
||
duration,
|
||
modalId,
|
||
) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const statusClass =
|
||
response.status >= 200 && response.status < 300
|
||
? "success"
|
||
: response.status >= 300 && response.status < 400
|
||
? "redirect"
|
||
: "error";
|
||
const bodyFormatted =
|
||
typeof body === "object"
|
||
? syntaxHighlightJson(JSON.stringify(body, null, 2))
|
||
: escapeHtml(bodyText || "");
|
||
const headersHtml = Object.entries(headers)
|
||
.map(
|
||
([k, v]) =>
|
||
`<div><span class="json-key">${escapeHtml(k)}</span>: <span class="json-string">${escapeHtml(v)}</span></div>`,
|
||
)
|
||
.join("");
|
||
|
||
responseArea.innerHTML = `
|
||
<div class="response-panel">
|
||
<div class="response-header">
|
||
<span class="response-status ${statusClass}">${response.status} ${response.statusText}</span>
|
||
<span class="response-time">⏱️ ${duration}ms</span>
|
||
<span class="response-size">📦 ${formatBytes(bodyText.length)}</span>
|
||
</div>
|
||
<div class="response-tabs">
|
||
<button type="button" class="response-tab active" data-tab="body">Body</button>
|
||
<button type="button" class="response-tab" data-tab="headers">Headers</button>
|
||
<button type="button" class="response-tab" data-tab="raw">Raw</button>
|
||
</div>
|
||
<div id="${modalId}_tab_body" class="response-body">${bodyFormatted || '<span style="color: #6a9955;">// Empty response</span>'}</div>
|
||
<div id="${modalId}_tab_headers" class="response-body" style="display: none;">${headersHtml || '<span style="color: #6a9955;">// No headers</span>'}</div>
|
||
<div id="${modalId}_tab_raw" class="response-body" style="display: none;">${escapeHtml(bodyText || "")}</div>
|
||
<div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid var(--border-light); display: flex; gap: 8px; flex-wrap: wrap;">
|
||
<button type="button" class="btn btn-accent btn-sm" id="${modalId}_copyResponseBtn">
|
||
<span>📋</span><span>کپی پاسخ در کلیپبورد</span>
|
||
</button>
|
||
</div>
|
||
</div>`;
|
||
|
||
responseArea.querySelectorAll(".response-tab").forEach((tab) => {
|
||
tab.addEventListener("click", () => {
|
||
responseArea
|
||
.querySelectorAll(".response-tab")
|
||
.forEach((t) => t.classList.remove("active"));
|
||
tab.classList.add("active");
|
||
const tabName = tab.dataset.tab;
|
||
document.getElementById(`${modalId}_tab_body`).style.display =
|
||
tabName === "body" ? "block" : "none";
|
||
document.getElementById(`${modalId}_tab_headers`).style.display =
|
||
tabName === "headers" ? "block" : "none";
|
||
document.getElementById(`${modalId}_tab_raw`).style.display =
|
||
tabName === "raw" ? "block" : "none";
|
||
});
|
||
});
|
||
|
||
// Copy response to clipboard button handler
|
||
document
|
||
.getElementById(`${modalId}_copyResponseBtn`)
|
||
.addEventListener("click", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
copyResponseToClipboard();
|
||
});
|
||
}
|
||
|
||
/* =========================================================================
|
||
NEW: Copy Response to Clipboard (instead of localStorage)
|
||
========================================================================= */
|
||
function copyResponseToClipboard() {
|
||
if (!window._lastResponseData) {
|
||
showToast("❌ هیچ پاسخی برای کپی وجود ندارد", "error");
|
||
return;
|
||
}
|
||
|
||
const r = window._lastResponseData;
|
||
|
||
// Build a comprehensive JSON representation of the response
|
||
const clipboardData = {
|
||
meta: {
|
||
method: r.method,
|
||
path: r.path,
|
||
url: r.url,
|
||
timestamp: r.timestamp,
|
||
duration: r.duration + "ms",
|
||
},
|
||
response: {
|
||
status: r.status,
|
||
statusText: r.statusText,
|
||
headers: r.headers,
|
||
body: r.body,
|
||
},
|
||
};
|
||
|
||
const jsonString = JSON.stringify(clipboardData, null, 2);
|
||
|
||
navigator.clipboard
|
||
.writeText(jsonString)
|
||
.then(() => {
|
||
showToast("✅ پاسخ در کلیپبورد کپی شد", "success");
|
||
})
|
||
.catch((err) => {
|
||
// Fallback for older browsers or non-HTTPS contexts
|
||
try {
|
||
const textarea = document.createElement("textarea");
|
||
textarea.value = jsonString;
|
||
textarea.style.position = "fixed";
|
||
textarea.style.opacity = "0";
|
||
document.body.appendChild(textarea);
|
||
textarea.select();
|
||
document.execCommand("copy");
|
||
document.body.removeChild(textarea);
|
||
showToast("✅ پاسخ در کلیپبورد کپی شد", "success");
|
||
} catch (fallbackErr) {
|
||
showToast(
|
||
"❌ خطا در کپی در کلیپبورد: " + fallbackErr.message,
|
||
"error",
|
||
);
|
||
}
|
||
});
|
||
}
|
||
|
||
function renderErrorResponse(error, modalId) {
|
||
const responseArea = document.getElementById(`${modalId}_responseArea`);
|
||
const isCorsError =
|
||
error.message?.includes("Failed to fetch") ||
|
||
error.message?.includes("NetworkError") ||
|
||
error.message?.includes("CORS") ||
|
||
error.message?.includes("Load failed");
|
||
responseArea.innerHTML = `
|
||
<div class="response-panel">
|
||
<div class="response-header"><span class="response-status error">❌ خطا</span></div>
|
||
<div class="response-body" style="color: #f56565;">${escapeHtml(error.message || String(error))}</div>
|
||
${
|
||
isCorsError
|
||
? `
|
||
<div style="margin-top: 12px; padding: 12px; background: rgba(221,107,32,0.1); border: 1px solid rgba(221,107,32,0.3); border-radius: 6px;">
|
||
<strong style="color: var(--warning);">💡 راهحلهای مشکل CORS:</strong>
|
||
<ol style="margin-top: 8px; padding-right: 20px; font-size: 12px; line-height: 1.8;">
|
||
<li><strong>استفاده از CORS Proxy:</strong> در نوار تنظیمات بالا، فیلد <code style="background: rgba(0,0,0,0.1); padding: 2px 6px; border-radius: 3px; direction: ltr;">CORS Proxy</code> را با یکی از مقادیر زیر پر کنید:
|
||
<ul style="margin-top: 4px; padding-right: 20px; direction: ltr; text-align: left;">
|
||
<li><code>https://corsproxy.io/?</code></li>
|
||
<li><code>https://api.allorigins.win/raw?url=</code></li>
|
||
</ul>
|
||
</li>
|
||
<li><strong>پیکربندی سرور:</strong> در Startup.cs سرور .NET خود، CORS را فعال کنید.</li>
|
||
<li><strong>افزونه مرورگر:</strong> برای تست موقت از افزونههای "CORS Unblock" استفاده کنید.</li>
|
||
</ol>
|
||
</div>`
|
||
: ""
|
||
}
|
||
</div>`;
|
||
}
|
||
|
||
function copyCurlCommand(endpoint, modalId) {
|
||
const modal = document.getElementById(modalId);
|
||
let url = endpoint.path.replace(
|
||
"{version}",
|
||
GlobalSettings.version || "1.0",
|
||
);
|
||
modal.querySelectorAll('[data-param-type="path"]').forEach((input) => {
|
||
url = url.replace(
|
||
`{${input.dataset.paramName}}`,
|
||
input.value || "VALUE",
|
||
);
|
||
});
|
||
const queryParams = new URLSearchParams();
|
||
modal.querySelectorAll('[data-param-type="query"]').forEach((input) => {
|
||
if (input.value)
|
||
queryParams.append(input.dataset.paramName, input.value);
|
||
});
|
||
const qs = queryParams.toString();
|
||
if (qs) url += "?" + qs;
|
||
const fullUrl = GlobalSettings.buildUrl(
|
||
GlobalSettings.baseUrl.replace(/\/$/, "") + url,
|
||
);
|
||
const headers = GlobalSettings.buildHeaders();
|
||
let curl = `curl -X ${endpoint.method.toUpperCase()} '${fullUrl}'`;
|
||
for (const [k, v] of Object.entries(headers))
|
||
curl += ` \\\n -H '${k}: ${v}'`;
|
||
const bodyInput = modal.querySelector('[data-param-type="body"]');
|
||
if (bodyInput && bodyInput.value.trim()) {
|
||
curl += ` \\\n -H 'Content-Type: application/json'`;
|
||
curl += ` \\\n -d '${bodyInput.value.replace(/'/g, "'\\''")}'`;
|
||
}
|
||
navigator.clipboard
|
||
.writeText(curl)
|
||
.then(() => showToast("دستور cURL کپی شد", "success"));
|
||
}
|
||
|
||
/* =========================================================================
|
||
Authentication
|
||
========================================================================= */
|
||
document.getElementById("openAuthBtn").addEventListener("click", () => {
|
||
document.getElementById("authModal").classList.add("active");
|
||
updateCurrentTokenInfo();
|
||
});
|
||
document
|
||
.querySelectorAll("[data-close-auth]")
|
||
.forEach((btn) =>
|
||
btn.addEventListener("click", () =>
|
||
document.getElementById("authModal").classList.remove("active"),
|
||
),
|
||
);
|
||
document.getElementById("authModal").addEventListener("click", (e) => {
|
||
if (e.target.id === "authModal")
|
||
document.getElementById("authModal").classList.remove("active");
|
||
});
|
||
|
||
document
|
||
.getElementById("doLoginBtn")
|
||
.addEventListener("click", async (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const btn = document.getElementById("doLoginBtn");
|
||
const userSelectBy = document
|
||
.getElementById("loginUserSelectBy")
|
||
.value.trim();
|
||
const password = document.getElementById("loginPassword").value;
|
||
const language =
|
||
document.getElementById("loginLanguage").value.trim() || "fa-IR";
|
||
if (!userSelectBy || !password) {
|
||
showToast("لطفاً userSelectBy و password را وارد کنید", "warning");
|
||
return;
|
||
}
|
||
btn.disabled = true;
|
||
btn.innerHTML =
|
||
'<span class="loading-spinner"></span><span>در حال ورود...</span>';
|
||
try {
|
||
const body = {
|
||
userSelectBy: userSelectBy,
|
||
password: password,
|
||
language: language,
|
||
device: {
|
||
os: "Web",
|
||
browser: "SDK-Manager",
|
||
osVersion: navigator.platform,
|
||
userAgent: navigator.userAgent,
|
||
deviceType: 3,
|
||
identifier: "web-sdk-manager-" + Date.now(),
|
||
},
|
||
};
|
||
const url = GlobalSettings.buildUrl(
|
||
GlobalSettings.baseUrl.replace(/\/$/, "") +
|
||
"/Account/Authenticate",
|
||
);
|
||
const headers = GlobalSettings.buildHeaders();
|
||
headers["Content-Type"] = "application/json";
|
||
const response = await fetch(url, {
|
||
method: "POST",
|
||
headers,
|
||
body: JSON.stringify(body),
|
||
});
|
||
if (!response.ok) {
|
||
const errorText = await response.text();
|
||
throw new Error(
|
||
`خطای ${response.status}: ${errorText.substring(0, 300)}`,
|
||
);
|
||
}
|
||
const data = await response.json();
|
||
if (data.accessToken) {
|
||
GlobalSettings.accessToken = data.accessToken;
|
||
GlobalSettings.refreshToken = data.refreshToken || "";
|
||
GlobalSettings.expiresAt = data.expiresAt || 0;
|
||
GlobalSettings.save();
|
||
document.getElementById("manualAccessToken").value =
|
||
data.accessToken;
|
||
document.getElementById("manualRefreshToken").value =
|
||
data.refreshToken || "";
|
||
document.getElementById("manualExpiresAt").value =
|
||
data.expiresAt || "";
|
||
updateAuthStatusUI();
|
||
showToast("✅ ورود با موفقیت انجام شد", "success");
|
||
} else {
|
||
throw new Error("پاسخ نامعتبر: accessToken یافت نشد.");
|
||
}
|
||
} catch (error) {
|
||
let errorMsg = error.message;
|
||
if (
|
||
error.message?.includes("Failed to fetch") ||
|
||
error.message?.includes("NetworkError")
|
||
)
|
||
errorMsg =
|
||
"خطای شبکه/CORS. لطفاً CORS Proxy را در تنظیمات عمومی تنظیم کنید.";
|
||
showToast("❌ خطا در ورود: " + errorMsg, "error", 6000);
|
||
} finally {
|
||
btn.disabled = false;
|
||
btn.innerHTML = "<span>🚀</span><span>ورود به سیستم</span>";
|
||
}
|
||
});
|
||
|
||
document
|
||
.getElementById("saveManualTokenBtn")
|
||
.addEventListener("click", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
const accessToken = document
|
||
.getElementById("manualAccessToken")
|
||
.value.trim();
|
||
if (!accessToken) {
|
||
showToast("لطفاً accessToken را وارد کنید", "warning");
|
||
return;
|
||
}
|
||
GlobalSettings.accessToken = accessToken;
|
||
GlobalSettings.refreshToken = document
|
||
.getElementById("manualRefreshToken")
|
||
.value.trim();
|
||
GlobalSettings.expiresAt =
|
||
parseInt(document.getElementById("manualExpiresAt").value) || 0;
|
||
GlobalSettings.save();
|
||
updateAuthStatusUI();
|
||
showToast("✅ توکنها ذخیره شدند", "success");
|
||
});
|
||
|
||
document
|
||
.getElementById("clearTokenBtn")
|
||
.addEventListener("click", (e) => {
|
||
e.preventDefault();
|
||
e.stopPropagation();
|
||
GlobalSettings.accessToken = "";
|
||
GlobalSettings.refreshToken = "";
|
||
GlobalSettings.expiresAt = 0;
|
||
GlobalSettings.save();
|
||
document.getElementById("manualAccessToken").value = "";
|
||
document.getElementById("manualRefreshToken").value = "";
|
||
document.getElementById("manualExpiresAt").value = "";
|
||
updateAuthStatusUI();
|
||
showToast("🗑️ توکنها پاک شدند", "info");
|
||
});
|
||
|
||
/* =========================================================================
|
||
Provider Service Generator
|
||
========================================================================= */
|
||
function renderProviderService(ctrl, content) {
|
||
const providerCode = generateProviderService(ctrl.name, ctrl.endpoints);
|
||
AppState.generatedProviderCode = providerCode.code;
|
||
AppState.generatedProviderFilename = providerCode.filename;
|
||
content.innerHTML = `
|
||
<div class="content-section">
|
||
<div class="section-header"><div class="section-icon">⚙️</div><div class="section-title"><h3>Service برای کنترلر ${ctrl.name}</h3></div></div>
|
||
<div style="display: flex; gap: 8px; margin-bottom: 14px; flex-wrap: wrap;">
|
||
<button type="button" class="btn btn-success" onclick="downloadProviderFile()"><span>💾</span><span>دانلود ${providerCode.filename}</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="openProviderModal()"><span>👁️</span><span>مشاهده کامل</span></button>
|
||
<button type="button" class="btn btn-ghost" style="background: var(--column-bg); color: var(--text); border: 1px solid var(--border);" onclick="copyProviderCode()"><span>📋</span><span>کپی</span></button>
|
||
</div>
|
||
<div class="code-block-header"><span>📄 ${providerCode.filename}</span><span style="color: var(--accent);">TypeScript | ${providerCode.methodCount} متد</span></div>
|
||
<div class="code-block"><pre>${highlightTS(providerCode.code)}</pre></div>
|
||
</div>`;
|
||
}
|
||
|
||
function generateProviderService(controllerName, endpoints) {
|
||
const filtered = endpoints.filter(
|
||
(e) => !e.path.toLowerCase().includes("/test/"),
|
||
);
|
||
if (filtered.length === 0)
|
||
return {
|
||
code: "// هیچ اندپوینتی یافت نشد\n",
|
||
filename: `${controllerName}.service.ts`,
|
||
methodCount: 0,
|
||
};
|
||
const className = `X${controllerName}Service`;
|
||
const routeEnumName = `X${controllerName}ServiceRoute`;
|
||
const paramEnumName = `X${controllerName}Param`;
|
||
const endPointEnumValue = `XApiEndPoint.${controllerName}sService`;
|
||
const basePath = extractBasePath(filtered);
|
||
const routeEntries = [],
|
||
paramEntries = new Map(),
|
||
methods = [];
|
||
filtered.forEach((ep) => {
|
||
const routeInfo = extractRouteInfo(ep.path, basePath);
|
||
if (!routeEntries.find((r) => r.name === routeInfo.routeName))
|
||
routeEntries.push(routeInfo);
|
||
extractPathParams(ep.path, basePath).forEach((p) =>
|
||
paramEntries.set(p.name, p.name),
|
||
);
|
||
(ep.operation.parameters || [])
|
||
.filter((p) => p.in === "query")
|
||
.forEach((p) => paramEntries.set(p.name, p.name));
|
||
methods.push(
|
||
generateMethod(
|
||
ep,
|
||
routeInfo.routeName,
|
||
routeInfo.routeValue,
|
||
basePath,
|
||
),
|
||
);
|
||
});
|
||
const imports = generateImports(controllerName, methods);
|
||
const routeEnum = generateRouteEnum(routeEnumName, routeEntries);
|
||
const paramEnum = generateParamEnum(
|
||
paramEnumName,
|
||
Array.from(paramEntries.values()),
|
||
);
|
||
const classCode = generateProviderClass(
|
||
className,
|
||
routeEnumName,
|
||
paramEnumName,
|
||
endPointEnumValue,
|
||
controllerName,
|
||
methods,
|
||
);
|
||
return {
|
||
code: `${imports}\n\n${routeEnum}\n\n${paramEnum}\n\n${classCode}\n`,
|
||
filename: `${controllerName}.service.ts`,
|
||
methodCount: methods.length,
|
||
};
|
||
}
|
||
|
||
function extractBasePath(endpoints) {
|
||
const firstPath = endpoints[0].path;
|
||
const parts = firstPath.split("/").filter((p) => p);
|
||
for (let i = 0; i < parts.length; i++) {
|
||
const part = parts[i];
|
||
if (
|
||
part.endsWith("Provider") ||
|
||
part === "Account" ||
|
||
part === "Startup" ||
|
||
part === "TestIdentity" ||
|
||
part === "TestFeatures"
|
||
)
|
||
return "/" + parts.slice(0, i + 1).join("/");
|
||
}
|
||
return "";
|
||
}
|
||
|
||
function extractRouteInfo(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath))
|
||
relativePath = path.substring(basePath.length);
|
||
if (relativePath.startsWith("/"))
|
||
relativePath = relativePath.substring(1);
|
||
let routeName,
|
||
routeValue = relativePath;
|
||
if (relativePath === "" || relativePath === "/") routeName = "All";
|
||
else {
|
||
const segments = relativePath.split("/").filter((s) => s);
|
||
routeName = segments
|
||
.map((s) =>
|
||
s.startsWith("{") && s.endsWith("}")
|
||
? "ById"
|
||
: s.charAt(0).toUpperCase() + s.slice(1),
|
||
)
|
||
.join("");
|
||
if (routeName === "ById") routeName = "Get";
|
||
}
|
||
return { routeName, routeValue };
|
||
}
|
||
|
||
function extractPathParams(path, basePath) {
|
||
let relativePath = path;
|
||
if (basePath && path.startsWith(basePath))
|
||
relativePath = path.substring(basePath.length);
|
||
const params = [];
|
||
for (const match of relativePath.matchAll(/\{([^}]+)\}/g))
|
||
if (match[1] !== "version") params.push({ name: match[1] });
|
||
return params;
|
||
}
|
||
|
||
function generateRouteEnum(enumName, entries) {
|
||
const lines = entries
|
||
.map((e) => `${e.name} = '${e.value}',`)
|
||
.join("\n ");
|
||
return `/**\n* All Available EndPoint Routes ...\n*/\nexport enum ${enumName} {\n ${lines}\n}`;
|
||
}
|
||
|
||
function generateParamEnum(enumName, paramNames) {
|
||
if (paramNames.length === 0)
|
||
return `/**\n* All Params ...\n*/\nexport enum ${enumName} {\n // No params\n}`;
|
||
const lines = paramNames
|
||
.map((p) => `${p.charAt(0).toUpperCase() + p.slice(1)} = '${p}',`)
|
||
.join("\n ");
|
||
return `/**\n* All Params ...\n*/\nexport enum ${enumName} {\n ${lines}\n}`;
|
||
}
|
||
|
||
function generateImports(controllerName, methods) {
|
||
const needsFormData = methods.some((m) => m.isFormData);
|
||
const needsConnectionId = methods.some((m) => m.hasConnectionId);
|
||
const needsFillRouteParams = methods.some((m) => m.hasPathParams);
|
||
const needsXQuery = methods.some((m) => m.isXQuery);
|
||
const coreImports = ["XValidators"];
|
||
if (needsFormData) coreImports.push("toArray", "hasChild");
|
||
let imports = `import {\n ${coreImports.join(",\n ")},\n} from 'x-framework-core';\nimport {\n HttpEvent, HttpClient, HttpParams, HttpHeaders, HttpResponse,\n} from '@angular/common/http';\nimport {\n X_API_CONFIG, XBaseApiService, XApiConfiguration${needsXQuery ? ", XQueryDto, XQueryResultDto" : ""},\n} from 'x-framework-identity-sdk';\nimport { Observable } from 'rxjs';\nimport { Router } from '@angular/router';\nimport { Inject, Injectable } from '@angular/core';`;
|
||
if (needsFillRouteParams)
|
||
imports += `\nimport { fillRouteParams } from '../../tools/x-route.tools';`;
|
||
imports += `\nimport { XApiEndPoint } from '../../typings/x-endpoint.typings';`;
|
||
imports += `\nimport { X${controllerName}ServiceRoute, X${controllerName}Param } from '../x-${toKebabCase(controllerName)}.typings';`;
|
||
if (needsConnectionId)
|
||
imports += `\nimport { applyConnectionIdToHeader } from '../../typings/x-push-provider.typings';`;
|
||
imports += `\nimport { X_SAHERELM_API_SDK_CONFIG } from '../../tokens/x-injectable-tokens';`;
|
||
imports += `\nimport { XSaherElmApiSDKConfig } from '../../config/x-saherelm-api-sdk.config';`;
|
||
return imports;
|
||
}
|
||
|
||
function generateMethod(endpoint, routeName, routeValue, basePath) {
|
||
const method = endpoint.method;
|
||
const operation = endpoint.operation;
|
||
const parameters = operation.parameters || [];
|
||
const pathParams = parameters.filter(
|
||
(p) => p.in === "path" && p.name !== "version",
|
||
);
|
||
const queryParams = parameters.filter((p) => p.in === "query");
|
||
let bodyType = null,
|
||
bodyParamName = null,
|
||
isFormData = false;
|
||
const requestBody = operation.requestBody;
|
||
if (requestBody?.content) {
|
||
if (requestBody.content["multipart/form-data"]) {
|
||
isFormData = true;
|
||
bodyType = "FormData";
|
||
bodyParamName = "formData";
|
||
} else if (requestBody.content["application/json"]) {
|
||
bodyType = resolveType(
|
||
requestBody.content["application/json"].schema,
|
||
);
|
||
bodyParamName = "model";
|
||
}
|
||
}
|
||
let returnType = "void";
|
||
const successResponse = operation.responses?.["200"];
|
||
if (successResponse?.content?.["application/json"]?.schema)
|
||
returnType = resolveType(
|
||
successResponse.content["application/json"].schema,
|
||
);
|
||
const isXQuery = queryParams.some((p) =>
|
||
[
|
||
"Filter",
|
||
"ContainsDetail",
|
||
"SortBy",
|
||
"IsAscending",
|
||
"Page",
|
||
"PageSize",
|
||
].includes(p.name),
|
||
);
|
||
const hasConnectionId = ["post", "put", "delete", "patch"].includes(
|
||
method,
|
||
);
|
||
const methodName = toCamelCase(routeName);
|
||
return {
|
||
methodName,
|
||
httpMethod: method,
|
||
routeName,
|
||
routeValue,
|
||
summary: (operation.summary || "").replace(/\r?\n/g, " ").trim(),
|
||
pathParams,
|
||
queryParams,
|
||
bodyType,
|
||
bodyParamName,
|
||
returnType,
|
||
isFormData,
|
||
isXQuery,
|
||
hasConnectionId,
|
||
hasPathParams: pathParams.length > 0,
|
||
};
|
||
}
|
||
|
||
function resolveType(schema) {
|
||
if (!schema) return "any";
|
||
if (schema.$ref)
|
||
return schema.$ref.replace("#/components/schemas/", "");
|
||
if (schema.type === "array")
|
||
return `Array<${resolveType(schema.items)}>`;
|
||
if (schema.type === "string") {
|
||
if (schema.format === "date-time") return "Date";
|
||
if (schema.format === "binary") return "File";
|
||
return "string";
|
||
}
|
||
if (schema.type === "integer" || schema.type === "number")
|
||
return "number";
|
||
if (schema.type === "boolean") return "boolean";
|
||
return "any";
|
||
}
|
||
|
||
function generateProviderClass(
|
||
className,
|
||
routeEnumName,
|
||
paramEnumName,
|
||
endPointEnumValue,
|
||
controllerName,
|
||
methods,
|
||
) {
|
||
const methodsCode = methods
|
||
.map((m) => generateMethodCode(m, routeEnumName, paramEnumName))
|
||
.join("\n\n");
|
||
return `/**\n* Provides all Provider Actions as a Service ...\n*/\n@Injectable({\n providedIn: 'root',\n})\nexport class ${className} extends XBaseApiService {\n //\n //#region Constructor ...\n constructor(\n protected router: Router,\n protected httpClient: HttpClient,\n @Inject(X_SAHERELM_API_SDK_CONFIG) config: XSaherElmApiSDKConfig,\n @Inject(X_API_CONFIG) apiConfig: XApiConfiguration\n ) {\n super(${endPointEnumValue}, true, true, httpClient, config, apiConfig);\n }\n //#endregion\n //\n //#region Actions ...\n //\n${methodsCode}\n //#endregion\n}`;
|
||
}
|
||
|
||
function generateMethodCode(methodInfo, routeEnumName, paramEnumName) {
|
||
const {
|
||
methodName,
|
||
httpMethod,
|
||
routeName,
|
||
summary,
|
||
pathParams,
|
||
queryParams,
|
||
bodyType,
|
||
bodyParamName,
|
||
returnType,
|
||
isFormData,
|
||
isXQuery,
|
||
hasConnectionId,
|
||
hasPathParams,
|
||
} = methodInfo;
|
||
const signatureParams = [];
|
||
pathParams.forEach((p) =>
|
||
signatureParams.push({
|
||
name: p.name,
|
||
type: "string",
|
||
required: true,
|
||
}),
|
||
);
|
||
if (bodyType && !isFormData)
|
||
signatureParams.push({
|
||
name: bodyParamName,
|
||
type: bodyType,
|
||
required: true,
|
||
});
|
||
if (!isXQuery)
|
||
queryParams.forEach((p) =>
|
||
signatureParams.push({
|
||
name: p.name,
|
||
type: "string",
|
||
required: p.required || false,
|
||
}),
|
||
);
|
||
else
|
||
signatureParams.push({
|
||
name: "query",
|
||
type: "XQueryDto",
|
||
required: true,
|
||
});
|
||
if (hasConnectionId)
|
||
signatureParams.push({
|
||
name: "connectionId",
|
||
type: "string",
|
||
required: false,
|
||
});
|
||
let jsDoc = `/**\n`;
|
||
if (summary) jsDoc += `* ${summary}\n`;
|
||
signatureParams.forEach((p) => (jsDoc += `*\n* @param ${p.name}\n`));
|
||
jsDoc += `*\n* @param observe\n* @param reportProgress\n*/`;
|
||
const overloads = [];
|
||
["body", "response", "events"].forEach((obs) => {
|
||
let obsReturnType =
|
||
obs === "body"
|
||
? returnType
|
||
: obs === "response"
|
||
? `HttpResponse<${returnType}>`
|
||
: `HttpEvent<${returnType}>`;
|
||
const obsParams = signatureParams.map(
|
||
(p) => `${p.name}${p.required ? "" : "?"}: ${p.type}`,
|
||
);
|
||
obsParams.push(`observe?: '${obs}'`);
|
||
obsParams.push(`reportProgress?: boolean`);
|
||
overloads.push(
|
||
` public ${methodName}(\n ${obsParams.join(",\n ")}\n ): Observable<${obsReturnType}>;`,
|
||
);
|
||
});
|
||
const finalParams = signatureParams.map(
|
||
(p) => `${p.name}${p.required ? "" : "?"}: ${p.type}`,
|
||
);
|
||
finalParams.push(`observe: any = 'body'`);
|
||
finalParams.push(`reportProgress: boolean = false`);
|
||
const methodBody = generateMethodBody(
|
||
methodInfo,
|
||
routeEnumName,
|
||
paramEnumName,
|
||
);
|
||
return `${jsDoc}\n${overloads.join("\n")}\n public ${methodName}(\n ${finalParams.join(",\n ")}\n ): Observable<any> {\n${methodBody}\n }`;
|
||
}
|
||
|
||
function generateMethodBody(methodInfo, routeEnumName, paramEnumName) {
|
||
const {
|
||
httpMethod,
|
||
routeName,
|
||
pathParams,
|
||
queryParams,
|
||
bodyType,
|
||
bodyParamName,
|
||
returnType,
|
||
isFormData,
|
||
isXQuery,
|
||
hasConnectionId,
|
||
hasPathParams,
|
||
} = methodInfo;
|
||
let body = "";
|
||
const validations = [];
|
||
pathParams.forEach((p) =>
|
||
validations.push(`XValidators.validateNotEmpty(${p.name});`),
|
||
);
|
||
if (bodyType && !isFormData)
|
||
validations.push(`XValidators.validateNotNull(${bodyParamName});`);
|
||
if (validations.length > 0) {
|
||
body += ` //\n // Validate Args ...\n`;
|
||
validations.forEach((v) => (body += ` ${v}\n`));
|
||
}
|
||
body += ` //\n // Base Requirements ...\n let params: HttpParams = null;\n let headers: HttpHeaders = this.defaultHeaders;\n //\n // Authentication ...\n headers = this.addAuthentication(headers);\n`;
|
||
if (httpMethod !== "get" && !isFormData) {
|
||
body += ` headers = this.addAcceptJson(headers);\n headers = this.addContentType(headers);\n`;
|
||
}
|
||
if (hasConnectionId)
|
||
body += ` headers = applyConnectionIdToHeader(connectionId, headers);\n`;
|
||
body += ` //\n // Prepare Endpoint\n`;
|
||
if (hasPathParams) {
|
||
const paramMappings = pathParams
|
||
.map(
|
||
(p) =>
|
||
` {\n key: ${paramEnumName}.${p.name.charAt(0).toUpperCase() + p.name.slice(1)},\n value: ${p.name}.toString(),\n }`,
|
||
)
|
||
.join(",\n");
|
||
body += ` const endPointPath = fillRouteParams(\n this.getActionRoute(${routeEnumName}.${routeName}),\n [\n${paramMappings}\n ]\n );\n`;
|
||
} else {
|
||
body += ` const endPointPath = this.getActionRoute(${routeEnumName}.${routeName});\n`;
|
||
}
|
||
if (isXQuery)
|
||
body += ` params = this.generateXQueryHttpParams(query);\n`;
|
||
body += ` //\n // Prepare Result ...\n`;
|
||
let bodyArg = "";
|
||
if (isFormData) bodyArg = "formData";
|
||
else if (bodyType && httpMethod !== "get" && httpMethod !== "delete")
|
||
bodyArg = bodyParamName;
|
||
if (bodyArg)
|
||
body += ` return this.httpClient.${httpMethod}<${returnType}>(endPointPath, ${bodyArg}, {\n`;
|
||
else
|
||
body += ` return this.httpClient.${httpMethod}<${returnType}>(endPointPath, {\n`;
|
||
body += ` withCredentials: this.apiConfig.withCredentials,\n headers,\n observe,\n params,\n reportProgress,\n });\n`;
|
||
return body;
|
||
}
|
||
|
||
function openProviderModal() {
|
||
document.getElementById("providerModalTitle").textContent =
|
||
`Service - ${AppState.activeController}`;
|
||
document.getElementById("providerModalBody").innerHTML =
|
||
`<div class="code-block-header"><span>📄 ${AppState.generatedProviderFilename}</span><span style="color: var(--accent);">TypeScript</span></div><div class="code-block"><pre>${highlightTS(AppState.generatedProviderCode)}</pre></div>`;
|
||
document.getElementById("providerModal").classList.add("active");
|
||
}
|
||
|
||
function downloadProviderFile() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
const blob = new Blob([AppState.generatedProviderCode], {
|
||
type: "text/typescript;charset=utf-8",
|
||
});
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = AppState.generatedProviderFilename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
showToast(
|
||
`فایل ${AppState.generatedProviderFilename} دانلود شد`,
|
||
"success",
|
||
);
|
||
}
|
||
|
||
function copyProviderCode() {
|
||
if (!AppState.generatedProviderCode) return;
|
||
navigator.clipboard
|
||
.writeText(AppState.generatedProviderCode)
|
||
.then(() => showToast("کد کپی شد", "success"));
|
||
}
|
||
|
||
document
|
||
.querySelectorAll("[data-close-provider]")
|
||
.forEach((btn) =>
|
||
btn.addEventListener("click", () =>
|
||
document.getElementById("providerModal").classList.remove("active"),
|
||
),
|
||
);
|
||
|
||
/* =========================================================================
|
||
DTO Generator
|
||
========================================================================= */
|
||
function openModelModal(modelName) {
|
||
AppState.selectedModel = modelName;
|
||
const schema = AppState.allSchemas[modelName];
|
||
if (!schema) {
|
||
showToast("مدل یافت نشد", "error");
|
||
return;
|
||
}
|
||
document.getElementById("modelModalTitle").textContent =
|
||
`مدل ${modelName}`;
|
||
const body = document.getElementById("modelModalBody");
|
||
const tsCode = generateTypeScriptDto(modelName, schema);
|
||
AppState.generatedCode = tsCode;
|
||
const props = schema.properties || {};
|
||
const propsList = Object.keys(props)
|
||
.map((name) => {
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const required = (schema.required || []).includes(name);
|
||
return `<tr><td style="font-family: 'Fira Code', monospace; font-size: 12px; direction: ltr; text-align: left;">${name}</td><td style="font-family: 'Fira Code', monospace; font-size: 12px; color: var(--info); direction: ltr; text-align: left;">${tsType}</td><td>${required ? '<span style="color: var(--danger); font-weight: 700;">ضروری</span>' : '<span style="color: var(--text-muted);">اختیاری</span>'}</td></tr>`;
|
||
})
|
||
.join("");
|
||
body.innerHTML = `<table class="endpoints-table" style="margin-bottom: 20px;"><thead><tr><th>فیلد</th><th>نوع</th><th>وضعیت</th></tr></thead><tbody>${propsList}</tbody></table><div class="code-block-header"><span>📄 ${toFileName(modelName)}.ts</span><span style="color: var(--accent);">TypeScript</span></div><div class="code-block"><pre>${highlightTS(tsCode)}</pre></div>`;
|
||
document.getElementById("modelModal").classList.add("active");
|
||
}
|
||
|
||
document
|
||
.querySelectorAll("[data-close-modal]")
|
||
.forEach((btn) =>
|
||
btn.addEventListener("click", () =>
|
||
document.getElementById("modelModal").classList.remove("active"),
|
||
),
|
||
);
|
||
document
|
||
.getElementById("downloadDtoBtn")
|
||
.addEventListener("click", () => {
|
||
if (!AppState.selectedModel || !AppState.generatedCode) return;
|
||
const filename = toFileName(AppState.selectedModel) + ".ts";
|
||
const blob = new Blob([AppState.generatedCode], {
|
||
type: "text/typescript;charset=utf-8",
|
||
});
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement("a");
|
||
a.href = url;
|
||
a.download = filename;
|
||
document.body.appendChild(a);
|
||
a.click();
|
||
document.body.removeChild(a);
|
||
URL.revokeObjectURL(url);
|
||
showToast(`فایل ${filename} دانلود شد`, "success");
|
||
});
|
||
document.getElementById("copyCodeBtn").addEventListener("click", () => {
|
||
if (!AppState.generatedCode) return;
|
||
navigator.clipboard
|
||
.writeText(AppState.generatedCode)
|
||
.then(() => showToast("کد کپی شد", "success"));
|
||
});
|
||
|
||
function generateTypeScriptDto(modelName, schema) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
if (schema.enum) return generateEnum(modelName, schema);
|
||
const parentType =
|
||
props.id?.type === "integer" ? "XBaseNumberIDDto" : "XBaseDto";
|
||
const interfaceCode = generateInterface(modelName, schema, parentType);
|
||
const defaultObjName = "default" + modelName.replace(/^X/, "");
|
||
const defaultObjCode = generateDefaultObject(
|
||
modelName,
|
||
props,
|
||
defaultObjName,
|
||
parentType,
|
||
);
|
||
const prepareFuncCode = generatePrepareFunction(
|
||
modelName,
|
||
props,
|
||
defaultObjName,
|
||
);
|
||
const isDefaultCode = `/**\n * Check Model is Default ...\n */\nexport function isDefault${modelName.replace(/^X/, "")}(model?: ${modelName}) {\n return isSameObject(prepare${modelName.replace(/^X/, "")}Fields(model), ${defaultObjName});\n}`;
|
||
const typeGuardCode = generateTypeGuard(
|
||
modelName,
|
||
props,
|
||
requiredFields,
|
||
);
|
||
return `${interfaceCode}\n\n${defaultObjCode}\n\n${prepareFuncCode}\n\n${isDefaultCode}\n\n${typeGuardCode}\n`;
|
||
}
|
||
|
||
function generateInterface(modelName, schema, parentType) {
|
||
const props = schema.properties || {};
|
||
const requiredFields = schema.required || [];
|
||
const fields = Object.keys(props)
|
||
.map((name) => {
|
||
if (["id", "deleted"].includes(name)) return "";
|
||
const prop = props[name];
|
||
const tsType = resolveType(prop);
|
||
const optional = requiredFields.includes(name) ? "" : "?";
|
||
return ` ${name}${optional}: ${tsType};`;
|
||
})
|
||
.filter((f) => f)
|
||
.join("\n");
|
||
return `/**\n * ${schema.description || `Model ${modelName}`}\n */\nexport interface ${modelName} extends ${parentType} {\n${fields}\n}`;
|
||
}
|
||
|
||
function generateDefaultObject(
|
||
modelName,
|
||
props,
|
||
defaultObjName,
|
||
parentType,
|
||
) {
|
||
const fields = Object.keys(props)
|
||
.map((name) => {
|
||
if (["id", "deleted"].includes(name)) return "";
|
||
const prop = props[name];
|
||
let defaultValue = "undefined";
|
||
if (prop.type === "string")
|
||
defaultValue = prop.format === "date-time" ? "undefined" : "''";
|
||
else if (prop.type === "integer" || prop.type === "number")
|
||
defaultValue = "0";
|
||
else if (prop.type === "boolean") defaultValue = "false";
|
||
else if (prop.type === "array") defaultValue = "[]";
|
||
return ` ${name}: ${defaultValue},`;
|
||
})
|
||
.filter((f) => f)
|
||
.join("\n");
|
||
return `/**\n * Default model ...\n */\nexport const ${defaultObjName}: ${modelName} = {\n${fields}\n};`;
|
||
}
|
||
|
||
function generatePrepareFunction(modelName, props, defaultObjName) {
|
||
const fields = Object.keys(props)
|
||
.map((name) => {
|
||
if (["id", "deleted"].includes(name)) return "";
|
||
const prop = props[name];
|
||
let check;
|
||
if (prop.type === "array")
|
||
check = `!isNullOrUndefined(model.${name}) && !hasChild(model.${name}) ? [...model.${name}] : ${defaultObjName}.${name}`;
|
||
else if (prop.type === "string" && prop.format !== "date-time")
|
||
check = `!isNullOrEmptyString(model.${name}) ? model.${name} : ${defaultObjName}.${name}`;
|
||
else
|
||
check = `!isNullOrUndefined(model.${name}) ? model.${name} : ${defaultObjName}.${name}`;
|
||
return ` ${name}: ${check},`;
|
||
})
|
||
.filter((f) => f)
|
||
.join("\n");
|
||
return `/**\n * Preparing Dto Fields ...\n */\nexport function prepare${modelName.replace(/^X/, "")}Fields(model?: ${modelName}) {\n if (isNullOrUndefined(model)) model = { ...${defaultObjName} };\n model = {\n${fields}\n };\n return model;\n}`;
|
||
}
|
||
|
||
function generateTypeGuard(modelName, props, requiredFields) {
|
||
let guardFields = requiredFields.filter((f) => f !== "deleted");
|
||
if (guardFields.length === 0) {
|
||
guardFields = Object.keys(props)
|
||
.filter(
|
||
(n) =>
|
||
!["deleted"].includes(n) &&
|
||
props[n] &&
|
||
!props[n].$ref &&
|
||
props[n].type !== "array" &&
|
||
["string", "integer", "number", "boolean"].includes(
|
||
props[n].type,
|
||
),
|
||
)
|
||
.slice(0, 5);
|
||
}
|
||
const fieldsList = guardFields.map((f) => ` '${f}',`).join("\n");
|
||
return `/**\n * Model Type Guard ...\n */\nexport const is${modelName} = typeGuard<${modelName}>([\n${fieldsList}\n]);`;
|
||
}
|
||
|
||
function generateEnum(modelName, schema) {
|
||
const values = schema.enum || [];
|
||
const isInt = values.length > 0 && typeof values[0] === "number";
|
||
const entries = values
|
||
.map((v) =>
|
||
isInt
|
||
? ` ${v} = ${v},`
|
||
: ` ${String(v).replace(/[^a-zA-Z0-9_]/g, "_")} = '${v}',`,
|
||
)
|
||
.join("\n");
|
||
return `/**\n * ${schema.description || `Enum ${modelName}`}\n */\nexport enum ${modelName} {\n${entries}\n}`;
|
||
}
|
||
|
||
function toFileName(modelName) {
|
||
return modelName
|
||
.replace(/^X/, "x-")
|
||
.replace(/([a-z])([A-Z])/g, "$1-$2")
|
||
.toLowerCase();
|
||
}
|
||
|
||
/* =========================================================================
|
||
Syntax Highlighting
|
||
========================================================================= */
|
||
function highlightTS(code) {
|
||
const tokens = [];
|
||
let remaining = code;
|
||
while (remaining.length > 0) {
|
||
let matched = false;
|
||
if (remaining.startsWith("/*")) {
|
||
const endIdx = remaining.indexOf("*/");
|
||
if (endIdx !== -1) {
|
||
tokens.push({
|
||
type: "comment",
|
||
content: remaining.substring(0, endIdx + 2),
|
||
});
|
||
remaining = remaining.substring(endIdx + 2);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched && remaining.startsWith("//")) {
|
||
const endIdx = remaining.indexOf("\n");
|
||
if (endIdx !== -1) {
|
||
tokens.push({
|
||
type: "comment",
|
||
content: remaining.substring(0, endIdx),
|
||
});
|
||
remaining = remaining.substring(endIdx);
|
||
matched = true;
|
||
} else {
|
||
tokens.push({ type: "comment", content: remaining });
|
||
remaining = "";
|
||
matched = true;
|
||
}
|
||
}
|
||
if (
|
||
!matched &&
|
||
(remaining.startsWith("'") ||
|
||
remaining.startsWith('"') ||
|
||
remaining.startsWith("`"))
|
||
) {
|
||
const quote = remaining[0];
|
||
let idx = 1;
|
||
while (idx < remaining.length) {
|
||
if (remaining[idx] === "\\") idx += 2;
|
||
else if (remaining[idx] === quote) {
|
||
idx++;
|
||
break;
|
||
} else idx++;
|
||
}
|
||
tokens.push({
|
||
type: "string",
|
||
content: remaining.substring(0, idx),
|
||
});
|
||
remaining = remaining.substring(idx);
|
||
matched = true;
|
||
}
|
||
if (!matched && /^[0-9]/.test(remaining)) {
|
||
const match = remaining.match(/^[0-9]+(\.[0-9]+)?/);
|
||
if (match) {
|
||
tokens.push({ type: "number", content: match[0] });
|
||
remaining = remaining.substring(match[0].length);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched && /[a-zA-Z_$]/.test(remaining[0])) {
|
||
const match = remaining.match(/^[a-zA-Z_$][a-zA-Z0-9_$]*/);
|
||
if (match) {
|
||
const word = match[0];
|
||
const keywords = [
|
||
"export",
|
||
"interface",
|
||
"const",
|
||
"function",
|
||
"enum",
|
||
"extends",
|
||
"import",
|
||
"from",
|
||
"return",
|
||
"if",
|
||
"public",
|
||
"private",
|
||
"protected",
|
||
"class",
|
||
"constructor",
|
||
];
|
||
const types = [
|
||
"string",
|
||
"number",
|
||
"boolean",
|
||
"any",
|
||
"void",
|
||
"Date",
|
||
"File",
|
||
"Array",
|
||
"Observable",
|
||
"HttpResponse",
|
||
"HttpEvent",
|
||
"HttpParams",
|
||
"HttpHeaders",
|
||
"FormData",
|
||
];
|
||
if (keywords.includes(word))
|
||
tokens.push({ type: "keyword", content: word });
|
||
else if (types.includes(word) || /^[A-Z]/.test(word))
|
||
tokens.push({ type: "type", content: word });
|
||
else tokens.push({ type: "identifier", content: word });
|
||
remaining = remaining.substring(match[0].length);
|
||
matched = true;
|
||
}
|
||
}
|
||
if (!matched) {
|
||
tokens.push({ type: "plain", content: remaining[0] });
|
||
remaining = remaining.substring(1);
|
||
}
|
||
}
|
||
return tokens
|
||
.map((t) => {
|
||
const escaped = escapeHtml(t.content);
|
||
if (t.type === "comment")
|
||
return `<span class="code-comment">${escaped}</span>`;
|
||
if (t.type === "string")
|
||
return `<span class="code-string">${escaped}</span>`;
|
||
if (t.type === "number")
|
||
return `<span class="code-number">${escaped}</span>`;
|
||
if (t.type === "keyword")
|
||
return `<span class="code-keyword">${escaped}</span>`;
|
||
if (t.type === "type")
|
||
return `<span class="code-type">${escaped}</span>`;
|
||
return escaped;
|
||
})
|
||
.join("");
|
||
}
|
||
|
||
// ============ Initialize ============
|
||
initGlobalSettings();
|
||
showToast(
|
||
"XFramework Backend SDK Manager آماده استفاده است",
|
||
"success",
|
||
4000,
|
||
);
|
||
</script>
|
||
</body>
|
||
</html>
|