@tilery/client 0.1.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/LICENSE +21 -0
- package/README.md +224 -0
- package/dist/client.d.ts +103 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +211 -0
- package/dist/index.js.map +1 -0
- package/dist/service-worker.d.ts +11 -0
- package/dist/service-worker.d.ts.map +1 -0
- package/dist/tilery-sw.js +1 -0
- package/dist/types.d.ts +96 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +42 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Snorre Magnus Davøen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
# @tilery/client
|
|
2
|
+
|
|
3
|
+
Client library for [Tilery.eu](https://tilery.eu) tile API with service worker caching and automatic token refresh.
|
|
4
|
+
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- **Token Management** - Automatic token refresh before expiry
|
|
8
|
+
- **Service Worker Caching** - Long-lived tile cache that survives token rotation
|
|
9
|
+
- **No CORS Preflight** - Token passed as query parameter, not header
|
|
10
|
+
- **MapLibre Integration** - Get ready-to-use style objects
|
|
11
|
+
|
|
12
|
+
> The SDK implements only the JWT/token-exchange flow — that's the safe
|
|
13
|
+
> path for browsers (15-minute lifetime, origin-locked, plays well with the
|
|
14
|
+
> service-worker cache). The Tilery API also accepts an _app-mode_ API key
|
|
15
|
+
> sent directly as `Authorization: Bearer …` for trusted backends, but
|
|
16
|
+
> that path skips the SDK entirely (and skips the cache). If you reach for
|
|
17
|
+
> it from a browser, you've left the safe envelope this SDK provides — see
|
|
18
|
+
> the [security model](https://tilery.eu/docs/security) before doing so.
|
|
19
|
+
|
|
20
|
+
## Installation
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
npm install @tilery/client
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
The package has zero runtime dependencies. MapLibre style JSON (including
|
|
27
|
+
all layer definitions) is fetched directly from the tile server.
|
|
28
|
+
|
|
29
|
+
## Quick Start
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { TileryClient } from "@tilery/client";
|
|
33
|
+
import maplibregl from "maplibre-gl";
|
|
34
|
+
|
|
35
|
+
// Create client with your token fetcher
|
|
36
|
+
const client = new TileryClient({
|
|
37
|
+
getToken: async () => {
|
|
38
|
+
// Your backend exchanges API key for short-lived JWT
|
|
39
|
+
const res = await fetch("/api/tile-token", { credentials: "include" });
|
|
40
|
+
if (!res.ok) throw new Error("Failed to get token");
|
|
41
|
+
return res.json(); // { token: string, exp: number }
|
|
42
|
+
},
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
// Register service worker for tile caching
|
|
46
|
+
await client.registerServiceWorker();
|
|
47
|
+
|
|
48
|
+
// Create map with auto-generated style
|
|
49
|
+
const map = new maplibregl.Map({
|
|
50
|
+
container: "map",
|
|
51
|
+
style: await client.getMapStyle({ flavor: "dark" }),
|
|
52
|
+
center: [10.75, 59.91],
|
|
53
|
+
zoom: 12,
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## Service Worker Setup
|
|
58
|
+
|
|
59
|
+
The service worker code is bundled in the library. Create a file in your public directory:
|
|
60
|
+
|
|
61
|
+
**Option 1: Copy from built library**
|
|
62
|
+
|
|
63
|
+
```bash
|
|
64
|
+
# The library exports the compiled SW code
|
|
65
|
+
node -e "import('@tilery/client').then(m => console.log(m.SERVICE_WORKER_CODE))" > public/tilery-sw.js
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
**Option 2: Build script**
|
|
69
|
+
|
|
70
|
+
```typescript
|
|
71
|
+
// scripts/build-sw.ts
|
|
72
|
+
import { SERVICE_WORKER_CODE } from "@tilery/client";
|
|
73
|
+
import { writeFileSync } from "fs";
|
|
74
|
+
writeFileSync("public/tilery-sw.js", SERVICE_WORKER_CODE);
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Then register it:
|
|
78
|
+
|
|
79
|
+
```typescript
|
|
80
|
+
await client.registerServiceWorker();
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The service worker intercepts tile requests and:
|
|
84
|
+
|
|
85
|
+
1. Strips the `?token=` query parameter to create a normalized cache key
|
|
86
|
+
2. Checks the cache using the normalized key
|
|
87
|
+
3. On cache miss, fetches with the original URL (including token)
|
|
88
|
+
4. Stores the response under the normalized key
|
|
89
|
+
|
|
90
|
+
This means tiles stay cached even when your token rotates!
|
|
91
|
+
|
|
92
|
+
## API Reference
|
|
93
|
+
|
|
94
|
+
### `TileryClient`
|
|
95
|
+
|
|
96
|
+
#### Constructor Options
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
interface TileryClientOptions {
|
|
100
|
+
// Required: async function that returns { token, exp }
|
|
101
|
+
getToken: () => Promise<{ token: string; exp: number }>;
|
|
102
|
+
|
|
103
|
+
// Optional: tile server URL (default: 'https://api.tilery.eu').
|
|
104
|
+
// Use 'https://api.test.tilery.eu' to point at the staging environment.
|
|
105
|
+
tileServer?: string;
|
|
106
|
+
|
|
107
|
+
// Optional: seconds before expiry to refresh (default: 60)
|
|
108
|
+
refreshBuffer?: number;
|
|
109
|
+
|
|
110
|
+
// Optional: path to service worker (default: '/tilery-sw.js')
|
|
111
|
+
serviceWorkerPath?: string;
|
|
112
|
+
}
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
#### Methods
|
|
116
|
+
|
|
117
|
+
```typescript
|
|
118
|
+
// Get current token (fetches if needed, cached otherwise)
|
|
119
|
+
const token = await client.getToken();
|
|
120
|
+
|
|
121
|
+
// Register service worker
|
|
122
|
+
await client.registerServiceWorker();
|
|
123
|
+
|
|
124
|
+
// Get MapLibre-compatible style (fetched from the tile server, token injected)
|
|
125
|
+
const style = await client.getMapStyle({
|
|
126
|
+
flavor: "light", // see GET {tileServer}/map/styles for the full list
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
// Get URL templates
|
|
130
|
+
const tileUrl = await client.getTileUrlTemplate();
|
|
131
|
+
const glyphsUrl = client.getGlyphsUrl();
|
|
132
|
+
const spriteUrl = client.getSpriteUrl("dark");
|
|
133
|
+
|
|
134
|
+
// Clean up
|
|
135
|
+
client.destroy();
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
#### Events
|
|
139
|
+
|
|
140
|
+
```typescript
|
|
141
|
+
client.on("token:refresh", (token) => {
|
|
142
|
+
console.log("Token refreshed, expires at:", token.exp);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
client.on("token:error", (error) => {
|
|
146
|
+
console.error("Token refresh failed:", error);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
client.on("sw:registered", (registration) => {
|
|
150
|
+
console.log("Service worker registered");
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
client.on("sw:error", (error) => {
|
|
154
|
+
console.error("Service worker failed:", error);
|
|
155
|
+
});
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
## Backend Token Endpoint
|
|
159
|
+
|
|
160
|
+
Your backend should exchange an API key for a short-lived JWT. Example with the Tilery API:
|
|
161
|
+
|
|
162
|
+
```typescript
|
|
163
|
+
// /api/tile-token.ts (your backend)
|
|
164
|
+
export async function GET(request: Request) {
|
|
165
|
+
const res = await fetch("https://tilery.eu/api/tokens/exchange", {
|
|
166
|
+
method: "POST",
|
|
167
|
+
headers: {
|
|
168
|
+
Authorization: `Bearer ${process.env.TILERY_API_KEY}`,
|
|
169
|
+
"Content-Type": "application/json",
|
|
170
|
+
},
|
|
171
|
+
body: JSON.stringify({ ttl: 900 }), // 15 minutes
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
return res.json(); // { token: string, exp: number }
|
|
175
|
+
}
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Manual Usage (without MapLibre helper)
|
|
179
|
+
|
|
180
|
+
```typescript
|
|
181
|
+
const client = new TileryClient({
|
|
182
|
+
getToken: async () => fetch("/api/tile-token").then((r) => r.json()),
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
// Get token and build URLs manually
|
|
186
|
+
const token = await client.getToken();
|
|
187
|
+
const tileUrl = `https://api.tilery.eu/tiles/{z}/{x}/{y}?token=${token.token}`;
|
|
188
|
+
|
|
189
|
+
// Use with any mapping library
|
|
190
|
+
const map = new maplibregl.Map({
|
|
191
|
+
container: "map",
|
|
192
|
+
style: {
|
|
193
|
+
version: 8,
|
|
194
|
+
sources: {
|
|
195
|
+
tiles: {
|
|
196
|
+
type: "vector",
|
|
197
|
+
tiles: [tileUrl],
|
|
198
|
+
maxzoom: 14,
|
|
199
|
+
},
|
|
200
|
+
},
|
|
201
|
+
layers: [
|
|
202
|
+
/* your layers */
|
|
203
|
+
],
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
## Service Worker Messages
|
|
209
|
+
|
|
210
|
+
You can communicate with the service worker for cache management:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
// Clear all cached tiles
|
|
214
|
+
navigator.serviceWorker.controller?.postMessage({ type: "CLEAR_CACHE" });
|
|
215
|
+
|
|
216
|
+
// Get cache size
|
|
217
|
+
const channel = new MessageChannel();
|
|
218
|
+
channel.port1.onmessage = (e) => console.log("Cache size:", e.data.size);
|
|
219
|
+
navigator.serviceWorker.controller?.postMessage({ type: "GET_CACHE_SIZE" }, [channel.port2]);
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
## License
|
|
223
|
+
|
|
224
|
+
MIT
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { EventListener, MapStyle, MapStyleOptions, TileToken, TileryClientEvents, TileryClientOptions } from "./types.js";
|
|
2
|
+
/**
|
|
3
|
+
* Tilery client for managing tile tokens and service worker caching.
|
|
4
|
+
*
|
|
5
|
+
* @example
|
|
6
|
+
* ```ts
|
|
7
|
+
* const client = new TileryClient({
|
|
8
|
+
* getToken: async () => {
|
|
9
|
+
* const res = await fetch('/api/tile-token');
|
|
10
|
+
* return res.json();
|
|
11
|
+
* },
|
|
12
|
+
* });
|
|
13
|
+
*
|
|
14
|
+
* await client.registerServiceWorker();
|
|
15
|
+
* const style = await client.getMapStyle({ flavor: 'dark' });
|
|
16
|
+
* ```
|
|
17
|
+
*/
|
|
18
|
+
export declare class TileryClient {
|
|
19
|
+
private readonly getTokenFn;
|
|
20
|
+
private readonly tileServer;
|
|
21
|
+
private readonly refreshBuffer;
|
|
22
|
+
private readonly swPath;
|
|
23
|
+
private currentToken;
|
|
24
|
+
private refreshTimeout;
|
|
25
|
+
private tokenPromise;
|
|
26
|
+
private listeners;
|
|
27
|
+
constructor(options: TileryClientOptions);
|
|
28
|
+
/**
|
|
29
|
+
* Get current valid token, fetching if needed.
|
|
30
|
+
* Token is cached and auto-refreshed before expiry.
|
|
31
|
+
*/
|
|
32
|
+
getToken(): Promise<TileToken>;
|
|
33
|
+
/**
|
|
34
|
+
* Get the current token string, or null if not yet fetched.
|
|
35
|
+
* Does not trigger a fetch - use getToken() for that.
|
|
36
|
+
*/
|
|
37
|
+
getCurrentTokenString(): string | null;
|
|
38
|
+
/**
|
|
39
|
+
* Register the service worker for tile caching.
|
|
40
|
+
* Normalizes cache keys by stripping the token param for long-lived caching.
|
|
41
|
+
*
|
|
42
|
+
* Requires a service worker file at the configured path (default: /tilery-sw.js).
|
|
43
|
+
* Create it with: import { SERVICE_WORKER_CODE } from '@tilery/client';
|
|
44
|
+
*
|
|
45
|
+
* @returns Promise that resolves when registration completes
|
|
46
|
+
*/
|
|
47
|
+
registerServiceWorker(): Promise<ServiceWorkerRegistration | null>;
|
|
48
|
+
/**
|
|
49
|
+
* Get the service worker code as a string.
|
|
50
|
+
* Use this to create the service worker file in your build process.
|
|
51
|
+
*/
|
|
52
|
+
static getServiceWorkerCode(): string;
|
|
53
|
+
/**
|
|
54
|
+
* Build a tile URL with the current token as query parameter.
|
|
55
|
+
*/
|
|
56
|
+
buildTileUrl(options: {
|
|
57
|
+
token?: string;
|
|
58
|
+
z: number;
|
|
59
|
+
x: number;
|
|
60
|
+
y: number;
|
|
61
|
+
}): string;
|
|
62
|
+
/**
|
|
63
|
+
* Get the tile URL template with {z}, {x}, {y} placeholders.
|
|
64
|
+
* Token is appended as query parameter.
|
|
65
|
+
*/
|
|
66
|
+
getTileUrlTemplate(): Promise<string>;
|
|
67
|
+
/**
|
|
68
|
+
* Get the font (glyph) URL template.
|
|
69
|
+
*/
|
|
70
|
+
getGlyphsUrl(): string;
|
|
71
|
+
/**
|
|
72
|
+
* Get the sprite URL for a given flavor.
|
|
73
|
+
*/
|
|
74
|
+
getSpriteUrl(flavor: string): string;
|
|
75
|
+
/**
|
|
76
|
+
* Fetch a MapLibre-compatible style from the tile server and inject the
|
|
77
|
+
* current token into the tile source URLs.
|
|
78
|
+
*
|
|
79
|
+
* @example
|
|
80
|
+
* ```ts
|
|
81
|
+
* const style = await client.getMapStyle({ flavor: 'dark' });
|
|
82
|
+
* const map = new maplibregl.Map({ container: 'map', style });
|
|
83
|
+
* ```
|
|
84
|
+
*/
|
|
85
|
+
getMapStyle(options?: MapStyleOptions): Promise<MapStyle>;
|
|
86
|
+
/**
|
|
87
|
+
* Subscribe to an event.
|
|
88
|
+
*/
|
|
89
|
+
on<K extends keyof TileryClientEvents>(event: K, listener: EventListener<TileryClientEvents[K]>): void;
|
|
90
|
+
/**
|
|
91
|
+
* Unsubscribe from an event.
|
|
92
|
+
*/
|
|
93
|
+
off<K extends keyof TileryClientEvents>(event: K, listener: EventListener<TileryClientEvents[K]>): void;
|
|
94
|
+
/**
|
|
95
|
+
* Stop token refresh and clean up.
|
|
96
|
+
*/
|
|
97
|
+
destroy(): void;
|
|
98
|
+
private emit;
|
|
99
|
+
private isTokenExpiringSoon;
|
|
100
|
+
private fetchAndScheduleRefresh;
|
|
101
|
+
private scheduleRefresh;
|
|
102
|
+
}
|
|
103
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,aAAa,EAEb,QAAQ,EACR,eAAe,EACf,SAAS,EACT,kBAAkB,EAClB,mBAAmB,EACpB,MAAM,YAAY,CAAC;AASpB;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,YAAY;IACvB,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAa;IACxC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAS;IACp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AIP;;OAEG;IACH,OAAO,IAAI,IAAI;IAYf,OAAO,CAAC,IAAI;IAUZ,OAAO,CAAC,mBAAmB;YAKb,uBAAuB;IAcrC,OAAO,CAAC,eAAe;CAqBxB"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { TileryClient } from "./client.js";
|
|
2
|
+
export { default as SERVICE_WORKER_CODE } from "virtual:service-worker-code";
|
|
3
|
+
export type { TileryClientOptions, TileryClientEvents, TileToken, GetTokenFn, MapStyleOptions, MapStyle, EventListener, } from "./types.js";
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAC3C,OAAO,EAAE,OAAO,IAAI,mBAAmB,EAAE,MAAM,6BAA6B,CAAC;AAC7E,YAAY,EACV,mBAAmB,EACnB,kBAAkB,EAClB,SAAS,EACT,UAAU,EACV,eAAe,EACf,QAAQ,EACR,aAAa,GACd,MAAM,YAAY,CAAC"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
//#region \0virtual:service-worker-code
|
|
2
|
+
var code = "const r=globalThis,c=\"tilery-tiles-v1\",l=/\\/tiles\\/\\d+\\/\\d+\\/\\d+/;function o(e){const t=new URL(e);return t.searchParams.delete(\"token\"),t.toString()}function h(e){return l.test(e)}r.addEventListener(\"install\",e=>{e.waitUntil(r.skipWaiting())}),r.addEventListener(\"activate\",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(t=>Promise.all(t.filter(s=>s.startsWith(\"tilery-\")&&s!==c).map(s=>caches.delete(s))))]))}),r.addEventListener(\"fetch\",e=>{const{request:t}=e;h(t.url)&&e.respondWith(d(t))});async function d(e){const t=await caches.open(c),s=o(e.url),n=await t.match(s);if(n)return n;try{const a=await fetch(e);if(a.ok){const i=a.clone();t.put(s,i)}return a}catch(a){const i=await t.match(s);if(i)return i;throw a}}r.addEventListener(\"message\",e=>{const{type:t,payload:s}=e.data||{};switch(t){case\"CLEAR_CACHE\":e.waitUntil(caches.delete(c).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case\"GET_CACHE_SIZE\":e.waitUntil(caches.open(c).then(async n=>{const a=await n.keys();e.ports[0]?.postMessage({size:a.length})}));break;case\"DELETE_TILE\":if(s?.url){const n=o(s.url);e.waitUntil(caches.open(c).then(async a=>{const i=await a.delete(n);e.ports[0]?.postMessage({deleted:i})}))}break}});export{};\n";
|
|
3
|
+
//#endregion
|
|
4
|
+
//#region src/client.ts
|
|
5
|
+
var MS_PER_SECOND = 1e3;
|
|
6
|
+
var DEFAULT_TILE_SERVER = "https://api.tilery.eu";
|
|
7
|
+
var DEFAULT_REFRESH_BUFFER = 60;
|
|
8
|
+
var DEFAULT_SW_PATH = "/tilery-sw.js";
|
|
9
|
+
/**
|
|
10
|
+
* Tilery client for managing tile tokens and service worker caching.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* const client = new TileryClient({
|
|
15
|
+
* getToken: async () => {
|
|
16
|
+
* const res = await fetch('/api/tile-token');
|
|
17
|
+
* return res.json();
|
|
18
|
+
* },
|
|
19
|
+
* });
|
|
20
|
+
*
|
|
21
|
+
* await client.registerServiceWorker();
|
|
22
|
+
* const style = await client.getMapStyle({ flavor: 'dark' });
|
|
23
|
+
* ```
|
|
24
|
+
*/
|
|
25
|
+
var TileryClient = class {
|
|
26
|
+
constructor(options) {
|
|
27
|
+
this.currentToken = null;
|
|
28
|
+
this.refreshTimeout = null;
|
|
29
|
+
this.tokenPromise = null;
|
|
30
|
+
this.listeners = /* @__PURE__ */ new Map();
|
|
31
|
+
this.getTokenFn = options.getToken;
|
|
32
|
+
this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;
|
|
33
|
+
this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;
|
|
34
|
+
this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Get current valid token, fetching if needed.
|
|
38
|
+
* Token is cached and auto-refreshed before expiry.
|
|
39
|
+
*/
|
|
40
|
+
async getToken() {
|
|
41
|
+
if (this.currentToken && !this.isTokenExpiringSoon(this.currentToken)) return this.currentToken;
|
|
42
|
+
if (this.tokenPromise) return this.tokenPromise;
|
|
43
|
+
this.tokenPromise = this.fetchAndScheduleRefresh();
|
|
44
|
+
try {
|
|
45
|
+
return await this.tokenPromise;
|
|
46
|
+
} finally {
|
|
47
|
+
this.tokenPromise = null;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Get the current token string, or null if not yet fetched.
|
|
52
|
+
* Does not trigger a fetch - use getToken() for that.
|
|
53
|
+
*/
|
|
54
|
+
getCurrentTokenString() {
|
|
55
|
+
return this.currentToken?.token ?? null;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Register the service worker for tile caching.
|
|
59
|
+
* Normalizes cache keys by stripping the token param for long-lived caching.
|
|
60
|
+
*
|
|
61
|
+
* Requires a service worker file at the configured path (default: /tilery-sw.js).
|
|
62
|
+
* Create it with: import { SERVICE_WORKER_CODE } from '@tilery/client';
|
|
63
|
+
*
|
|
64
|
+
* @returns Promise that resolves when registration completes
|
|
65
|
+
*/
|
|
66
|
+
async registerServiceWorker() {
|
|
67
|
+
if (typeof navigator === "undefined" || !("serviceWorker" in navigator)) {
|
|
68
|
+
console.warn("[TileryClient] Service workers not supported");
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
try {
|
|
72
|
+
const registration = await navigator.serviceWorker.register(this.swPath, {
|
|
73
|
+
scope: "/",
|
|
74
|
+
type: "classic"
|
|
75
|
+
});
|
|
76
|
+
this.emit("sw:registered", registration);
|
|
77
|
+
console.log("[TileryClient] Service worker registered");
|
|
78
|
+
return registration;
|
|
79
|
+
} catch (error) {
|
|
80
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
81
|
+
this.emit("sw:error", err);
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Get the service worker code as a string.
|
|
87
|
+
* Use this to create the service worker file in your build process.
|
|
88
|
+
*/
|
|
89
|
+
static getServiceWorkerCode() {
|
|
90
|
+
return code;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Build a tile URL with the current token as query parameter.
|
|
94
|
+
*/
|
|
95
|
+
buildTileUrl(options) {
|
|
96
|
+
const { token, x, y, z } = options;
|
|
97
|
+
const tok = token ?? this.currentToken?.token;
|
|
98
|
+
if (!tok) throw new Error("No token available. Call getToken() first.");
|
|
99
|
+
return `${this.tileServer}/map/tiles/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Get the tile URL template with {z}, {x}, {y} placeholders.
|
|
103
|
+
* Token is appended as query parameter.
|
|
104
|
+
*/
|
|
105
|
+
async getTileUrlTemplate() {
|
|
106
|
+
const token = await this.getToken();
|
|
107
|
+
return `${this.tileServer}/map/tiles/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Get the font (glyph) URL template.
|
|
111
|
+
*/
|
|
112
|
+
getGlyphsUrl() {
|
|
113
|
+
return `${this.tileServer}/map/fonts/{fontstack}/{range}.pbf`;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Get the sprite URL for a given flavor.
|
|
117
|
+
*/
|
|
118
|
+
getSpriteUrl(flavor) {
|
|
119
|
+
return `${this.tileServer}/map/sprites/v4/${flavor}`;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Fetch a MapLibre-compatible style from the tile server and inject the
|
|
123
|
+
* current token into the tile source URLs.
|
|
124
|
+
*
|
|
125
|
+
* @example
|
|
126
|
+
* ```ts
|
|
127
|
+
* const style = await client.getMapStyle({ flavor: 'dark' });
|
|
128
|
+
* const map = new maplibregl.Map({ container: 'map', style });
|
|
129
|
+
* ```
|
|
130
|
+
*/
|
|
131
|
+
async getMapStyle(options = {}) {
|
|
132
|
+
const { flavor = "light" } = options;
|
|
133
|
+
const [token, res] = await Promise.all([this.getToken(), fetch(`${this.tileServer}/map/styles/${encodeURIComponent(flavor)}`)]);
|
|
134
|
+
if (!res.ok) throw new Error(`Failed to fetch style "${flavor}": ${res.status} ${res.statusText}`);
|
|
135
|
+
const style = await res.json();
|
|
136
|
+
const tokenParam = `token=${encodeURIComponent(token.token)}`;
|
|
137
|
+
for (const source of Object.values(style.sources)) source.tiles = source.tiles.map((url) => url.includes("?") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`);
|
|
138
|
+
return style;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Subscribe to an event.
|
|
142
|
+
*/
|
|
143
|
+
on(event, listener) {
|
|
144
|
+
if (!this.listeners.has(event)) this.listeners.set(event, /* @__PURE__ */ new Set());
|
|
145
|
+
this.listeners.get(event).add(listener);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Unsubscribe from an event.
|
|
149
|
+
*/
|
|
150
|
+
off(event, listener) {
|
|
151
|
+
this.listeners.get(event)?.delete(listener);
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Stop token refresh and clean up.
|
|
155
|
+
*/
|
|
156
|
+
destroy() {
|
|
157
|
+
if (this.refreshTimeout) {
|
|
158
|
+
clearTimeout(this.refreshTimeout);
|
|
159
|
+
this.refreshTimeout = null;
|
|
160
|
+
}
|
|
161
|
+
this.currentToken = null;
|
|
162
|
+
this.tokenPromise = null;
|
|
163
|
+
this.listeners.clear();
|
|
164
|
+
}
|
|
165
|
+
emit(event, data) {
|
|
166
|
+
this.listeners.get(event)?.forEach((listener) => {
|
|
167
|
+
try {
|
|
168
|
+
listener(data);
|
|
169
|
+
} catch (e) {
|
|
170
|
+
console.error(`[TileryClient] Error in ${event} listener:`, e);
|
|
171
|
+
}
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
isTokenExpiringSoon(token) {
|
|
175
|
+
const now = Math.floor(Date.now() / MS_PER_SECOND);
|
|
176
|
+
return token.exp <= now + this.refreshBuffer;
|
|
177
|
+
}
|
|
178
|
+
async fetchAndScheduleRefresh() {
|
|
179
|
+
try {
|
|
180
|
+
const token = await this.getTokenFn();
|
|
181
|
+
this.currentToken = token;
|
|
182
|
+
this.scheduleRefresh(token);
|
|
183
|
+
this.emit("token:refresh", token);
|
|
184
|
+
return token;
|
|
185
|
+
} catch (error) {
|
|
186
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
187
|
+
this.emit("token:error", err);
|
|
188
|
+
throw err;
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
scheduleRefresh(token) {
|
|
192
|
+
if (this.refreshTimeout) clearTimeout(this.refreshTimeout);
|
|
193
|
+
const now = Math.floor(Date.now() / MS_PER_SECOND);
|
|
194
|
+
const refreshAt = token.exp - this.refreshBuffer;
|
|
195
|
+
const delayMs = Math.max(0, (refreshAt - now) * MS_PER_SECOND);
|
|
196
|
+
this.refreshTimeout = setTimeout(async () => {
|
|
197
|
+
try {
|
|
198
|
+
this.tokenPromise = this.fetchAndScheduleRefresh();
|
|
199
|
+
await this.tokenPromise;
|
|
200
|
+
} catch (e) {
|
|
201
|
+
console.error("[TileryClient] Token refresh failed:", e);
|
|
202
|
+
} finally {
|
|
203
|
+
this.tokenPromise = null;
|
|
204
|
+
}
|
|
205
|
+
}, delayMs);
|
|
206
|
+
}
|
|
207
|
+
};
|
|
208
|
+
//#endregion
|
|
209
|
+
export { code as SERVICE_WORKER_CODE, TileryClient };
|
|
210
|
+
|
|
211
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/client.ts"],"sourcesContent":["// oxlint-disable id-length\nimport type {\n EventListener,\n GetTokenFn,\n MapStyle,\n MapStyleOptions,\n TileToken,\n TileryClientEvents,\n TileryClientOptions,\n} from \"./types.js\";\n\nimport serviceWorkerCode from \"virtual:service-worker-code\";\n\nconst MS_PER_SECOND = 1000;\nconst DEFAULT_TILE_SERVER = \"https://api.tilery.eu\";\nconst DEFAULT_REFRESH_BUFFER = 60;\nconst DEFAULT_SW_PATH = \"/tilery-sw.js\";\n\n/**\n * Tilery client for managing tile tokens and service worker caching.\n *\n * @example\n * ```ts\n * const client = new TileryClient({\n * getToken: async () => {\n * const res = await fetch('/api/tile-token');\n * return res.json();\n * },\n * });\n *\n * await client.registerServiceWorker();\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * ```\n */\nexport class TileryClient {\n private readonly getTokenFn: GetTokenFn;\n private readonly tileServer: string;\n private readonly refreshBuffer: number;\n private readonly swPath: string;\n\n private currentToken: TileToken | null = null;\n private refreshTimeout: ReturnType<typeof setTimeout> | null = null;\n private tokenPromise: Promise<TileToken> | null = null;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private listeners = new Map<keyof TileryClientEvents, Set<EventListener<any>>>();\n\n constructor(options: TileryClientOptions) {\n this.getTokenFn = options.getToken;\n this.tileServer = options.tileServer ?? DEFAULT_TILE_SERVER;\n this.refreshBuffer = options.refreshBuffer ?? DEFAULT_REFRESH_BUFFER;\n this.swPath = options.serviceWorkerPath ?? DEFAULT_SW_PATH;\n }\n\n /**\n * Get current valid token, fetching if needed.\n * Token is cached and auto-refreshed before expiry.\n */\n async getToken(): Promise<TileToken> {\n // Return cached token if still valid (with buffer)\n if (this.currentToken && !this.isTokenExpiringSoon(this.currentToken)) {\n return this.currentToken;\n }\n\n // If already fetching, wait for that promise\n if (this.tokenPromise) {\n return this.tokenPromise;\n }\n\n // Fetch new token\n this.tokenPromise = this.fetchAndScheduleRefresh();\n try {\n return await this.tokenPromise;\n } finally {\n this.tokenPromise = null;\n }\n }\n\n /**\n * Get the current token string, or null if not yet fetched.\n * Does not trigger a fetch - use getToken() for that.\n */\n getCurrentTokenString(): string | null {\n return this.currentToken?.token ?? null;\n }\n\n /**\n * Register the service worker for tile caching.\n * Normalizes cache keys by stripping the token param for long-lived caching.\n *\n * Requires a service worker file at the configured path (default: /tilery-sw.js).\n * Create it with: import { SERVICE_WORKER_CODE } from '@tilery/client';\n *\n * @returns Promise that resolves when registration completes\n */\n async registerServiceWorker(): Promise<ServiceWorkerRegistration | null> {\n if (typeof navigator === \"undefined\" || !(\"serviceWorker\" in navigator)) {\n console.warn(\"[TileryClient] Service workers not supported\");\n return null;\n }\n\n try {\n const registration = await navigator.serviceWorker.register(this.swPath, {\n scope: \"/\",\n type: \"classic\",\n });\n this.emit(\"sw:registered\", registration);\n console.log(\"[TileryClient] Service worker registered\");\n return registration;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit(\"sw:error\", err);\n throw err;\n }\n }\n\n /**\n * Get the service worker code as a string.\n * Use this to create the service worker file in your build process.\n */\n static getServiceWorkerCode(): string {\n return serviceWorkerCode;\n }\n\n /**\n * Build a tile URL with the current token as query parameter.\n */\n buildTileUrl(options: { token?: string; z: number; x: number; y: number }): string {\n const { token, x, y, z } = options;\n const tok = token ?? this.currentToken?.token;\n if (!tok) {\n throw new Error(\"No token available. Call getToken() first.\");\n }\n return `${this.tileServer}/map/tiles/${z}/${x}/${y}?token=${encodeURIComponent(tok)}`;\n }\n\n /**\n * Get the tile URL template with {z}, {x}, {y} placeholders.\n * Token is appended as query parameter.\n */\n async getTileUrlTemplate(): Promise<string> {\n const token = await this.getToken();\n return `${this.tileServer}/map/tiles/{z}/{x}/{y}?token=${encodeURIComponent(token.token)}`;\n }\n\n /**\n * Get the font (glyph) URL template.\n */\n getGlyphsUrl(): string {\n return `${this.tileServer}/map/fonts/{fontstack}/{range}.pbf`;\n }\n\n /**\n * Get the sprite URL for a given flavor.\n */\n getSpriteUrl(flavor: string): string {\n return `${this.tileServer}/map/sprites/v4/${flavor}`;\n }\n\n /**\n * Fetch a MapLibre-compatible style from the tile server and inject the\n * current token into the tile source URLs.\n *\n * @example\n * ```ts\n * const style = await client.getMapStyle({ flavor: 'dark' });\n * const map = new maplibregl.Map({ container: 'map', style });\n * ```\n */\n async getMapStyle(options: MapStyleOptions = {}): Promise<MapStyle> {\n const { flavor = \"light\" } = options;\n\n const [token, res] = await Promise.all([\n this.getToken(),\n fetch(`${this.tileServer}/map/styles/${encodeURIComponent(flavor)}`),\n ]);\n\n if (!res.ok) {\n throw new Error(`Failed to fetch style \"${flavor}\": ${res.status} ${res.statusText}`);\n }\n\n const style = (await res.json()) as MapStyle;\n const tokenParam = `token=${encodeURIComponent(token.token)}`;\n\n for (const source of Object.values(style.sources)) {\n source.tiles = source.tiles.map((url) =>\n url.includes(\"?\") ? `${url}&${tokenParam}` : `${url}?${tokenParam}`,\n );\n }\n\n return style;\n }\n\n /**\n * Subscribe to an event.\n */\n on<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n if (!this.listeners.has(event)) {\n this.listeners.set(event, new Set());\n }\n this.listeners.get(event)!.add(listener);\n }\n\n /**\n * Unsubscribe from an event.\n */\n off<K extends keyof TileryClientEvents>(\n event: K,\n listener: EventListener<TileryClientEvents[K]>,\n ): void {\n this.listeners.get(event)?.delete(listener);\n }\n\n /**\n * Stop token refresh and clean up.\n */\n destroy(): void {\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n this.refreshTimeout = null;\n }\n this.currentToken = null;\n this.tokenPromise = null;\n this.listeners.clear();\n }\n\n // ---- Private methods ----\n\n private emit<K extends keyof TileryClientEvents>(event: K, data: TileryClientEvents[K]): void {\n this.listeners.get(event)?.forEach((listener) => {\n try {\n listener(data);\n } catch (e) {\n console.error(`[TileryClient] Error in ${event} listener:`, e);\n }\n });\n }\n\n private isTokenExpiringSoon(token: TileToken): boolean {\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n return token.exp <= now + this.refreshBuffer;\n }\n\n private async fetchAndScheduleRefresh(): Promise<TileToken> {\n try {\n const token = await this.getTokenFn();\n this.currentToken = token;\n this.scheduleRefresh(token);\n this.emit(\"token:refresh\", token);\n return token;\n } catch (error) {\n const err = error instanceof Error ? error : new Error(String(error));\n this.emit(\"token:error\", err);\n throw err;\n }\n }\n\n private scheduleRefresh(token: TileToken): void {\n if (this.refreshTimeout) {\n clearTimeout(this.refreshTimeout);\n }\n\n const now = Math.floor(Date.now() / MS_PER_SECOND);\n const refreshAt = token.exp - this.refreshBuffer;\n const delayMs = Math.max(0, (refreshAt - now) * MS_PER_SECOND);\n\n this.refreshTimeout = setTimeout(async () => {\n try {\n this.tokenPromise = this.fetchAndScheduleRefresh();\n await this.tokenPromise;\n } catch (e) {\n // Error already emitted via event\n console.error(\"[TileryClient] Token refresh failed:\", e);\n } finally {\n this.tokenPromise = null;\n }\n }, delayMs);\n }\n}\n"],"mappings":";;;;AAaA,IAAM,gBAAgB;AACtB,IAAM,sBAAsB;AAC5B,IAAM,yBAAyB;AAC/B,IAAM,kBAAkB;;;;;;;;;;;;;;;;;AAkBxB,IAAa,eAAb,MAA0B;CAaxB,YAAY,SAA8B;sBAPD;wBACsB;sBACb;mCAG9B,IAAI,KAAwD;AAG9E,OAAK,aAAa,QAAQ;AAC1B,OAAK,aAAa,QAAQ,cAAc;AACxC,OAAK,gBAAgB,QAAQ,iBAAiB;AAC9C,OAAK,SAAS,QAAQ,qBAAqB;;;;;;CAO7C,MAAM,WAA+B;AAEnC,MAAI,KAAK,gBAAgB,CAAC,KAAK,oBAAoB,KAAK,aAAa,CACnE,QAAO,KAAK;AAId,MAAI,KAAK,aACP,QAAO,KAAK;AAId,OAAK,eAAe,KAAK,yBAAyB;AAClD,MAAI;AACF,UAAO,MAAM,KAAK;YACV;AACR,QAAK,eAAe;;;;;;;CAQxB,wBAAuC;AACrC,SAAO,K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AAK,KAAK,eAAe,IAAI;AAC7B,SAAM;;;CAIV,gBAAwB,OAAwB;AAC9C,MAAI,KAAK,eACP,cAAa,KAAK,eAAe;EAGnC,MAAM,MAAM,KAAK,MAAM,KAAK,KAAK,GAAG,cAAc;EAClD,MAAM,YAAY,MAAM,MAAM,KAAK;EACnC,MAAM,UAAU,KAAK,IAAI,IAAI,YAAY,OAAO,cAAc;AAE9D,OAAK,iBAAiB,WAAW,YAAY;AAC3C,OAAI;AACF,SAAK,eAAe,KAAK,yBAAyB;AAClD,UAAM,KAAK;YACJ,GAAG;AAEV,YAAQ,MAAM,wCAAwC,EAAE;aAChD;AACR,SAAK,eAAe;;KAErB,QAAQ"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tilery Service Worker
|
|
3
|
+
*
|
|
4
|
+
* Caches tile requests with normalized cache keys (token stripped).
|
|
5
|
+
* This allows tiles to be cached across token rotations.
|
|
6
|
+
*
|
|
7
|
+
* Usage: Copy this file to your public directory (e.g., /tilery-sw.js)
|
|
8
|
+
* and register it via TileryClient.registerServiceWorker()
|
|
9
|
+
*/
|
|
10
|
+
export {};
|
|
11
|
+
//# sourceMappingURL=service-worker.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"service-worker.d.ts","sourceRoot":"","sources":["../src/service-worker.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAmIH,OAAO,EAAE,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
const r=globalThis,c="tilery-tiles-v1",l=/\/tiles\/\d+\/\d+\/\d+/;function o(e){const t=new URL(e);return t.searchParams.delete("token"),t.toString()}function h(e){return l.test(e)}r.addEventListener("install",e=>{e.waitUntil(r.skipWaiting())}),r.addEventListener("activate",e=>{e.waitUntil(Promise.all([r.clients.claim(),caches.keys().then(t=>Promise.all(t.filter(s=>s.startsWith("tilery-")&&s!==c).map(s=>caches.delete(s))))]))}),r.addEventListener("fetch",e=>{const{request:t}=e;h(t.url)&&e.respondWith(d(t))});async function d(e){const t=await caches.open(c),s=o(e.url),n=await t.match(s);if(n)return n;try{const a=await fetch(e);if(a.ok){const i=a.clone();t.put(s,i)}return a}catch(a){const i=await t.match(s);if(i)return i;throw a}}r.addEventListener("message",e=>{const{type:t,payload:s}=e.data||{};switch(t){case"CLEAR_CACHE":e.waitUntil(caches.delete(c).then(()=>{e.ports[0]?.postMessage({success:!0})}));break;case"GET_CACHE_SIZE":e.waitUntil(caches.open(c).then(async n=>{const a=await n.keys();e.ports[0]?.postMessage({size:a.length})}));break;case"DELETE_TILE":if(s?.url){const n=o(s.url);e.waitUntil(caches.open(c).then(async a=>{const i=await a.delete(n);e.ports[0]?.postMessage({deleted:i})}))}break}});export{};
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Token response from the user's token endpoint.
|
|
3
|
+
*/
|
|
4
|
+
export interface TileToken {
|
|
5
|
+
/** JWT token string */
|
|
6
|
+
token: string;
|
|
7
|
+
/** Expiry timestamp (unix seconds) */
|
|
8
|
+
exp: number;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Async function that fetches a new tile token.
|
|
12
|
+
* User provides this to keep API key server-side.
|
|
13
|
+
*/
|
|
14
|
+
export type GetTokenFn = () => Promise<TileToken>;
|
|
15
|
+
/**
|
|
16
|
+
* Configuration options for TileryClient.
|
|
17
|
+
*/
|
|
18
|
+
export interface TileryClientOptions {
|
|
19
|
+
/**
|
|
20
|
+
* Async function that returns a tile token.
|
|
21
|
+
* Called on init and when token needs refresh.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* getToken: async () => {
|
|
26
|
+
* const res = await fetch('/api/tile-token', { credentials: 'include' });
|
|
27
|
+
* if (!res.ok) throw new Error('Failed to get token');
|
|
28
|
+
* return res.json();
|
|
29
|
+
* }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
getToken: GetTokenFn;
|
|
33
|
+
/**
|
|
34
|
+
* Tile server URL. Set to `https://api.test.tilery.eu` to point at the
|
|
35
|
+
* staging environment.
|
|
36
|
+
* @default 'https://api.tilery.eu'
|
|
37
|
+
*/
|
|
38
|
+
tileServer?: string;
|
|
39
|
+
/**
|
|
40
|
+
* Seconds before expiry to refresh token.
|
|
41
|
+
* @default 60
|
|
42
|
+
*/
|
|
43
|
+
refreshBuffer?: number;
|
|
44
|
+
/**
|
|
45
|
+
* Path to the service worker script.
|
|
46
|
+
* Required for Firefox (doesn't support blob: URLs for service workers).
|
|
47
|
+
* Create a file with: import { SERVICE_WORKER_CODE } from '@tilery/client';
|
|
48
|
+
* @default '/tilery-sw.js'
|
|
49
|
+
*/
|
|
50
|
+
serviceWorkerPath?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Options for getMapStyle().
|
|
54
|
+
*/
|
|
55
|
+
export interface MapStyleOptions {
|
|
56
|
+
/**
|
|
57
|
+
* Style identifier as served by the tile server (e.g. 'light', 'dark',
|
|
58
|
+
* 'grayscale', 'poster-light', 'nordic-frost'). The full list is
|
|
59
|
+
* available from `GET {tileServer}/map/styles`.
|
|
60
|
+
* @default 'light'
|
|
61
|
+
*/
|
|
62
|
+
flavor?: string;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* MapLibre-compatible style specification (simplified).
|
|
66
|
+
*/
|
|
67
|
+
export interface MapStyle {
|
|
68
|
+
version: 8;
|
|
69
|
+
glyphs: string;
|
|
70
|
+
sprite: string;
|
|
71
|
+
sources: Record<string, {
|
|
72
|
+
type: "vector";
|
|
73
|
+
tiles: string[];
|
|
74
|
+
maxzoom: number;
|
|
75
|
+
attribution: string;
|
|
76
|
+
}>;
|
|
77
|
+
layers: unknown[];
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Events emitted by TileryClient.
|
|
81
|
+
*/
|
|
82
|
+
export interface TileryClientEvents {
|
|
83
|
+
/** Emitted when token is successfully refreshed */
|
|
84
|
+
"token:refresh": TileToken;
|
|
85
|
+
/** Emitted when token refresh fails */
|
|
86
|
+
"token:error": Error;
|
|
87
|
+
/** Emitted when service worker is registered */
|
|
88
|
+
"sw:registered": ServiceWorkerRegistration;
|
|
89
|
+
/** Emitted when service worker registration fails */
|
|
90
|
+
"sw:error": Error;
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* Event listener function type.
|
|
94
|
+
*/
|
|
95
|
+
export type EventListener<T> = (data: T) => void;
|
|
96
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,SAAS;IACxB,uBAAuB;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,sCAAsC;IACtC,GAAG,EAAE,MAAM,CAAC;CACb;AAED;;;GAGG;AACH,MAAM,MAAM,UAAU,GAAG,MAAM,OAAO,CAAC,SAAS,CAAC,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC;;;;;;;;;;;;OAYG;IACH,QAAQ,EAAE,UAAU,CAAC;IAErB;;;;OAIG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB;;;;;OAKG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;CAC5B;AAED;;GAEG;AACH,MAAM,WAAW,eAAe;IAC9B;;;;;OAKG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,OAAO,EAAE,CAAC,CAAC;IACX,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,CACb,MAAM,EACN;QACE,IAAI,EAAE,QAAQ,CAAC;QACf,KAAK,EAAE,MAAM,EAAE,CAAC;QAChB,OAAO,EAAE,MAAM,CAAC;QAChB,WAAW,EAAE,MAAM,CAAC;KACrB,CACF,CAAC;IACF,MAAM,EAAE,OAAO,EAAE,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC,mDAAmD;IACnD,eAAe,EAAE,SAAS,CAAC;IAC3B,uCAAuC;IACvC,aAAa,EAAE,KAAK,CAAC;IACrB,gDAAgD;IAChD,eAAe,EAAE,yBAAyB,CAAC;IAC3C,qDAAqD;IACrD,UAAU,EAAE,KAAK,CAAC;CACnB;AAED;;GAEG;AACH,MAAM,MAAM,aAAa,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,CAAC,KAAK,IAAI,CAAC"}
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@tilery/client",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Client library for Tilery.eu tile API with service worker caching",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"maplibre",
|
|
7
|
+
"maps",
|
|
8
|
+
"service-worker",
|
|
9
|
+
"tilery",
|
|
10
|
+
"tiles",
|
|
11
|
+
"vector-tiles"
|
|
12
|
+
],
|
|
13
|
+
"license": "MIT",
|
|
14
|
+
"author": "Snorre Magnus Davøen",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"email": "support@tilery.eu"
|
|
17
|
+
},
|
|
18
|
+
"publishConfig": {
|
|
19
|
+
"access": "public"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"type": "module",
|
|
26
|
+
"main": "./dist/index.js",
|
|
27
|
+
"module": "./dist/index.js",
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"exports": {
|
|
30
|
+
".": {
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"import": "./dist/index.js"
|
|
33
|
+
}
|
|
34
|
+
},
|
|
35
|
+
"scripts": {
|
|
36
|
+
"build": "vite build && tsc --emitDeclarationOnly",
|
|
37
|
+
"dev": "vite build --watch",
|
|
38
|
+
"prepublishOnly": "npm run build",
|
|
39
|
+
"test": "vitest run",
|
|
40
|
+
"test:watch": "vitest"
|
|
41
|
+
}
|
|
42
|
+
}
|