@tekrom/tsoft-app-gate 0.1.1 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +233 -29
- package/dist/client.d.ts +102 -0
- package/dist/client.js +205 -0
- package/dist/index.d.ts +4 -17
- package/dist/index.js +2 -21
- package/dist/protocol.d.ts +84 -0
- package/dist/protocol.js +5 -0
- package/dist/tsoft-app-gate.min.js +1 -0
- package/package.json +11 -4
package/README.md
CHANGED
|
@@ -1,50 +1,254 @@
|
|
|
1
1
|
# T-Soft App Gate
|
|
2
2
|
|
|
3
|
-
T-Soft App
|
|
3
|
+
T-Soft paneli içinde (iframe) açılan uygulamalar için **App Bridge** istemcisi. Uygulama, panelden oturum token'ı alır; panelin bildirim, onay penceresi, ürün seçici ve gezinme bileşenlerini kullanır; iframe yüksekliğini ayarlar. Tüm çağrılar promise döner, zaman aşımına ve hata kodlarına sahiptir.
|
|
4
4
|
|
|
5
|
-
## Özellikler
|
|
6
|
-
- `createApp` ile API anahtarınıza ve mağaza bilgilerinize bağlı bir köprü kurar.
|
|
7
|
-
- `setNavigationMenu` çağrısı ile T-Soft yönetim menüsünü uygulamanıza göre güncellemenizi sağlar.
|
|
8
|
-
- `showToast` sayesinde panel üzerindeki kullanıcıya başarı/başarısızlık bildirimleri gönderebilirsiniz.
|
|
9
|
-
- Tarayıcı `postMessage` altyapısını kullanır, böylece uygulamanız iframe içinde güvenle çalışabilir.
|
|
10
|
-
|
|
11
|
-
## Kurulum
|
|
12
5
|
```bash
|
|
13
6
|
npm install @tekrom/tsoft-app-gate
|
|
14
7
|
```
|
|
15
8
|
|
|
16
|
-
|
|
17
|
-
|
|
9
|
+
Paketleyici kullanmıyorsanız tarayıcı derlemesini `<script>` ile yükleyin; aynı API `TSoftAppGate` global'i altında gelir:
|
|
10
|
+
|
|
11
|
+
```html
|
|
12
|
+
<script src="https://cdn.jsdelivr.net/npm/@tekrom/tsoft-app-gate@0.3/dist/tsoft-app-gate.min.js"></script>
|
|
13
|
+
<script>
|
|
14
|
+
const app = TSoftAppGate.createApp();
|
|
15
|
+
</script>
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Sürümü sabitleyin (`@0.3` ya da tam sürüm); üretimde dosyayı kendi sunucunuzdan sunmak da mümkündür.
|
|
19
|
+
|
|
20
|
+
## Hızlı başlangıç
|
|
18
21
|
|
|
19
22
|
```ts
|
|
20
|
-
import { createApp,
|
|
23
|
+
import { createApp, isEmbedded, AppBridgeError } from '@tekrom/tsoft-app-gate';
|
|
24
|
+
|
|
25
|
+
if (!isEmbedded()) {
|
|
26
|
+
// Panel dışında açıldı: kendi giriş akışınızı gösterin.
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const app = createApp();
|
|
30
|
+
|
|
31
|
+
app.claims?.store_id; // hangi mağaza (doğrulamayı sunucuda yapın)
|
|
32
|
+
|
|
33
|
+
// Arka uca giden her istekte taze token kullanın.
|
|
34
|
+
const token = await app.getSessionToken();
|
|
35
|
+
await fetch('/api/settings', { headers: { Authorization: `Bearer ${token}` } });
|
|
36
|
+
|
|
37
|
+
await app.toast('Ayarlar kaydedildi');
|
|
38
|
+
|
|
39
|
+
if (await app.confirm({ title: 'Kampanyayı sil', message: 'Bu işlem geri alınamaz.', confirmText: 'Sil' })) {
|
|
40
|
+
// ...
|
|
41
|
+
}
|
|
21
42
|
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
43
|
+
try {
|
|
44
|
+
const { ids, cancelled } = await app.pickResource({ type: 'product', multiple: true });
|
|
45
|
+
} catch (error) {
|
|
46
|
+
if (error instanceof AppBridgeError && error.code === 'missing_scope') {
|
|
47
|
+
// Uygulamanın read_products kapsamı yok.
|
|
48
|
+
}
|
|
49
|
+
}
|
|
27
50
|
|
|
28
|
-
|
|
29
|
-
{ label: 'Siparişler', path: '/orders' },
|
|
30
|
-
{ label: 'Kampanyalar', path: '/campaigns' },
|
|
31
|
-
]);
|
|
51
|
+
await app.navigate.panel('order', 1042);
|
|
32
52
|
|
|
33
|
-
|
|
53
|
+
const stop = app.autoResize();
|
|
34
54
|
```
|
|
35
55
|
|
|
56
|
+
## API
|
|
57
|
+
|
|
58
|
+
### `createApp(options?)`
|
|
59
|
+
|
|
60
|
+
| Seçenek | Varsayılan | Açıklama |
|
|
61
|
+
|---|---|---|
|
|
62
|
+
| `panelOrigin` | otomatik | Panelin origin'i. Verilmezse `location.ancestorOrigins`, yoksa `document.referrer` kullanılır (panel iframe'i `referrerpolicy="strict-origin"` ile açar) ve T-Soft panel alan adlarından biri olmalıdır. Elle verilen değer denetlenmez; yalnız yerel geliştirmede kullanın. |
|
|
63
|
+
| `timeout` | `10000` | Kullanıcı etkileşimi beklemeyen isteklerin zaman aşımı (ms). |
|
|
64
|
+
|
|
65
|
+
Panel alan adları `PANEL_ORIGIN_PATTERN` ile denetlenir: `tsoftpanel.com`, `tsoftpanel.net`, `paneltsoft.com` ve bunların alt alan adları, yalnız `https`. Böylece uygulamanızı başka bir siteye gömen biri panel gibi yanıt veremez.
|
|
66
|
+
|
|
67
|
+
Uygulama bir iframe içinde değilse ya da üst pencere bir T-Soft paneli değilse `AppBridgeError('not_embedded')` fırlatır. Önceden bakmak için `isEmbedded()` kullanın.
|
|
68
|
+
|
|
69
|
+
Dönen nesnede ayrıca şunlar vardır:
|
|
70
|
+
|
|
71
|
+
- `panelOrigin`: Mesajların gönderildiği ve yanıtların kabul edildiği origin.
|
|
72
|
+
- `claims`: Elimizdeki son oturum token'ının içeriği (`store_id`, `dest`, `sub`, `aud`, `exp`…); token yoksa `null`. Token yenilendikçe güncellenir.
|
|
73
|
+
- `installCode`: Panelin kurulumdan hemen sonra eklediği `?code=` değeri; yoksa `null`.
|
|
74
|
+
|
|
75
|
+
### Oturum token'ı
|
|
76
|
+
|
|
77
|
+
```ts
|
|
78
|
+
app.getSessionToken(options?): Promise<string>
|
|
79
|
+
app.getSession(options?): Promise<{ token, claims, expiresAt, scopes }>
|
|
80
|
+
decodeSessionToken(token): SessionClaims | null
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- Panel uygulamayı `?session=<jwt>` ile açar. Bu token süresi dolmamışsa ilk çağrıda panele gidilmeden kullanılır; bu durumda `scopes` `null` olur.
|
|
84
|
+
- Token 60 saniye yaşar. Bitmesine 15 saniyeden az kaldıysa panelden yenisi istenir; aynı anda gelen yenileme çağrıları tek isteğe bağlanır. Her sunucu isteğinden önce `getSessionToken()` çağırmanız yeterlidir.
|
|
85
|
+
- `forceRefresh: true` önbelleği atlar; `scopes` her zaman panelden gelen güncel listeyi içerir.
|
|
86
|
+
- Token ES256 imzalı bir JWT'dir (`iss`, `aud` = uygulama prefix'i, `sub` = panel kullanıcısı, `store_id`, `dest` = mağaza alan adı, `iat`, `nbf`, `exp`, `jti`). İstemci içeriği imza doğrulamadan okur; **imzayı sunucunuzda JWKS ile doğrulayın** (`https://api.tsoftapps.com/api/integration/v3/apps/jwks.json`, ayrıntı: [Panele Gömülü Uygulamalar](https://developer.tsoft.com.tr/uygulama-gelistirme/embedded-uygulamalar)).
|
|
87
|
+
- Oturum token'ı Admin API için değildir; uygulamanın kendi sunucusuyla konuşması içindir.
|
|
88
|
+
|
|
89
|
+
### `toast(message, { variant? })`
|
|
90
|
+
|
|
91
|
+
Panelde bildirim gösterir. `variant`: `'success'` (varsayılan) ya da `'error'`. Mesaj panel tarafında 200 karaktere kesilir; boş mesaj `invalid_payload` döner.
|
|
92
|
+
|
|
93
|
+
### `confirm(message | { message, title?, confirmText? })`
|
|
94
|
+
|
|
95
|
+
Panelin onay penceresini açar. Kullanıcı onaylarsa `true`, vazgeçerse `false` döner. Sınırlar: `message` 500, `title` 100, `confirmText` 40 karakter. Mesaj düz metindir, HTML yorumlanmaz. Kullanıcıyı beklediği için **varsayılan olarak zaman aşımı yoktur**; istenirse `timeout` verilebilir.
|
|
96
|
+
|
|
97
|
+
### `navigate.app(path)`
|
|
98
|
+
|
|
99
|
+
Panel adres çubuğundaki `?path=` değerini uygulama içi yola eşitler. Sayfa yenilendiğinde ya da bağlantı paylaşıldığında uygulama bu yoldan açılır. **iframe'i yeniden yüklemez;** uygulama içindeki gezinmeyi uygulamanın kendi yönlendiricisi yapar, bu çağrı yalnız panel URL'ini güncel tutar.
|
|
100
|
+
|
|
101
|
+
`path` `/` ile başlamalı, `//` ile başlamamalı ve uygulamanın origin'inde kalmalı; aksi halde `invalid_path`.
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
router.afterEach((to) => app.navigate.app(to.fullPath).catch(() => {}));
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### `navigate.panel(resource, id?)`
|
|
108
|
+
|
|
109
|
+
Panelde başka bir sayfaya geçer (uygulama kapanır).
|
|
110
|
+
|
|
111
|
+
| `resource` | Kimlik | Panel sayfası |
|
|
112
|
+
|---|---|---|
|
|
113
|
+
| `orders` | — | Sipariş listesi |
|
|
114
|
+
| `order` | gerekli | Sipariş detayı |
|
|
115
|
+
| `products` | — | Ürün listesi |
|
|
116
|
+
| `product` | gerekli | Ürün düzenleme |
|
|
117
|
+
| `apps` | — | Uygulamalarım |
|
|
118
|
+
|
|
119
|
+
Kimlik `^[A-Za-z0-9_-]{1,64}$` kalıbına uymalı; bilinmeyen kaynak ya da geçersiz kimlik `invalid_route` döner.
|
|
120
|
+
|
|
121
|
+
### `pickResource({ type, multiple? })`
|
|
122
|
+
|
|
123
|
+
Panelin seçicisini açar, seçilen kayıtların kimliklerini döner: `{ ids, cancelled }`. Kullanıcı pencereyi kapatırsa `{ ids: [], cancelled: true }`. Varsayılan olarak zaman aşımı yoktur.
|
|
124
|
+
|
|
125
|
+
| `type` | Gerekli kapsam |
|
|
126
|
+
|---|---|
|
|
127
|
+
| `product` | `read_products` |
|
|
128
|
+
|
|
129
|
+
Kapsam yoksa `missing_scope`, bilinmeyen tür `unsupported_resource` döner. Seçici açıkken yeni bir seçim istenirse önceki istek `cancelled: true` ile kapanır.
|
|
130
|
+
|
|
131
|
+
### `setHeight(height)` ve `autoResize({ target? })`
|
|
132
|
+
|
|
133
|
+
`setHeight` iframe yüksekliğini piksel olarak ayarlar; panel değeri 300–5000 aralığına sıkıştırır. Yükseklik hiç bildirilmezse iframe görünür alanı doldurur.
|
|
134
|
+
|
|
135
|
+
`autoResize` `ResizeObserver` ile `target` öğesini (varsayılan `document.body`) izler, boy değiştikçe kare başına en fazla bir kez bildirir. Dönen fonksiyon izlemeyi durdurur. `html, body { height: 100% }` gibi kurallar ölçümü görünür alana kilitler; otomatik yükseklik kullanırken bunlardan kaçının.
|
|
136
|
+
|
|
137
|
+
### `request(type, payload, { timeout? })`
|
|
138
|
+
|
|
139
|
+
Ham istek. Pakette henüz sarmalayıcısı olmayan bir mesaj tipini göndermek için kullanılır.
|
|
140
|
+
|
|
141
|
+
### `destroy()`
|
|
142
|
+
|
|
143
|
+
Dinleyiciyi kaldırır, bekleyen istekleri `destroyed` hatasıyla reddeder.
|
|
144
|
+
|
|
145
|
+
## Hatalar
|
|
146
|
+
|
|
147
|
+
Tüm reddedilen promise'ler `AppBridgeError` taşır; `code` alanı aşağıdakilerden biridir.
|
|
148
|
+
|
|
149
|
+
| Kod | Kaynak | Anlamı |
|
|
150
|
+
|---|---|---|
|
|
151
|
+
| `invalid_payload` | panel | Zorunlu alan boş ya da tipi yanlış. |
|
|
152
|
+
| `invalid_path` | panel | `navigate.app` yolu geçersiz ya da uygulama origin'i dışında. |
|
|
153
|
+
| `invalid_route` | panel | `navigate.panel` kaynağı bilinmiyor ya da kimlik geçersiz. |
|
|
154
|
+
| `missing_scope` | panel | Uygulamanın bu iş için gereken kapsamı yok. |
|
|
155
|
+
| `unsupported_resource` | panel | `pickResource` türü desteklenmiyor. |
|
|
156
|
+
| `unsupported_type` | panel | Panel bu mesaj tipini tanımıyor (eski panel sürümü). |
|
|
157
|
+
| `internal_error` | panel | Panel isteği işlerken hata aldı (ör. token alınamadı). |
|
|
158
|
+
| `timeout` | istemci | Süre içinde yanıt gelmedi. |
|
|
159
|
+
| `not_embedded` | istemci | Uygulama panel iframe'i içinde değil ya da üst pencere bir T-Soft paneli değil. |
|
|
160
|
+
| `destroyed` | istemci | `destroy()` çağrıldıktan sonra istek yapıldı. |
|
|
161
|
+
|
|
162
|
+
## Protokol
|
|
163
|
+
|
|
164
|
+
Paket kullanmadan köprüye bağlanmak isteyenler için sözleşme. Panel tarafındaki referans uygulama t-panel'de `pages/apps/open/[prefix].vue` dosyasıdır.
|
|
165
|
+
|
|
166
|
+
### Açılış
|
|
167
|
+
|
|
168
|
+
Panel uygulamanın `app_url` adresini (yalnız `https`, panel origin'inden farklı) şu parametrelerle iframe'de açar:
|
|
169
|
+
|
|
170
|
+
- `session`: Oturum JWT'si.
|
|
171
|
+
- `code`: Yalnız kurulumdan hemen sonraki ilk açılışta, kurulum kodu.
|
|
172
|
+
- Panel URL'inde `?path=/x` varsa uygulama `app_url` origin'i altındaki `/x` yolundan açılır.
|
|
173
|
+
|
|
174
|
+
iframe `sandbox="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads"`, `allow="clipboard-write"` ve `referrerpolicy="strict-origin"` ile açılır. Üst pencereye yönlendirme (`allow-top-navigation`) yoktur; panelde gezinmek için `navigate.panel` kullanılır.
|
|
175
|
+
|
|
176
|
+
### Zarf
|
|
177
|
+
|
|
178
|
+
Uygulama → panel (`window.parent.postMessage(message, panelOrigin)`):
|
|
179
|
+
|
|
180
|
+
```json
|
|
181
|
+
{ "source": "tsoft-app", "version": 1, "id": "app-1", "type": "toast.show", "payload": { "message": "Kaydedildi" } }
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
Panel → uygulama (`targetOrigin` = uygulama origin'i):
|
|
185
|
+
|
|
186
|
+
```json
|
|
187
|
+
{ "source": "tsoft-panel", "version": 1, "id": "app-1", "ok": true, "payload": {} }
|
|
188
|
+
{ "source": "tsoft-panel", "version": 1, "id": "app-1", "ok": false, "error": "invalid_payload" }
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Kurallar:
|
|
192
|
+
|
|
193
|
+
- Panel yalnız `event.origin` uygulama origin'ine eşit ve `event.source` kendi iframe'i olan mesajları işler.
|
|
194
|
+
- `source`, `version` (1), `type` (string) ve `id` (string) zorunludur; uymayan mesaj sessizce yok sayılır, yanıt dönmez.
|
|
195
|
+
- `id` panel tarafında 64 karaktere kesilir; yanıt bu kesilmiş kimlikle döner. 64 karakteri aşmayın.
|
|
196
|
+
- Uygulama da mesajı `targetOrigin` olarak panel origin'iyle göndermeli, yanıtları yalnız `event.source === window.parent` ve `event.origin` panel alan adlarından biriyse kabul etmelidir.
|
|
197
|
+
|
|
198
|
+
### Mesaj tipleri
|
|
199
|
+
|
|
200
|
+
| `type` | `payload` | Başarılı yanıt `payload` | Hatalar |
|
|
201
|
+
|---|---|---|---|
|
|
202
|
+
| `session-token.get` | `{}` | `{ token, expires_in, scopes }` | `internal_error` |
|
|
203
|
+
| `toast.show` | `{ message, variant? }` | `{}` | `invalid_payload` |
|
|
204
|
+
| `confirm.open` | `{ message, title?, confirmText? }` | `{ confirmed }` | `invalid_payload` |
|
|
205
|
+
| `navigate.app` | `{ path }` | `{}` | `invalid_path` |
|
|
206
|
+
| `navigate.panel` | `{ resource, id? }` | `{}` | `invalid_route` |
|
|
207
|
+
| `resource.pick` | `{ type, multiple? }` | `{ ids, cancelled? }` | `unsupported_resource`, `missing_scope` |
|
|
208
|
+
| `size.set` | `{ height }` | `{}` | `invalid_payload` |
|
|
209
|
+
| diğer | — | — | `unsupported_type` |
|
|
210
|
+
|
|
211
|
+
`confirm.open` ve `resource.pick` yanıtı kullanıcı işlem yapınca gelir.
|
|
212
|
+
|
|
213
|
+
### Eski token mesajı
|
|
214
|
+
|
|
215
|
+
Geriye dönük uyumluluk için panel zarfsız eski mesajı da yanıtlar. Yeni uygulamalarda kullanmayın.
|
|
216
|
+
|
|
217
|
+
```js
|
|
218
|
+
window.parent.postMessage({ type: 'tsoft:session-token:request' }, panelOrigin);
|
|
219
|
+
// başarı: { type: 'tsoft:session-token', token, expires_in }
|
|
220
|
+
// hata: { type: 'tsoft:session-token:error' }
|
|
221
|
+
```
|
|
222
|
+
|
|
223
|
+
## Geçiş
|
|
224
|
+
|
|
225
|
+
### `developer.tsoft.com.tr/app-bridge/v1` script'inden
|
|
226
|
+
|
|
227
|
+
| `TSoftBridge` | `TSoftAppGate` / npm |
|
|
228
|
+
|---|---|
|
|
229
|
+
| `TSoftBridge.create()` | `createApp()` |
|
|
230
|
+
| `bridge.claims` | `app.claims` |
|
|
231
|
+
| `bridge.sessionToken()` | `app.getSessionToken()` |
|
|
232
|
+
| `bridge.toast(message, 'error')` | `app.toast(message, { variant: 'error' })` |
|
|
233
|
+
| `bridge.confirm(opts)` | `app.confirm(opts)` |
|
|
234
|
+
| `bridge.pickProducts({ multiple })` | `app.pickResource({ type: 'product', multiple })` |
|
|
235
|
+
| `bridge.navigate(path)` | `app.navigate.app(path)` |
|
|
236
|
+
| `bridge.openPanel(resource, id)` | `app.navigate.panel(resource, id)` |
|
|
237
|
+
| `bridge.setHeight(h)` / `bridge.autoResize()` | `app.setHeight(h)` / `app.autoResize()` |
|
|
238
|
+
| `Error.message` | `AppBridgeError.code` |
|
|
239
|
+
|
|
240
|
+
Script panel dışında açılınca ilk istekte hata veriyordu; `createApp()` ise hemen `not_embedded` fırlatır.
|
|
241
|
+
|
|
242
|
+
### 0.1.x'ten
|
|
243
|
+
|
|
244
|
+
0.1.x'teki `createApp({ apiKey, shopId, host })`, `setNavigationMenu` ve `showToast` panelin tanımadığı bir mesaj biçimi (`T_SOFT_APP_BRIDGE`) gönderiyordu; kaldırıldı. `showToast(app, opts)` yerine `app.toast(message, opts)` kullanın; uygulama menüsünün karşılığı yok.
|
|
245
|
+
|
|
36
246
|
## Geliştirme
|
|
37
|
-
Projeyi kaynak koddan çalıştırmak için:
|
|
38
247
|
|
|
39
248
|
```bash
|
|
40
249
|
npm install
|
|
250
|
+
npm test # derler ve node --test ile testleri koşar (Node 23.6+)
|
|
41
251
|
npm run build
|
|
42
252
|
```
|
|
43
253
|
|
|
44
|
-
`
|
|
45
|
-
|
|
46
|
-
## Katkı ve Destek
|
|
47
|
-
- Yeni aksiyonlar (ör. bildirim, modal, navigation) eklenmesini istiyorsanız issue açabilirsiniz.
|
|
48
|
-
- Hatalar veya iyileştirme önerileri için PR göndermekten çekinmeyin.
|
|
49
|
-
|
|
50
|
-
Tüm sorularınız için T-Soft ekibi ile iletişime geçebilirsiniz.
|
|
254
|
+
Derleme iki çıktı üretir: `tsc` ile ESM + tipler (`dist/index.js`) ve `esbuild` ile tarayıcı derlemesi (`dist/tsoft-app-gate.min.js`). `dist/` yalnız npm paketine girer, repoya eklenmez. `prepublishOnly` yayın öncesi derlemeyi çalıştırır.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { type BridgeErrorCode, type PanelDetailResource, type PanelListResource, type PickableResource, type RequestPayloads, type RequestType, type ResponsePayloads, type ToastVariant } from './protocol.js';
|
|
2
|
+
export declare class AppBridgeError extends Error {
|
|
3
|
+
readonly code: BridgeErrorCode;
|
|
4
|
+
constructor(code: BridgeErrorCode, message?: string);
|
|
5
|
+
}
|
|
6
|
+
export interface AppOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Panelin origin'i. Verilmezse `location.ancestorOrigins` ya da `document.referrer`
|
|
9
|
+
* üzerinden bulunur ve T-Soft panel alan adlarından biri olmalıdır. Elle verilen
|
|
10
|
+
* değer bu listeyle denetlenmez; yerel geliştirme içindir.
|
|
11
|
+
*/
|
|
12
|
+
panelOrigin?: string;
|
|
13
|
+
/** Kullanıcı etkileşimi beklemeyen isteklerin zaman aşımı (ms). Varsayılan 10000. */
|
|
14
|
+
timeout?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface RequestOptions {
|
|
17
|
+
/** Bu isteğin zaman aşımı (ms). `0` zaman aşımını kapatır. */
|
|
18
|
+
timeout?: number;
|
|
19
|
+
}
|
|
20
|
+
/** Oturum token'ının içeriği. İmza doğrulanmadan okunur; güvenmeden önce sunucuda doğrulayın. */
|
|
21
|
+
export interface SessionClaims {
|
|
22
|
+
iss: string;
|
|
23
|
+
/** Uygulamanın prefix'i. */
|
|
24
|
+
aud: string;
|
|
25
|
+
/** Uygulamayı açan panel kullanıcısı. */
|
|
26
|
+
sub: string;
|
|
27
|
+
store_id: string;
|
|
28
|
+
/** Mağaza alan adı. */
|
|
29
|
+
dest: string;
|
|
30
|
+
iat: number;
|
|
31
|
+
nbf: number;
|
|
32
|
+
exp: number;
|
|
33
|
+
jti: string;
|
|
34
|
+
[claim: string]: unknown;
|
|
35
|
+
}
|
|
36
|
+
export interface SessionToken {
|
|
37
|
+
token: string;
|
|
38
|
+
claims: SessionClaims | null;
|
|
39
|
+
/** Token'ın geçerliliğini yitirdiği an (epoch ms). */
|
|
40
|
+
expiresAt: number;
|
|
41
|
+
/** Panelden alınmışsa uygulamanın kapsamları; URL'deki token için `null`. */
|
|
42
|
+
scopes: string[] | null;
|
|
43
|
+
}
|
|
44
|
+
export interface ToastOptions extends RequestOptions {
|
|
45
|
+
variant?: ToastVariant;
|
|
46
|
+
}
|
|
47
|
+
export interface ConfirmOptions extends RequestOptions {
|
|
48
|
+
message: string;
|
|
49
|
+
title?: string;
|
|
50
|
+
confirmText?: string;
|
|
51
|
+
}
|
|
52
|
+
export interface PickOptions extends RequestOptions {
|
|
53
|
+
type: PickableResource;
|
|
54
|
+
multiple?: boolean;
|
|
55
|
+
}
|
|
56
|
+
export interface PickResult {
|
|
57
|
+
ids: Array<string | number>;
|
|
58
|
+
cancelled: boolean;
|
|
59
|
+
}
|
|
60
|
+
export interface AutoResizeOptions {
|
|
61
|
+
/** Yüksekliği ölçülecek öğe. Varsayılan `document.body`. */
|
|
62
|
+
target?: Element;
|
|
63
|
+
}
|
|
64
|
+
export interface App {
|
|
65
|
+
readonly panelOrigin: string;
|
|
66
|
+
/** Elimizdeki son oturum token'ının içeriği; token yoksa `null`. */
|
|
67
|
+
readonly claims: SessionClaims | null;
|
|
68
|
+
/** Panelin kurulumdan hemen sonra URL'e eklediği `?code=` değeri. */
|
|
69
|
+
readonly installCode: string | null;
|
|
70
|
+
getSessionToken(options?: {
|
|
71
|
+
forceRefresh?: boolean;
|
|
72
|
+
} & RequestOptions): Promise<string>;
|
|
73
|
+
getSession(options?: {
|
|
74
|
+
forceRefresh?: boolean;
|
|
75
|
+
} & RequestOptions): Promise<SessionToken>;
|
|
76
|
+
toast(message: string, options?: ToastOptions): Promise<void>;
|
|
77
|
+
/** Kullanıcı onaylarsa `true`, vazgeçerse `false`. Varsayılan olarak zaman aşımı yoktur. */
|
|
78
|
+
confirm(options: ConfirmOptions | string): Promise<boolean>;
|
|
79
|
+
navigate: {
|
|
80
|
+
/** Panel adres çubuğunu uygulama içi yola eşitler; iframe'i yeniden yüklemez. */
|
|
81
|
+
app(path: string, options?: RequestOptions): Promise<void>;
|
|
82
|
+
panel(resource: PanelListResource, options?: RequestOptions): Promise<void>;
|
|
83
|
+
panel(resource: PanelDetailResource, id: string | number, options?: RequestOptions): Promise<void>;
|
|
84
|
+
};
|
|
85
|
+
/** Panelin seçicisini açar. Varsayılan olarak zaman aşımı yoktur. */
|
|
86
|
+
pickResource(options: PickOptions): Promise<PickResult>;
|
|
87
|
+
/** iframe yüksekliğini ayarlar; panel 300–5000 px aralığına sıkıştırır. */
|
|
88
|
+
setHeight(height: number, options?: RequestOptions): Promise<void>;
|
|
89
|
+
/** İçerik boyu değiştikçe yüksekliği bildirir; durdurmak için dönen fonksiyonu çağırın. */
|
|
90
|
+
autoResize(options?: AutoResizeOptions): () => void;
|
|
91
|
+
/** Ham istek; yeni mesaj tipleri için kaçış kapısı. */
|
|
92
|
+
request<T extends RequestType>(type: T, payload: RequestPayloads[T], options?: RequestOptions): Promise<ResponsePayloads[T]>;
|
|
93
|
+
/** Dinleyicileri kaldırır, bekleyen istekleri `destroyed` ile reddeder. */
|
|
94
|
+
destroy(): void;
|
|
95
|
+
}
|
|
96
|
+
/** Panelin yayınlandığı alan adları (t-panel `PANEL_DOMAINS`). */
|
|
97
|
+
export declare const PANEL_ORIGIN_PATTERN: RegExp;
|
|
98
|
+
/** Sayfa bir iframe içinde mi açılmış. */
|
|
99
|
+
export declare function isEmbedded(): boolean;
|
|
100
|
+
/** JWT gövdesini imza doğrulamadan okur. */
|
|
101
|
+
export declare function decodeSessionToken(token: string): SessionClaims | null;
|
|
102
|
+
export declare function createApp(options?: AppOptions): App;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
import { APP_SOURCE, BRIDGE_VERSION, PANEL_SOURCE, } from './protocol.js';
|
|
2
|
+
export class AppBridgeError extends Error {
|
|
3
|
+
constructor(code, message) {
|
|
4
|
+
super(message !== null && message !== void 0 ? message : `T-Soft App Bridge: ${code}`);
|
|
5
|
+
this.name = 'AppBridgeError';
|
|
6
|
+
this.code = code;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
const DEFAULT_TIMEOUT = 10000;
|
|
10
|
+
// Token 60 sn yaşar; sunucuya giderken süresi dolmasın diye 15 sn kala yenilenir.
|
|
11
|
+
const REFRESH_MARGIN = 15000;
|
|
12
|
+
/** Panelin yayınlandığı alan adları (t-panel `PANEL_DOMAINS`). */
|
|
13
|
+
export const PANEL_ORIGIN_PATTERN = /^https:\/\/([a-z0-9-]+\.)*(tsoftpanel\.com|tsoftpanel\.net|paneltsoft\.com)$/;
|
|
14
|
+
/** Sayfa bir iframe içinde mi açılmış. */
|
|
15
|
+
export function isEmbedded() {
|
|
16
|
+
return typeof window !== 'undefined' && window.parent !== window;
|
|
17
|
+
}
|
|
18
|
+
function detectPanelOrigin() {
|
|
19
|
+
const ancestors = window.location.ancestorOrigins;
|
|
20
|
+
if (ancestors && ancestors.length > 0) {
|
|
21
|
+
return ancestors[0];
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
return document.referrer ? new URL(document.referrer).origin : null;
|
|
25
|
+
}
|
|
26
|
+
catch (_a) {
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
/** JWT gövdesini imza doğrulamadan okur. */
|
|
31
|
+
export function decodeSessionToken(token) {
|
|
32
|
+
try {
|
|
33
|
+
const binary = atob(token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'));
|
|
34
|
+
const claims = JSON.parse(new TextDecoder().decode(Uint8Array.from(binary, (c) => c.charCodeAt(0))));
|
|
35
|
+
return claims && typeof claims.exp === 'number' ? claims : null;
|
|
36
|
+
}
|
|
37
|
+
catch (_a) {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function isFresh(session) {
|
|
42
|
+
return session !== null && session.expiresAt - REFRESH_MARGIN > Date.now();
|
|
43
|
+
}
|
|
44
|
+
export function createApp(options = {}) {
|
|
45
|
+
var _a, _b;
|
|
46
|
+
if (!isEmbedded()) {
|
|
47
|
+
throw new AppBridgeError('not_embedded', 'T-Soft App Bridge: uygulama panel iframe\'i içinde açılmamış');
|
|
48
|
+
}
|
|
49
|
+
const detected = options.panelOrigin ? null : detectPanelOrigin();
|
|
50
|
+
if (!options.panelOrigin && !(detected && PANEL_ORIGIN_PATTERN.test(detected))) {
|
|
51
|
+
throw new AppBridgeError('not_embedded', `T-Soft App Bridge: üst pencere bir T-Soft paneli değil (${detected !== null && detected !== void 0 ? detected : 'bilinmiyor'})`);
|
|
52
|
+
}
|
|
53
|
+
const panelOrigin = ((_a = options.panelOrigin) !== null && _a !== void 0 ? _a : detected);
|
|
54
|
+
const defaultTimeout = (_b = options.timeout) !== null && _b !== void 0 ? _b : DEFAULT_TIMEOUT;
|
|
55
|
+
const pending = new Map();
|
|
56
|
+
const params = new URLSearchParams(window.location.search);
|
|
57
|
+
const urlToken = params.get('session');
|
|
58
|
+
let counter = 0;
|
|
59
|
+
let destroyed = false;
|
|
60
|
+
let session = null;
|
|
61
|
+
let refreshing = null;
|
|
62
|
+
if (urlToken) {
|
|
63
|
+
const claims = decodeSessionToken(urlToken);
|
|
64
|
+
if (claims) {
|
|
65
|
+
session = { token: urlToken, claims, expiresAt: claims.exp * 1000, scopes: null };
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
function onMessage(event) {
|
|
69
|
+
var _a;
|
|
70
|
+
if (event.source !== window.parent || event.origin !== panelOrigin) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
const data = event.data;
|
|
74
|
+
if ((data === null || data === void 0 ? void 0 : data.source) !== PANEL_SOURCE || (data === null || data === void 0 ? void 0 : data.version) !== BRIDGE_VERSION || typeof (data === null || data === void 0 ? void 0 : data.id) !== 'string') {
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
const entry = pending.get(data.id);
|
|
78
|
+
if (!entry) {
|
|
79
|
+
return;
|
|
80
|
+
}
|
|
81
|
+
pending.delete(data.id);
|
|
82
|
+
clearTimeout(entry.timer);
|
|
83
|
+
if (data.ok === true) {
|
|
84
|
+
entry.resolve((_a = data.payload) !== null && _a !== void 0 ? _a : {});
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
entry.reject(new AppBridgeError(typeof data.error === 'string' ? data.error : 'internal_error'));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
window.addEventListener('message', onMessage);
|
|
91
|
+
function request(type, payload, requestOptions = {}, fallbackTimeout = defaultTimeout) {
|
|
92
|
+
var _a;
|
|
93
|
+
if (destroyed) {
|
|
94
|
+
return Promise.reject(new AppBridgeError('destroyed'));
|
|
95
|
+
}
|
|
96
|
+
const id = `app-${Date.now().toString(36)}-${(counter++).toString(36)}`;
|
|
97
|
+
const timeout = (_a = requestOptions.timeout) !== null && _a !== void 0 ? _a : fallbackTimeout;
|
|
98
|
+
return new Promise((resolve, reject) => {
|
|
99
|
+
const entry = { resolve, reject };
|
|
100
|
+
if (timeout > 0) {
|
|
101
|
+
entry.timer = setTimeout(() => {
|
|
102
|
+
pending.delete(id);
|
|
103
|
+
reject(new AppBridgeError('timeout'));
|
|
104
|
+
}, timeout);
|
|
105
|
+
}
|
|
106
|
+
pending.set(id, entry);
|
|
107
|
+
window.parent.postMessage({ source: APP_SOURCE, version: BRIDGE_VERSION, id, type, payload }, panelOrigin);
|
|
108
|
+
});
|
|
109
|
+
}
|
|
110
|
+
async function getSession(sessionOptions = {}) {
|
|
111
|
+
if (!sessionOptions.forceRefresh && isFresh(session)) {
|
|
112
|
+
return session;
|
|
113
|
+
}
|
|
114
|
+
refreshing !== null && refreshing !== void 0 ? refreshing : (refreshing = request('session-token.get', {}, sessionOptions)
|
|
115
|
+
.then((response) => {
|
|
116
|
+
// expires_in görece olduğu için istemci saatindeki kaymadan etkilenmez.
|
|
117
|
+
session = {
|
|
118
|
+
token: response.token,
|
|
119
|
+
claims: decodeSessionToken(response.token),
|
|
120
|
+
expiresAt: Date.now() + response.expires_in * 1000,
|
|
121
|
+
scopes: Array.isArray(response.scopes) ? response.scopes : [],
|
|
122
|
+
};
|
|
123
|
+
return session;
|
|
124
|
+
})
|
|
125
|
+
.finally(() => {
|
|
126
|
+
refreshing = null;
|
|
127
|
+
}));
|
|
128
|
+
return refreshing;
|
|
129
|
+
}
|
|
130
|
+
async function empty(type, payload, requestOptions) {
|
|
131
|
+
await request(type, payload, requestOptions);
|
|
132
|
+
}
|
|
133
|
+
return {
|
|
134
|
+
panelOrigin,
|
|
135
|
+
get claims() {
|
|
136
|
+
var _a;
|
|
137
|
+
return (_a = session === null || session === void 0 ? void 0 : session.claims) !== null && _a !== void 0 ? _a : null;
|
|
138
|
+
},
|
|
139
|
+
installCode: params.get('code'),
|
|
140
|
+
getSession,
|
|
141
|
+
async getSessionToken(sessionOptions) {
|
|
142
|
+
return (await getSession(sessionOptions)).token;
|
|
143
|
+
},
|
|
144
|
+
toast(message, { variant, ...rest } = {}) {
|
|
145
|
+
return empty('toast.show', variant ? { message, variant } : { message }, rest);
|
|
146
|
+
},
|
|
147
|
+
async confirm(input) {
|
|
148
|
+
const { message, title, confirmText, ...rest } = typeof input === 'string' ? { message: input } : input;
|
|
149
|
+
const response = await request('confirm.open', { message, title, confirmText }, rest, 0);
|
|
150
|
+
return response.confirmed === true;
|
|
151
|
+
},
|
|
152
|
+
navigate: {
|
|
153
|
+
app(path, requestOptions) {
|
|
154
|
+
return empty('navigate.app', { path }, requestOptions);
|
|
155
|
+
},
|
|
156
|
+
panel(resource, idOrOptions, maybeOptions) {
|
|
157
|
+
if (typeof idOrOptions === 'string' || typeof idOrOptions === 'number') {
|
|
158
|
+
return empty('navigate.panel', { resource, id: String(idOrOptions) }, maybeOptions);
|
|
159
|
+
}
|
|
160
|
+
return empty('navigate.panel', { resource }, idOrOptions);
|
|
161
|
+
},
|
|
162
|
+
},
|
|
163
|
+
async pickResource({ type, multiple, ...rest }) {
|
|
164
|
+
const response = await request('resource.pick', { type, multiple: multiple === true }, rest, 0);
|
|
165
|
+
return { ids: Array.isArray(response.ids) ? response.ids : [], cancelled: response.cancelled === true };
|
|
166
|
+
},
|
|
167
|
+
setHeight(height, requestOptions) {
|
|
168
|
+
return empty('size.set', { height: Math.ceil(height) }, requestOptions);
|
|
169
|
+
},
|
|
170
|
+
autoResize({ target } = {}) {
|
|
171
|
+
const element = target !== null && target !== void 0 ? target : document.body;
|
|
172
|
+
let last = 0;
|
|
173
|
+
let frame = 0;
|
|
174
|
+
const measure = () => {
|
|
175
|
+
frame = 0;
|
|
176
|
+
const style = getComputedStyle(element);
|
|
177
|
+
const height = Math.ceil(element.getBoundingClientRect().height + parseFloat(style.marginTop) + parseFloat(style.marginBottom));
|
|
178
|
+
if (height !== last) {
|
|
179
|
+
last = height;
|
|
180
|
+
request('size.set', { height }).catch(() => { });
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
const observer = new ResizeObserver(() => {
|
|
184
|
+
if (!frame)
|
|
185
|
+
frame = requestAnimationFrame(measure);
|
|
186
|
+
});
|
|
187
|
+
observer.observe(element);
|
|
188
|
+
return () => {
|
|
189
|
+
observer.disconnect();
|
|
190
|
+
if (frame)
|
|
191
|
+
cancelAnimationFrame(frame);
|
|
192
|
+
};
|
|
193
|
+
},
|
|
194
|
+
request,
|
|
195
|
+
destroy() {
|
|
196
|
+
destroyed = true;
|
|
197
|
+
window.removeEventListener('message', onMessage);
|
|
198
|
+
for (const entry of pending.values()) {
|
|
199
|
+
clearTimeout(entry.timer);
|
|
200
|
+
entry.reject(new AppBridgeError('destroyed'));
|
|
201
|
+
}
|
|
202
|
+
pending.clear();
|
|
203
|
+
},
|
|
204
|
+
};
|
|
205
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,17 +1,4 @@
|
|
|
1
|
-
export
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
};
|
|
6
|
-
export declare function createApp(config: BridgeConfig): {
|
|
7
|
-
config: BridgeConfig;
|
|
8
|
-
post(action: string, payload: any): void;
|
|
9
|
-
};
|
|
10
|
-
export declare function setNavigationMenu(app: ReturnType<typeof createApp>, items: Array<{
|
|
11
|
-
label: string;
|
|
12
|
-
path: string;
|
|
13
|
-
}>): void;
|
|
14
|
-
export declare function showToast(app: ReturnType<typeof createApp>, options: {
|
|
15
|
-
message: string;
|
|
16
|
-
variant?: 'success' | 'error';
|
|
17
|
-
}): void;
|
|
1
|
+
export { createApp, isEmbedded, decodeSessionToken, AppBridgeError, PANEL_ORIGIN_PATTERN } from './client.js';
|
|
2
|
+
export type { App, AppOptions, AutoResizeOptions, ConfirmOptions, PickOptions, PickResult, RequestOptions, SessionClaims, SessionToken, ToastOptions, } from './client.js';
|
|
3
|
+
export { BRIDGE_VERSION, APP_SOURCE, PANEL_SOURCE } from './protocol.js';
|
|
4
|
+
export type { BridgeErrorCode, BridgeRequest, BridgeResponse, PanelDetailResource, PanelListResource, PanelResource, PickableResource, RequestPayloads, RequestType, ResponsePayloads, ToastVariant, } from './protocol.js';
|
package/dist/index.js
CHANGED
|
@@ -1,21 +1,2 @@
|
|
|
1
|
-
|
|
2
|
-
export
|
|
3
|
-
const app = {
|
|
4
|
-
config,
|
|
5
|
-
post(action, payload) {
|
|
6
|
-
window.parent.postMessage({
|
|
7
|
-
namespace: 'T_SOFT_APP_BRIDGE',
|
|
8
|
-
action,
|
|
9
|
-
payload,
|
|
10
|
-
appId: config.apiKey, // veya başka id
|
|
11
|
-
}, config.host);
|
|
12
|
-
},
|
|
13
|
-
};
|
|
14
|
-
return app;
|
|
15
|
-
}
|
|
16
|
-
export function setNavigationMenu(app, items) {
|
|
17
|
-
app.post('NAVIGATION_MENU.SET', { items });
|
|
18
|
-
}
|
|
19
|
-
export function showToast(app, options) {
|
|
20
|
-
app.post('TOAST.SHOW', options);
|
|
21
|
-
}
|
|
1
|
+
export { createApp, isEmbedded, decodeSessionToken, AppBridgeError, PANEL_ORIGIN_PATTERN } from './client.js';
|
|
2
|
+
export { BRIDGE_VERSION, APP_SOURCE, PANEL_SOURCE } from './protocol.js';
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export declare const BRIDGE_VERSION = 1;
|
|
2
|
+
export declare const APP_SOURCE = "tsoft-app";
|
|
3
|
+
export declare const PANEL_SOURCE = "tsoft-panel";
|
|
4
|
+
/** Uygulamadan panele giden istek zarfı. */
|
|
5
|
+
export interface BridgeRequest<T extends RequestType = RequestType> {
|
|
6
|
+
source: typeof APP_SOURCE;
|
|
7
|
+
version: typeof BRIDGE_VERSION;
|
|
8
|
+
/** İsteğe özgü kimlik; panel en fazla 64 karakterini kullanır. */
|
|
9
|
+
id: string;
|
|
10
|
+
type: T;
|
|
11
|
+
payload: RequestPayloads[T];
|
|
12
|
+
}
|
|
13
|
+
/** Panelden uygulamaya dönen yanıt zarfı. */
|
|
14
|
+
export type BridgeResponse = {
|
|
15
|
+
source: typeof PANEL_SOURCE;
|
|
16
|
+
version: typeof BRIDGE_VERSION;
|
|
17
|
+
id: string;
|
|
18
|
+
ok: true;
|
|
19
|
+
payload: unknown;
|
|
20
|
+
} | {
|
|
21
|
+
source: typeof PANEL_SOURCE;
|
|
22
|
+
version: typeof BRIDGE_VERSION;
|
|
23
|
+
id: string;
|
|
24
|
+
ok: false;
|
|
25
|
+
error: BridgeErrorCode;
|
|
26
|
+
};
|
|
27
|
+
export type ToastVariant = 'success' | 'error';
|
|
28
|
+
/** Kimlik istemeyen panel sayfaları. */
|
|
29
|
+
export type PanelListResource = 'orders' | 'products' | 'apps';
|
|
30
|
+
/** Kimlikle açılan panel sayfaları; kimlik `^[A-Za-z0-9_-]{1,64}$` olmalı. */
|
|
31
|
+
export type PanelDetailResource = 'order' | 'product';
|
|
32
|
+
export type PanelResource = PanelListResource | PanelDetailResource;
|
|
33
|
+
/** Seçici türü ve istediği kapsam: `product` → `read_products`. */
|
|
34
|
+
export type PickableResource = 'product';
|
|
35
|
+
export interface RequestPayloads {
|
|
36
|
+
'session-token.get': Record<string, never>;
|
|
37
|
+
'toast.show': {
|
|
38
|
+
message: string;
|
|
39
|
+
variant?: ToastVariant;
|
|
40
|
+
};
|
|
41
|
+
'confirm.open': {
|
|
42
|
+
message: string;
|
|
43
|
+
title?: string;
|
|
44
|
+
confirmText?: string;
|
|
45
|
+
};
|
|
46
|
+
'navigate.app': {
|
|
47
|
+
path: string;
|
|
48
|
+
};
|
|
49
|
+
'navigate.panel': {
|
|
50
|
+
resource: PanelResource;
|
|
51
|
+
id?: string;
|
|
52
|
+
};
|
|
53
|
+
'resource.pick': {
|
|
54
|
+
type: PickableResource;
|
|
55
|
+
multiple?: boolean;
|
|
56
|
+
};
|
|
57
|
+
'size.set': {
|
|
58
|
+
height: number;
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
export interface ResponsePayloads {
|
|
62
|
+
'session-token.get': {
|
|
63
|
+
token: string;
|
|
64
|
+
expires_in: number;
|
|
65
|
+
scopes: string[];
|
|
66
|
+
};
|
|
67
|
+
'toast.show': Record<string, never>;
|
|
68
|
+
'confirm.open': {
|
|
69
|
+
confirmed: boolean;
|
|
70
|
+
};
|
|
71
|
+
'navigate.app': Record<string, never>;
|
|
72
|
+
'navigate.panel': Record<string, never>;
|
|
73
|
+
'resource.pick': {
|
|
74
|
+
ids: Array<string | number>;
|
|
75
|
+
cancelled?: boolean;
|
|
76
|
+
};
|
|
77
|
+
'size.set': Record<string, never>;
|
|
78
|
+
}
|
|
79
|
+
export type RequestType = keyof RequestPayloads;
|
|
80
|
+
/**
|
|
81
|
+
* Panelin döndürdüğü hata kodları ile istemcinin kendi ürettikleri.
|
|
82
|
+
* Bilinmeyen kodlar da string olarak geçer.
|
|
83
|
+
*/
|
|
84
|
+
export type BridgeErrorCode = 'invalid_payload' | 'invalid_path' | 'invalid_route' | 'missing_scope' | 'unsupported_resource' | 'unsupported_type' | 'internal_error' | 'timeout' | 'not_embedded' | 'destroyed' | (string & {});
|
package/dist/protocol.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var TSoftAppGate=(()=>{var S=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var U=Object.prototype.hasOwnProperty;var z=(n,o)=>{for(var r in o)S(n,r,{get:o[r],enumerable:!0})},V=(n,o,r,u)=>{if(o&&typeof o=="object"||typeof o=="function")for(let a of I(o))!U.call(n,a)&&a!==r&&S(n,a,{get:()=>o[a],enumerable:!(u=D(o,a))||u.enumerable});return n};var G=n=>V(S({},"__esModule",{value:!0}),n);var H={};z(H,{APP_SOURCE:()=>T,AppBridgeError:()=>p,BRIDGE_VERSION:()=>P,PANEL_ORIGIN_PATTERN:()=>k,PANEL_SOURCE:()=>O,createApp:()=>L,decodeSessionToken:()=>x,isEmbedded:()=>b});var P=1,T="tsoft-app",O="tsoft-panel";var p=class extends Error{constructor(o,r){super(r!=null?r:`T-Soft App Bridge: ${o}`),this.name="AppBridgeError",this.code=o}},M=1e4,F=15e3,k=/^https:\/\/([a-z0-9-]+\.)*(tsoftpanel\.com|tsoftpanel\.net|paneltsoft\.com)$/;function b(){return typeof window!="undefined"&&window.parent!==window}function j(){let n=window.location.ancestorOrigins;if(n&&n.length>0)return n[0];try{return document.referrer?new URL(document.referrer).origin:null}catch(o){return null}}function x(n){try{let o=atob(n.split(".")[1].replace(/-/g,"+").replace(/_/g,"/")),r=JSON.parse(new TextDecoder().decode(Uint8Array.from(o,u=>u.charCodeAt(0))));return r&&typeof r.exp=="number"?r:null}catch(o){return null}}function $(n){return n!==null&&n.expiresAt-F>Date.now()}function L(n={}){var _,h;if(!b())throw new p("not_embedded","T-Soft App Bridge: uygulama panel iframe'i i\xE7inde a\xE7\u0131lmam\u0131\u015F");let o=n.panelOrigin?null:j();if(!n.panelOrigin&&!(o&&k.test(o)))throw new p("not_embedded",`T-Soft App Bridge: \xFCst pencere bir T-Soft paneli de\u011Fil (${o!=null?o:"bilinmiyor"})`);let r=(_=n.panelOrigin)!=null?_:o,u=(h=n.timeout)!=null?h:M,a=new Map,A=new URLSearchParams(window.location.search),E=A.get("session"),N=0,w=!1,l=null,m=null;if(E){let t=x(E);t&&(l={token:E,claims:t,expiresAt:t.exp*1e3,scopes:null})}function v(t){var i;if(t.source!==window.parent||t.origin!==r)return;let e=t.data;if((e==null?void 0:e.source)!==O||(e==null?void 0:e.version)!==1||typeof(e==null?void 0:e.id)!="string")return;let s=a.get(e.id);s&&(a.delete(e.id),clearTimeout(s.timer),e.ok===!0?s.resolve((i=e.payload)!=null?i:{}):s.reject(new p(typeof e.error=="string"?e.error:"internal_error")))}window.addEventListener("message",v);function d(t,e,s={},i=u){var y;if(w)return Promise.reject(new p("destroyed"));let c=`app-${Date.now().toString(36)}-${(N++).toString(36)}`,g=(y=s.timeout)!=null?y:i;return new Promise((f,C)=>{let B={resolve:f,reject:C};g>0&&(B.timer=setTimeout(()=>{a.delete(c),C(new p("timeout"))},g)),a.set(c,B),window.parent.postMessage({source:T,version:1,id:c,type:t,payload:e},r)})}async function q(t={}){return!t.forceRefresh&&$(l)?l:(m!=null||(m=d("session-token.get",{},t).then(e=>(l={token:e.token,claims:x(e.token),expiresAt:Date.now()+e.expires_in*1e3,scopes:Array.isArray(e.scopes)?e.scopes:[]},l)).finally(()=>{m=null})),m)}async function R(t,e,s){await d(t,e,s)}return{panelOrigin:r,get claims(){var t;return(t=l==null?void 0:l.claims)!=null?t:null},installCode:A.get("code"),getSession:q,async getSessionToken(t){return(await q(t)).token},toast(t,{variant:e,...s}={}){return R("toast.show",e?{message:t,variant:e}:{message:t},s)},async confirm(t){let{message:e,title:s,confirmText:i,...c}=typeof t=="string"?{message:t}:t;return(await d("confirm.open",{message:e,title:s,confirmText:i},c,0)).confirmed===!0},navigate:{app(t,e){return R("navigate.app",{path:t},e)},panel(t,e,s){return typeof e=="string"||typeof e=="number"?R("navigate.panel",{resource:t,id:String(e)},s):R("navigate.panel",{resource:t},e)}},async pickResource({type:t,multiple:e,...s}){let i=await d("resource.pick",{type:t,multiple:e===!0},s,0);return{ids:Array.isArray(i.ids)?i.ids:[],cancelled:i.cancelled===!0}},setHeight(t,e){return R("size.set",{height:Math.ceil(t)},e)},autoResize({target:t}={}){let e=t!=null?t:document.body,s=0,i=0,c=()=>{i=0;let y=getComputedStyle(e),f=Math.ceil(e.getBoundingClientRect().height+parseFloat(y.marginTop)+parseFloat(y.marginBottom));f!==s&&(s=f,d("size.set",{height:f}).catch(()=>{}))},g=new ResizeObserver(()=>{i||(i=requestAnimationFrame(c))});return g.observe(e),()=>{g.disconnect(),i&&cancelAnimationFrame(i)}},request:d,destroy(){w=!0,window.removeEventListener("message",v);for(let t of a.values())clearTimeout(t.timer),t.reject(new p("destroyed"));a.clear()}}}return G(H);})();
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tekrom/tsoft-app-gate",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "T-Soft
|
|
3
|
+
"version": "0.3.0",
|
|
4
|
+
"description": "T-Soft paneli içinde açılan uygulamalar için App Bridge istemcisi",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
@@ -9,13 +9,18 @@
|
|
|
9
9
|
".": {
|
|
10
10
|
"types": "./dist/index.d.ts",
|
|
11
11
|
"import": "./dist/index.js"
|
|
12
|
-
}
|
|
12
|
+
},
|
|
13
|
+
"./browser": "./dist/tsoft-app-gate.min.js"
|
|
13
14
|
},
|
|
15
|
+
"unpkg": "./dist/tsoft-app-gate.min.js",
|
|
16
|
+
"jsdelivr": "./dist/tsoft-app-gate.min.js",
|
|
14
17
|
"files": [
|
|
15
18
|
"dist"
|
|
16
19
|
],
|
|
20
|
+
"sideEffects": false,
|
|
17
21
|
"scripts": {
|
|
18
|
-
"build": "tsc",
|
|
22
|
+
"build": "tsc && esbuild src/index.ts --bundle --format=iife --global-name=TSoftAppGate --target=es2018 --minify --outfile=dist/tsoft-app-gate.min.js",
|
|
23
|
+
"test": "npm run build && node --test test/",
|
|
19
24
|
"prepublishOnly": "npm run build"
|
|
20
25
|
},
|
|
21
26
|
"repository": {
|
|
@@ -25,11 +30,13 @@
|
|
|
25
30
|
"keywords": [
|
|
26
31
|
"tsoft",
|
|
27
32
|
"app-gate",
|
|
33
|
+
"app-bridge",
|
|
28
34
|
"embedded-app"
|
|
29
35
|
],
|
|
30
36
|
"author": "T-Soft",
|
|
31
37
|
"license": "MIT",
|
|
32
38
|
"devDependencies": {
|
|
39
|
+
"esbuild": "^0.25.10",
|
|
33
40
|
"typescript": "^5.9.3"
|
|
34
41
|
}
|
|
35
42
|
}
|