-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelfDeploy.js
More file actions
226 lines (196 loc) · 5.67 KB
/
Copy pathSelfDeploy.js
File metadata and controls
226 lines (196 loc) · 5.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
/**
* SelfDeploy - Auto-updating pages via Nostr git sync
*
* Enables pages to automatically reload when their source repo
* receives updates via Nostr announcements.
*/
import { NostrGitClient } from './NostrGitClient.js';
export class SelfDeploy {
/**
* Initialize self-deploying page
*
* @param {Object} options
* @param {string} options.repo - Git repository URL
* @param {string} options.repoId - Repository identifier (optional, derived from repo)
* @param {string} options.branch - Branch to track (default: 'main')
* @param {string[]} options.relays - Nostr relay URLs
* @param {string[]} options.trusted - Trusted publisher pubkeys (required for auto-reload)
* @param {Function} options.onUpdate - Called when update detected (default: reload page)
* @param {Function} options.onSync - Called after sync completes
* @param {Function} options.onError - Called on errors
* @param {boolean} options.autoReload - Auto reload on update (default: true)
* @param {number} options.reloadDelay - Delay before reload in ms (default: 1000)
* @param {string} options.corsProxy - CORS proxy URL (optional)
* @returns {SelfDeploy} Instance
*/
static init(options) {
return new SelfDeploy(options);
}
constructor(options) {
if (!options.repo) {
throw new Error('repo is required');
}
if (!options.trusted || options.trusted.length === 0) {
throw new Error('trusted pubkeys required for SelfDeploy');
}
this.options = {
autoReload: true,
reloadDelay: 1000,
branch: 'main',
...options
};
this.client = new NostrGitClient({
repo: this.options.repo,
repoId: this.options.repoId,
branch: this.options.branch,
relays: this.options.relays,
trusted: this.options.trusted,
corsProxy: this.options.corsProxy
});
this.currentCommit = null;
this.setupListeners();
this.client.connect();
}
setupListeners() {
// Track sync events
this.client.on('sync', (event) => {
if (event.status === 'complete') {
const isUpdate = this.currentCommit && this.currentCommit !== event.commit;
this.currentCommit = event.commit;
if (this.options.onSync) {
this.options.onSync(event);
}
if (isUpdate) {
this.handleUpdate(event);
}
}
if (event.status === 'error' && this.options.onError) {
this.options.onError(new Error(event.error));
}
});
// Track repo events from trusted publishers
this.client.on('event', (event) => {
if (event.type === 'repo') {
// New commit announced - trigger sync
if (event.commit !== this.currentCommit) {
this.client.sync(event.commit);
}
}
});
// Forward errors
this.client.on('error', (err) => {
if (this.options.onError) {
this.options.onError(err);
}
});
// Log connections
this.client.on('connect', (url) => {
console.log(`[SelfDeploy] Connected to ${url}`);
});
}
handleUpdate(event) {
console.log(`[SelfDeploy] Update detected: ${event.commit?.slice(0, 8)}`);
if (this.options.onUpdate) {
this.options.onUpdate(event);
}
if (this.options.autoReload) {
console.log(`[SelfDeploy] Reloading in ${this.options.reloadDelay}ms...`);
setTimeout(() => {
location.reload();
}, this.options.reloadDelay);
}
}
/**
* Manually trigger sync
* @returns {Promise<Object>} Sync result
*/
sync() {
return this.client.sync();
}
/**
* Get current commit info
* @returns {Promise<Object>} Commit info
*/
getCommit() {
return this.client.getCommit();
}
/**
* Read a file from the synced repo
* @param {string} path - File path
* @returns {Promise<string>} File content
*/
readFile(path) {
return this.client.readFile(path);
}
/**
* List files in directory
* @param {string} path - Directory path
* @returns {Promise<Array>} File entries
*/
listFiles(path) {
return this.client.listFiles(path);
}
/**
* Check if synced
* @returns {boolean}
*/
get synced() {
return this.client.synced;
}
/**
* Disconnect from relays
*/
disconnect() {
this.client.disconnect();
}
/**
* Create a minimal loader script for embedding
* Returns HTML that can be injected to enable self-deploy
*
* @param {Object} options - Same as constructor options
* @returns {string} Script tag HTML
*/
static loaderScript(options) {
const config = JSON.stringify(options);
return `<script type="module">
import { SelfDeploy } from 'nostr-git-client';
SelfDeploy.init(${config});
</script>`;
}
/**
* Create a service worker for offline-first self-deploy
* The service worker syncs in the background and notifies the page
*
* @returns {string} Service worker code
*/
static serviceWorkerCode() {
return `
// SelfDeploy Service Worker
// Syncs git repo in background and caches files
const CACHE_NAME = 'selfdeploy-v1';
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(clients.claim());
});
self.addEventListener('message', async (event) => {
if (event.data.type === 'SYNC') {
// Notify all clients of update
const clients = await self.clients.matchAll();
clients.forEach(client => {
client.postMessage({ type: 'UPDATE', commit: event.data.commit });
});
}
});
self.addEventListener('fetch', (event) => {
// Cache-first strategy for synced files
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request);
})
);
});
`;
}
}