shared-hosting-sync 0.1.3 → 0.1.5

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.
@@ -1,3 +1,4 @@
1
+ import { syncScope } from './syncState.js'
1
2
  import { resolveEnv, credsFromResolved } from './envResolver.js'
2
3
  import { assertLocalFolder } from '../onboarding.js'
3
4
  import { validateRemotePath } from '../paths.js'
@@ -11,11 +12,13 @@ export function resolveDeployment(project, options = {}) {
11
12
  ...project, localPath: assertLocalFolder(project.localPath),
12
13
  remotePath: validateRemotePath(resolved.values.DEVSYNC_REMOTE_PATH)
13
14
  }
15
+ target.syncScope = syncScope(target, credsFromResolved(resolved.values))
14
16
  return {
15
17
  project: target,
16
18
  matcher: buildMatcher(target.localPath),
17
19
  creds: credsFromResolved(resolved.values),
18
20
  dryRun: ['true', '1', true].includes(resolved.values.DEVSYNC_DRY_RUN),
21
+ concurrency: Number(resolved.values.DEVSYNC_CONCURRENCY),
19
22
  debounceMs: Number(resolved.values.DEVSYNC_DEBOUNCE_MS),
20
23
  values: resolved.values
21
24
  }
@@ -82,6 +82,15 @@ export const ENV_SCHEMA = [
82
82
  label: 'Dry run',
83
83
  help: 'Plan and report without uploading.'
84
84
  },
85
+ {
86
+ key: 'DEVSYNC_CONCURRENCY',
87
+ type: 'int',
88
+ default: 3,
89
+ min: 1,
90
+ max: 8,
91
+ label: 'Parallel uploads',
92
+ help: 'Upload queues (1–8). Default 3. Use 1 if your host limits connections.'
93
+ },
85
94
  {
86
95
  key: 'DEVSYNC_DEBOUNCE_MS',
87
96
  type: 'int',
@@ -0,0 +1,9 @@
1
+ import fs from 'node:fs'
2
+
3
+ export const fingerprint = (stat) => ({ size: stat.size, mtimeMs: stat.mtimeMs, ctimeMs: stat.ctimeMs })
4
+ export const sameFile = (a, b) => !!a && !!b && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs
5
+ export function currentFingerprint(abs) {
6
+ try { const stat = fs.statSync(abs); return stat.isFile() ? fingerprint(stat) : null }
7
+ catch (error) { if (error.code === 'ENOENT') return null; throw error }
8
+ }
9
+
@@ -0,0 +1,18 @@
1
+ -- Persistent sync metadata scoped to the project source and hosting destination.
2
+ CREATE TABLE sync_targets (
3
+ project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
4
+ target_key TEXT NOT NULL,
5
+ scanned_at TEXT,
6
+ PRIMARY KEY (project_id, target_key)
7
+ );
8
+ CREATE TABLE sync_files (
9
+ project_id INTEGER NOT NULL,
10
+ target_key TEXT NOT NULL,
11
+ relative_path TEXT NOT NULL,
12
+ size INTEGER NOT NULL,
13
+ mtime_ms REAL NOT NULL,
14
+ ctime_ms REAL NOT NULL,
15
+ synced_at TEXT NOT NULL,
16
+ PRIMARY KEY (project_id, target_key, relative_path),
17
+ FOREIGN KEY (project_id, target_key) REFERENCES sync_targets(project_id, target_key) ON DELETE CASCADE
18
+ );
@@ -0,0 +1,65 @@
1
+ import crypto from 'node:crypto'
2
+ import { sameFile, currentFingerprint } from './fileFingerprint.js'
3
+ import { openDb } from './db.js'
4
+
5
+ /** Credentials are deliberately excluded; changes to source or destination get a new baseline. */
6
+ export function syncScope(project, creds) {
7
+ return {
8
+ projectId: project.id,
9
+ targetKey: crypto.createHash('sha256').update(JSON.stringify([
10
+ project.localPath, creds.transport, String(creds.host).toLowerCase(),
11
+ Number(creds.port), creds.username, project.remotePath
12
+ ])).digest('hex')
13
+ }
14
+ }
15
+
16
+
17
+ export function readSyncFiles(scope) {
18
+ return new Map(openDb().prepare(`SELECT relative_path, size, mtime_ms, ctime_ms FROM sync_files
19
+ WHERE project_id = ? AND target_key = ?`).all(scope.projectId, scope.targetKey)
20
+ .map(row => [row.relative_path, { size: row.size, mtimeMs: row.mtime_ms, ctimeMs: row.ctime_ms }]))
21
+ }
22
+
23
+ export function syncStatus(scope) {
24
+ const db = openDb()
25
+ const target = db.prepare('SELECT scanned_at FROM sync_targets WHERE project_id = ? AND target_key = ?').get(scope.projectId, scope.targetKey)
26
+ const { count } = db.prepare('SELECT COUNT(*) AS count FROM sync_files WHERE project_id = ? AND target_key = ?').get(scope.projectId, scope.targetKey)
27
+ return { trackedFiles: count, scannedAt: target?.scanned_at || null, ready: !!target }
28
+ }
29
+
30
+ function ensureTarget(db, scope) {
31
+ db.prepare('INSERT OR IGNORE INTO sync_targets (project_id, target_key) VALUES (?, ?)').run(scope.projectId, scope.targetKey)
32
+ }
33
+ function writeFile(db, scope, rel, value) {
34
+ db.prepare(`INSERT INTO sync_files (project_id, target_key, relative_path, size, mtime_ms, ctime_ms, synced_at)
35
+ VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(project_id, target_key, relative_path) DO UPDATE SET
36
+ size=excluded.size, mtime_ms=excluded.mtime_ms, ctime_ms=excluded.ctime_ms, synced_at=excluded.synced_at`)
37
+ .run(scope.projectId, scope.targetKey, rel, value.size, value.mtimeMs, value.ctimeMs, new Date().toISOString())
38
+ }
39
+
40
+ /** Save only the exact local version that was uploaded successfully. */
41
+ export function recordUploadedFile(scope, item) {
42
+ const db = openDb()
43
+ if (!sameFile(item.fingerprint, currentFingerprint(item.abs))) {
44
+ db.prepare('DELETE FROM sync_files WHERE project_id = ? AND target_key = ? AND relative_path = ?').run(scope.projectId, scope.targetKey, item.rel)
45
+ return
46
+ }
47
+ ensureTarget(db, scope)
48
+ writeFile(db, scope, item.rel, item.fingerprint)
49
+ }
50
+
51
+ /** Commit a completed read-only server scan atomically; failed scans leave the previous baseline intact. */
52
+ export function replaceScannedFiles(scope, matches) {
53
+ const db = openDb()
54
+ db.exec('BEGIN IMMEDIATE')
55
+ try {
56
+ ensureTarget(db, scope)
57
+ db.prepare('DELETE FROM sync_files WHERE project_id = ? AND target_key = ?').run(scope.projectId, scope.targetKey)
58
+ for (const item of matches) {
59
+ if (sameFile(item.fingerprint, currentFingerprint(item.abs))) writeFile(db, scope, item.rel, item.fingerprint)
60
+ }
61
+ db.prepare('UPDATE sync_targets SET scanned_at = ? WHERE project_id = ? AND target_key = ?')
62
+ .run(new Date().toISOString(), scope.projectId, scope.targetKey)
63
+ db.exec('COMMIT')
64
+ } catch (error) { db.exec('ROLLBACK'); throw error }
65
+ }
@@ -2,7 +2,8 @@ import crypto from 'node:crypto'
2
2
  import { getProject, setStatus, recordSync } from '../core/projects.js'
3
3
  import { resolveDeployment } from '../core/deployment.js'
4
4
  import { createTransport } from '../transport/index.js'
5
- import { buildPlan, runPlan } from '../uploader.js'
5
+ import { syncStatus } from '../core/syncState.js'
6
+ import { buildPlan, runPlan, scanServer } from '../uploader.js'
6
7
  import { ProjectWatcher } from '../watcher.js'
7
8
  import { acquireOperation, assertProjectIdle, projectOperation } from '../core/operationLock.js'
8
9
 
@@ -36,7 +37,10 @@ export class DeploymentService {
36
37
  projectId: project.id, kind: null, state: 'idle', phase: 'idle', logs: [], plan: null,
37
38
  result: null, progress: null, lastError: project.lastStatus === 'error' ? project.lastError : null
38
39
  }
40
+ let baseline = null
41
+ try { baseline = syncStatus(resolveDeployment(project, { useEnvFileEnvironment: false }).project.syncScope) } catch {}
39
42
  return structuredClone({
43
+ baseline,
40
44
  ...view, active: this.isBusy(project.id), externalOperation: !this.isBusy(project.id) ? projectOperation(project.id) : null,
41
45
  watching: !!(record?.watcher || record?.view.kind === 'watch' && record?.task),
42
46
  stopping: !!record?.stopping, lastSyncAt: project.lastSyncAt, lastUploadBytes: project.lastUploadBytes
@@ -56,7 +60,7 @@ export class DeploymentService {
56
60
  }
57
61
 
58
62
  progress(record, event) {
59
- if (!record.stopRequested) record.view.phase = event.phase === 'planning' ? 'planning' : 'uploading'
63
+ if (!record.stopRequested) record.view.phase = event.phase === 'inventory' ? 'inventory' : event.phase === 'planning' ? 'planning' : 'uploading'
60
64
  record.view.progress = {
61
65
  current: event.index, total: event.total, file: this.clean(record, event.item.rel),
62
66
  bytes: record.view.progress?.bytes || 0
@@ -65,6 +69,7 @@ export class DeploymentService {
65
69
  }
66
70
 
67
71
  plan(record, plan) {
72
+ record.view.workers = []
68
73
  record.view.plan = {
69
74
  considered: plan.totalFiles, uploadCount: plan.uploads.length, skippedCount: plan.skipped.length,
70
75
  bytes: plan.comparedBytes,
@@ -78,6 +83,15 @@ export class DeploymentService {
78
83
  this.log(record, `Compared ${plan.totalFiles} files: ${plan.uploads.length} to upload, ${plan.skipped.length} unchanged`)
79
84
  }
80
85
 
86
+ workerState(record, event) {
87
+ record.view.workers ||= []
88
+ const current = record.view.workers.findIndex(worker => worker.workerId === event.workerId)
89
+ const value = { workerId: event.workerId, state: event.state, file: event.file ? this.clean(record, event.file) : null }
90
+ if (current < 0) record.view.workers.push(value)
91
+ else record.view.workers[current] = value
92
+ record.view.updatedAt = stamp()
93
+ }
94
+
81
95
  fileResult(record, event) {
82
96
  record.view.progress = { current: event.index + 1, total: event.total, file: this.clean(record, event.item.rel), bytes: event.bytes }
83
97
  this.log(record, event.success ? `${event.dryRun ? 'Would upload' : 'Uploaded'} ${event.item.rel}` : `Failed ${event.item.rel}: ${event.error}`, event.success ? 'info' : 'error')
@@ -104,15 +118,16 @@ export class DeploymentService {
104
118
 
105
119
  start(id, kind, options = {}) {
106
120
  if (this.closing) throw fail('The dashboard is shutting down', 503)
107
- if (!['preview', 'deploy', 'sync', 'watch'].includes(kind)) throw fail('Unknown deployment operation')
121
+ if (!['preview', 'deploy', 'sync', 'watch', 'scan'].includes(kind)) throw fail('Unknown deployment operation')
108
122
  if (!options || typeof options !== 'object' || Array.isArray(options)) throw fail('Operation options must be an object')
123
+ if (kind === 'scan' && options.confirmed !== true) throw fail('Confirm the first-time server scan before continuing')
109
124
  if (options.dryRun !== undefined && typeof options.dryRun !== 'boolean') throw fail('dryRun must be a boolean')
110
125
  if (options.mode !== undefined && !['sync', 'deploy'].includes(options.mode)) throw fail('Preview mode must be sync or deploy')
111
126
  const project = getProject(Number(id))
112
127
  if (!project) throw fail('Project not found', 404)
113
128
  if (this.isBusy(project.id)) throw fail('This project already has an operation running. Stop watching or wait for it to finish.', 409)
114
129
  const context = resolveDeployment(project, { useEnvFileEnvironment: false })
115
- const dryRun = kind === 'preview' || context.dryRun || !!options.dryRun
130
+ const dryRun = kind === 'scan' || kind === 'preview' || context.dryRun || !!options.dryRun
116
131
  const release = acquireOperation(project.id, kind, { creds: context.creds, remotePath: context.project.remotePath })
117
132
  const record = {
118
133
  context, release, task: null, watcher: null, transport: null, stopping: null, stopRequested: false,
@@ -120,7 +135,7 @@ export class DeploymentService {
120
135
  projectId: project.id, operationId: crypto.randomUUID(), kind,
121
136
  mode: kind === 'preview' ? options.mode || 'sync' : kind === 'deploy' ? 'deploy' : 'sync',
122
137
  state: 'running', phase: 'connecting', dryRun, plan: null, result: null, progress: null,
123
- logs: [], lastError: null, startedAt: stamp(), updatedAt: stamp(), remotePath: context.project.remotePath
138
+ logs: [], workers: [], concurrency: context.concurrency, lastError: null, startedAt: stamp(), updatedAt: stamp(), remotePath: context.project.remotePath
124
139
  }
125
140
  }
126
141
  this.records.set(project.id, record)
@@ -138,14 +153,34 @@ export class DeploymentService {
138
153
  }
139
154
 
140
155
  async execute(record) {
141
- record.transport = await this.connect(record.context.creds, undefined, {
142
- onRetry: ({ attempt, retries }) => this.log(record, `Connection interrupted; reconnecting (${attempt}/${retries})`, 'warning')
143
- })
156
+ const connect = async () => {
157
+ record.view.phase = 'connecting'
158
+ record.transport = await this.connect(record.context.creds, undefined, {
159
+ onRetry: ({ attempt, retries }) => this.log(record, `Connection interrupted; reconnecting (${attempt}/${retries})`, 'warning')
160
+ })
161
+ }
144
162
  if (record.stopRequested || this.closing) return
145
163
  const context = record.context
164
+ const createWorker = () => this.connect(context.creds, undefined, { retries: 0 })
165
+ if (record.view.kind === 'scan') {
166
+ await connect()
167
+ const plan = await scanServer(context.project, context.matcher, record.transport, { onProgress: (event) => this.progress(record, event) })
168
+ this.plan(record, plan)
169
+ record.view.result = { uploaded: 0, planned: plan.uploads.length, failed: [], failedCount: 0, bytes: 0, dryRun: true, scanned: plan.totalFiles, matched: plan.skipped.length }
170
+ record.view.state = 'success'
171
+ record.view.phase = 'complete'
172
+ record.view.progress = { current: plan.totalFiles, total: plan.totalFiles, file: null, bytes: 0 }
173
+ setStatus(record.view.projectId, 'idle')
174
+ this.log(record, `Server scan complete: ${plan.skipped.length} matching files saved; ${plan.uploads.length} new or changed. No files uploaded. Use Sync changes next.`, 'success')
175
+ return
176
+ }
146
177
  if (record.view.kind === 'watch') {
178
+ await connect()
179
+ if (record.stopRequested || this.closing) return
147
180
  const watcher = this.watcherFactory(context.project, context.matcher, record.transport, {
148
181
  dryRun: record.view.dryRun, debounceMs: context.debounceMs,
182
+ createWorker, concurrency: context.concurrency,
183
+ onWorkerState: event => this.workerState(record, event),
149
184
  onProgress: (event) => this.progress(record, event),
150
185
  onPlan: (plan) => this.plan(record, plan),
151
186
  onFileResult: (event) => this.fileResult(record, event),
@@ -172,7 +207,9 @@ export class DeploymentService {
172
207
  })
173
208
  this.plan(record, plan)
174
209
  const result = await runPlan(plan, record.transport, {
175
- dryRun: record.view.dryRun,
210
+ dryRun: record.view.dryRun, createWorker, concurrency: context.concurrency,
211
+ onWorkerState: event => this.workerState(record, event),
212
+ onRetry: event => this.log(record, `Queue ${event.workerId}: ${event.connectionFailure ? 'connection unavailable' : event.item.rel + ' interrupted'}; returned to the pending queue.`, 'warning'),
176
213
  onProgress: (event) => this.progress(record, event), onFileResult: (event) => this.fileResult(record, event)
177
214
  })
178
215
  this.complete(record, { done: result.done.length, failed: result.failed, bytes: result.bytes, dryRun: record.view.dryRun })
@@ -12,7 +12,8 @@ const UI_DIR = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'ui
12
12
  const assets = new Map([
13
13
  ['/', ['index.html', 'text/html']], ['/index.html', ['index.html', 'text/html']],
14
14
  ['/ui.js', ['ui.js', 'application/javascript']], ['/style.css', ['style.css', 'text/css']],
15
- ['/deployments.js', ['deployments.js', 'application/javascript']]
15
+ ['/deployments.js', ['deployments.js', 'application/javascript']],
16
+ ['/logo.svg', ['logo.svg', 'image/svg+xml']]
16
17
  ])
17
18
 
18
19
  export async function startServer({ port = 5180, host = '127.0.0.1', openBrowser = true } = {}) {
@@ -112,7 +112,7 @@ export async function handle(req, res, { onboarding, deployments } = {}) {
112
112
  // All routes below need auth.
113
113
  if (!sessionOk(req, res)) return
114
114
 
115
- const deploymentMatch = url.pathname.match(/^\/api\/projects\/(\d+)\/(activity|preview|deploy|sync|watch)(\/stop)?$/)
115
+ const deploymentMatch = url.pathname.match(/^\/api\/projects\/(\d+)\/(activity|preview|deploy|sync|watch|scan)(\/stop)?$/)
116
116
  if (deploymentMatch) {
117
117
  if (!deployments) return json(res, 503, { error: 'Deployment service is unavailable' })
118
118
  const [, id, action, stop] = deploymentMatch
@@ -35,7 +35,7 @@ export class FtpTransport {
35
35
  const items = await this.client.list(remotePath || '/')
36
36
  return items.map((e) => ({
37
37
  name: e.name,
38
- type: e.isDirectory ? 'dir' : 'file',
38
+ type: e.isDirectory ? 'dir' : e.isFile ? 'file' : 'other',
39
39
  size: e.size ?? 0,
40
40
  mtime: e.modifyTime ? new Date(e.modifyTime) : null
41
41
  }))
@@ -19,15 +19,15 @@ export class ReliableTransport {
19
19
 
20
20
  async connect() { await this.transaction(async () => {}); return this }
21
21
 
22
- async transaction(action) {
22
+ async transaction(action, { retries = this.retries } = {}) {
23
23
  for (let attempt = 0; ; attempt++) {
24
24
  if (this.closed) throw new Error('Transport has been closed')
25
25
  try {
26
26
  this.raw ||= await this.connectRaw()
27
27
  return await action(this.raw)
28
28
  } catch (error) {
29
- if (!isTransient(error) || attempt >= this.retries || this.closed) throw error
30
- this.onRetry({ attempt: attempt + 1, retries: this.retries })
29
+ if (!isTransient(error) || attempt >= retries || this.closed) throw error
30
+ this.onRetry({ attempt: attempt + 1, retries })
31
31
  if (this.raw) await this.raw.close().catch(() => {})
32
32
  this.raw = null
33
33
  await delay(this.retryDelayMs * 2 ** attempt)
@@ -40,7 +40,7 @@ export class SftpTransport {
40
40
  .filter((e) => e.name !== '.' && e.name !== '..')
41
41
  .map((e) => ({
42
42
  name: e.name,
43
- type: e.type === 'd' ? 'dir' : 'file',
43
+ type: e.type === 'd' ? 'dir' : e.type === '-' ? 'file' : 'other',
44
44
  size: e.size ?? 0,
45
45
  mtime: e.modifyTime ? new Date(e.modifyTime) : null
46
46
  }))
@@ -50,7 +50,13 @@ export class SftpTransport {
50
50
  if (!remotePath) return
51
51
  const type = await this.client.exists(remotePath)
52
52
  if (type && type !== 'd') throw new Error(`Remote directory path is occupied by a file: ${remotePath}`)
53
- if (!type) await this.client.mkdir(remotePath, true)
53
+ if (!type) {
54
+ try { await this.client.mkdir(remotePath, true) }
55
+ catch (error) {
56
+ // Another upload worker may have created the same directory meanwhile.
57
+ if (await this.client.exists(remotePath) !== 'd') throw error
58
+ }
59
+ }
54
60
  }
55
61
 
56
62
  async exists(remotePath) {
@@ -24,10 +24,11 @@ export class DeploymentPanel {
24
24
  this.settingsDryRun = ['true', '1', true].includes(configuration.values.DEVSYNC_DRY_RUN)
25
25
  this.configured = !Object.keys(configuration.errors).length
26
26
  const element = document.querySelector('#deploymentPanel')
27
- element.innerHTML = `<h2>Deploy your project</h2><p class="muted">Deploy uploads all eligible files. Sync uploads only changed files. Server files are never deleted.</p><div class="operation-options"><div class="field"><label for="previewMode">Preview mode</label><select id="previewMode"><option value="sync">Changed files (sync)</option><option value="deploy">All eligible files (deploy)</option></select></div><label class="check"><input id="operationDryRun" type="checkbox" ${this.settingsDryRun ? 'checked disabled' : ''}>Preview only for deploy, sync and watch</label></div>${this.settingsDryRun ? '<p class="help">Preview-only mode is enabled in this project’s settings.</p>' : ''}<div class="operation-actions"><button class="secondary" id="previewUploads">Preview uploads</button><button class="primary" id="deployFiles">Deploy all files</button><button class="secondary" id="syncFiles">Sync changes</button><button class="secondary" id="startWatching">Start watching</button><button class="danger" id="stopWatching" hidden>Stop watching</button></div><p class="help">Watch syncs current files first, then follows saves while devsync is running. Stop waits for the current batch to finish.</p><div id="operationStatus" class="notice" role="status"></div><div class="operation-progress"><progress id="uploadProgress" max="1" value="0" aria-label="Operation progress"></progress><span id="progressText" class="help"></span></div><div id="operationResult"></div><div id="operationPlan"></div><details id="activityDetails"><summary>Activity log</summary><ol class="operation-log" id="operationLogs"><li>No operations yet.</li></ol></details><p id="lastSync" class="help"></p>`
27
+ element.innerHTML = `<h2>Deploy your project</h2><p class="muted">Sync checks local file sizes and timestamps against your saved sync records. Deploy uploads all eligible files. Server files are never deleted. Up to ${Number(configuration.values.DEVSYNC_CONCURRENCY) || 3} upload queues share the work and retry interrupted files.</p><div class="operation-options"><div class="field"><label for="previewMode">Preview mode</label><select id="previewMode"><option value="sync">Changed files (sync)</option><option value="deploy">All eligible files (deploy)</option></select></div><label class="check"><input id="operationDryRun" type="checkbox" ${this.settingsDryRun ? 'checked disabled' : ''}>Preview only for deploy, sync and watch</label></div>${this.settingsDryRun ? '<p class="help">Preview-only mode is enabled in this project’s settings.</p>' : ''}<div class="operation-actions"><button class="secondary" id="previewUploads">Preview uploads</button><button class="secondary" id="deployFiles">Deploy all files</button><button class="primary" id="syncFiles">Sync changes</button><button class="secondary" id="startWatching">Start watching</button><button class="danger" id="stopWatching" hidden>Stop watching</button></div><div class="sync-baseline"><p id="syncBaseline" class="help"></p><button class="secondary" id="scanServer">Scan server / Initial sync</button><p class="help">Use this button only if you are syncing for the first time. It lists server folders first, then checks local files and saves verified matches without uploading. After that, use Sync changes.</p></div><p class="help">Watch syncs current files first, then follows saves while devsync is running. Stop waits for the current batch to finish.</p><div id="operationStatus" class="notice" role="status"></div><div class="operation-progress"><progress id="uploadProgress" max="1" value="0" aria-label="Operation progress"></progress><span id="progressText" class="help"></span></div><div id="uploadQueues" class="upload-queues" aria-label="Upload queues"></div><div id="operationResult"></div><div id="operationPlan"></div><details id="activityDetails"><summary>Activity log</summary><ol class="operation-log" id="operationLogs"><li>No operations yet.</li></ol></details><p id="lastSync" class="help"></p>`
28
28
  document.querySelector('#previewUploads').onclick = () => this.start('preview')
29
29
  document.querySelector('#deployFiles').onclick = () => this.start('deploy')
30
30
  document.querySelector('#syncFiles').onclick = () => this.start('sync')
31
+ document.querySelector('#scanServer').onclick = () => this.start('scan')
31
32
  document.querySelector('#startWatching').onclick = () => this.start('watch')
32
33
  document.querySelector('#stopWatching').onclick = () => this.run(async () => {
33
34
  this.message('')
@@ -38,10 +39,12 @@ export class DeploymentPanel {
38
39
  }
39
40
 
40
41
  start(kind) {
42
+ if (kind === 'scan' && !confirm('Are you sure?\n\nUse this button only if you are syncing for the first time.\n\nThis reads server files to rebuild your sync records. No files are uploaded or deleted. Use Sync changes for everyday uploads.')) return
41
43
  this.run(async () => {
42
44
  this.message('')
43
45
  const options = {
44
46
  dryRun: document.querySelector('#operationDryRun').checked,
47
+ ...(kind === 'scan' ? { confirmed: true } : {}),
45
48
  ...(kind === 'preview' ? { mode: document.querySelector('#previewMode').value } : {})
46
49
  }
47
50
  const result = await this.api('POST', `/api/projects/${this.projectId}/${kind}`, options)
@@ -82,7 +85,7 @@ export class DeploymentPanel {
82
85
  render(activity) {
83
86
  if (!this.projectId || activity.projectId !== this.projectId) return
84
87
  const busy = activity.active || !!activity.externalOperation
85
- for (const id of ['previewUploads', 'deployFiles', 'syncFiles', 'startWatching', 'previewMode']) this.disable(id, busy || !this.configured)
88
+ for (const id of ['previewUploads', 'deployFiles', 'syncFiles', 'startWatching', 'scanServer', 'previewMode']) this.disable(id, busy || !this.configured)
86
89
  this.disable('operationDryRun', busy || this.settingsDryRun || !this.configured)
87
90
  for (const id of ['editProject', 'testProject', 'deleteProject']) this.disable(id, busy)
88
91
  const startingWatch = activity.kind === 'watch' && busy
@@ -90,9 +93,10 @@ export class DeploymentPanel {
90
93
  document.querySelector('#stopWatching').hidden = !startingWatch
91
94
  this.disable('stopWatching', !startingWatch || activity.stopping)
92
95
  const status = document.querySelector('#operationStatus')
93
- const phases = { connecting: 'Connecting to hosting…', planning: 'Comparing local and server files…', uploading: activity.dryRun ? 'Building the preview…' : 'Uploading files…', watching: 'Watching for local saves.', stopping: 'Stopping watching — finishing the current batch…', complete: 'Operation complete.', error: 'Operation needs attention.', idle: 'Preview uploads before deploying, or start a sync when you are ready.' }
96
+ const phases = { connecting: 'Connecting to hosting…', inventory: 'Listing server folders…', planning: activity.kind === 'scan' ? 'Comparing local files and saving verified matches…' : 'Checking local files against saved sync records…', uploading: activity.dryRun ? 'Building the preview…' : 'Uploading files…', watching: 'Watching for local saves.', stopping: 'Stopping watching — finishing the current batch…', complete: 'Operation complete.', error: 'Operation needs attention.', idle: 'Preview uploads before deploying, or start a sync when you are ready.' }
94
97
  let text = activity.stopping ? phases.stopping : phases[activity.phase] || phases.idle
95
- if (activity.state === 'success') text = activity.dryRun ? 'Preview complete. No files were uploaded.' : 'Upload complete.'
98
+ if (activity.state === 'success') text = activity.dryRun ? 'Preview complete. No files were uploaded.' : activity.result?.uploaded === 0 ? 'Up to date. No uploads needed.' : 'Upload complete.'
99
+ if (activity.kind === 'scan' && activity.state === 'success') text = `Server scan complete. ${activity.result?.matched || 0} files matched; ${activity.plan?.uploadCount || 0} new or changed. Use Sync changes to upload them.`
96
100
  if (activity.state === 'stopped') text = 'Watching stopped. No further saves will be uploaded.'
97
101
  if (activity.externalOperation) text = 'An operation is running in another CLI or dashboard. Stop it there or wait for it to finish.'
98
102
  if (activity.lastError) text = `${activity.watching && !activity.stopping ? 'Watching is still active; the last sync failed. ' : ''}${activity.lastError} Check the connection and server folder permissions, then retry.`
@@ -104,8 +108,14 @@ export class DeploymentPanel {
104
108
  meter.max = Math.max(1, progress?.total || 0)
105
109
  meter.value = progress?.current || 0
106
110
  document.querySelector('#progressText').textContent = progress ? `${progress.current} / ${progress.total} files${progress.file ? ' · ' + progress.file : ''}${progress.bytes ? ' · ' + bytes(progress.bytes) : ''}` : ''
111
+ const baseline = activity.baseline
112
+ document.querySelector('#syncBaseline').textContent = baseline?.ready
113
+ ? `${baseline.trackedFiles} files tracked for this source and destination. Sync changes uses these records.${baseline.scannedAt ? ' Last server scan: ' + new Date(baseline.scannedAt).toLocaleString() + '.' : ''}`
114
+ : 'No sync records yet for this source and destination. If files are already on your server, scan once to avoid re-uploading matches. Otherwise, Sync changes uploads all eligible files and starts tracking them.'
115
+ const queueNames = { connecting: 'Connecting', uploading: 'Uploading', failed: 'Unavailable · work returned to queue', complete: 'Finished' }
116
+ document.querySelector('#uploadQueues').innerHTML = (activity.workers || []).sort((a, b) => a.workerId - b.workerId).map(worker => `<div class="upload-queue queue-${esc(worker.state)}"><strong>Queue ${worker.workerId}</strong><span>${esc(queueNames[worker.state] || worker.state)}</span>${worker.file ? `<small title="${esc(worker.file)}">${esc(worker.file)}</small>` : ''}</div>`).join('')
107
117
  const result = activity.result
108
- document.querySelector('#operationResult').innerHTML = result ? `<div class="operation-metrics"><div><strong>${result.dryRun ? result.planned : result.uploaded}</strong><span>${result.dryRun ? 'would upload' : 'uploaded'}</span></div><div><strong>${result.failedCount ?? result.failed.length}</strong><span>failed</span></div><div><strong>${bytes(result.bytes)}</strong><span>uploaded</span></div></div>${result.failed.length ? `<details open><summary>Files needing attention</summary><ul class="errors">${result.failed.map((file) => `<li>${esc(file.rel)} — ${esc(file.error)}</li>`).join('')}</ul></details>` : ''}` : ''
118
+ document.querySelector('#operationResult').innerHTML = result?.scanned !== undefined ? `<div class="operation-metrics"><div><strong>${result.scanned}</strong><span>files scanned</span></div><div><strong>${result.matched}</strong><span>matching files</span></div><div><strong>${result.planned}</strong><span>pending upload</span></div></div>` : result ? `<div class="operation-metrics"><div><strong>${result.dryRun ? result.planned : result.uploaded}</strong><span>${result.dryRun ? 'would upload' : 'uploaded'}</span></div><div><strong>${result.failedCount ?? result.failed.length}</strong><span>failed</span></div><div><strong>${bytes(result.bytes)}</strong><span>uploaded</span></div></div>${result.failed.length ? `<details open><summary>Files needing attention</summary><ul class="errors">${result.failed.map((file) => `<li>${esc(file.rel)} — ${esc(file.error)}</li>`).join('')}</ul></details>` : ''}` : ''
109
119
  this.renderPlan(activity.plan)
110
120
  const logSignature = JSON.stringify(activity.logs)
111
121
  if (logSignature !== this.lastLogs) {
@@ -124,6 +134,6 @@ export class DeploymentPanel {
124
134
  this.lastPlan = signature
125
135
  const element = document.querySelector('#operationPlan')
126
136
  if (!plan) { element.innerHTML = ''; return }
127
- element.innerHTML = `<div class="operation-metrics"><div><strong>${plan.considered}</strong><span>eligible files</span></div><div><strong>${plan.uploadCount}</strong><span>selected to upload</span></div><div><strong>${plan.skippedCount}</strong><span>unchanged</span></div><div><strong>${bytes(plan.bytes)}</strong><span>selected size</span></div></div><details open><summary>Selected files (${plan.uploadCount})</summary>${plan.uploads.length ? `<div class="plan-table-wrap"><table class="plan-table"><thead><tr><th>File</th><th>Server destination</th><th>Size</th></tr></thead><tbody>${plan.uploads.map((file) => `<tr><td>${esc(file.rel)}</td><td>${esc(file.remote)}</td><td>${bytes(file.bytes)}</td></tr>`).join('')}</tbody></table></div>` : '<p class="help">No files need uploading.</p>'}${plan.uploadCount > plan.uploads.length ? '<p class="help">Showing the first 200 selected files.</p>' : ''}</details><details><summary>Unchanged files (${plan.skippedCount})</summary><ul class="file-list">${plan.skipped.map((file) => `<li>${esc(file.rel)} <span class="muted">· ${esc(file.reason)}</span></li>`).join('') || '<li>No unchanged files.</li>'}</ul>${plan.skippedCount > plan.skipped.length ? '<p class="help">Showing the first 200 unchanged files.</p>' : ''}</details><details><summary>Excluded entries (${plan.excludedCount})</summary><ul class="file-list">${plan.excluded.map((file) => `<li>${esc(file.rel)} <span class="muted">· ${esc(file.reason)}</span></li>`).join('') || '<li>No excluded entries.</li>'}</ul><p class="help">Excluded directories represent their entire contents.${plan.excludedCount > plan.excluded.length ? ' Showing the first 200 entries.' : ''}</p></details><p class="help">Each operation checks current files and settings again. A preview never uploads or deletes files.</p>`
137
+ element.innerHTML = `<div class="operation-metrics"><div><strong>${plan.considered}</strong><span>eligible files</span></div><div><strong>${plan.uploadCount}</strong><span>selected to upload</span></div><div><strong>${plan.skippedCount}</strong><span>unchanged</span></div><div><strong>${bytes(plan.bytes)}</strong><span>selected size</span></div></div><details open><summary>Selected files (${plan.uploadCount})</summary>${plan.uploads.length ? `<div class="plan-table-wrap"><table class="plan-table"><thead><tr><th>File</th><th>Server destination</th><th>Size</th></tr></thead><tbody>${plan.uploads.map((file) => `<tr><td>${esc(file.rel)}</td><td>${esc(file.remote)}</td><td>${bytes(file.bytes)}</td></tr>`).join('')}</tbody></table></div>` : '<p class="help">No files need uploading.</p>'}${plan.uploadCount > plan.uploads.length ? '<p class="help">Showing the first 200 selected files.</p>' : ''}</details><details><summary>Unchanged files (${plan.skippedCount})</summary><ul class="file-list">${plan.skipped.map((file) => `<li>${esc(file.rel)} <span class="muted">· ${esc(file.reason)}</span></li>`).join('') || '<li>No unchanged files.</li>'}</ul>${plan.skippedCount > plan.skipped.length ? '<p class="help">Showing the first 200 unchanged files.</p>' : ''}</details><details><summary>Excluded entries (${plan.excludedCount})</summary><ul class="file-list">${plan.excluded.map((file) => `<li>${esc(file.rel)} <span class="muted">· ${esc(file.reason)}</span></li>`).join('') || '<li>No excluded entries.</li>'}</ul><p class="help">Excluded directories represent their entire contents.${plan.excludedCount > plan.excluded.length ? ' Showing the first 200 entries.' : ''}</p></details><p class="help">Sync checks current local metadata against saved records; it does not check for changes made directly on the server. A preview never changes sync records or uploads files.</p>`
128
138
  }
129
- }
139
+ }
package/src/ui/index.html CHANGED
@@ -3,32 +3,33 @@
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width,initial-scale=1">
6
- <title>shared-hosting-sync · Projects</title>
6
+ <title>DevSync · Projects</title>
7
+ <link rel="icon" type="image/svg+xml" href="/logo.svg">
7
8
  <link rel="stylesheet" href="/style.css">
8
9
  <script type="module" src="/ui.js"></script>
9
10
  </head>
10
11
  <body>
11
- <header class="topbar"><a class="brand" href="/">shared-hosting-sync<span class="brand-dot"></span></a><span class="topbar-note">Your projects. Your hosting.</span><span class="connection-pill" id="serverStatus">Connecting…</span></header>
12
+ <header class="topbar"><a class="brand" href="/" aria-label="DevSync home"><img class="brand-logo" src="/logo.svg" width="40" height="40" alt=""><span>Dev<span class="brand-accent">Sync</span></span></a><span class="topbar-note">Your projects. Your hosting.</span><span class="connection-pill" id="serverStatus">Connecting…</span></header>
12
13
  <div class="layout">
13
14
  <aside class="sidebar"><div class="sidebar-heading">PROJECTS <span id="projectCount">0</span></div><div id="projectList"></div><button class="add-project" id="addProject">+ Add project</button><button class="about-help-button secondary" id="openAboutHelp" aria-haspopup="dialog">About &amp; Help</button><div class="sidebar-note">Runs on this computer.<br>Hosting credentials stay local.</div></aside>
14
15
  <main id="pane" class="pane" aria-live="polite"><div class="empty">Loading your projects…</div></main>
15
16
  </div>
16
17
  <dialog id="aboutHelpDialog" class="about-help-dialog" aria-labelledby="aboutHelpTitle">
17
- <div class="about-help-heading"><div><p class="eyebrow">DEVSYNC</p><h1 id="aboutHelpTitle">About &amp; Help</h1></div><form method="dialog"><button class="secondary" aria-label="Close About and Help" autofocus>Close</button></form></div>
18
+ <div class="about-help-heading"><div><div class="about-brand"><img src="/logo.svg" width="52" height="52" alt=""><span>Dev<span class="brand-accent">Sync</span></span><span class="app-version" id="aboutVersion" role="status">Loading version…</span></div><p class="eyebrow">ABOUT THE APP</p><h1 id="aboutHelpTitle">About &amp; Help</h1></div><form method="dialog"><button class="secondary" aria-label="Close About and Help" autofocus>Close</button></form></div>
18
19
  <p class="sub">A simpler way to move local projects to your hosting.</p>
19
20
  <nav class="help-links" aria-label="About and help sections"><a href="#aboutCreator">About</a><a href="#gettingStarted">Getting started</a><a href="#commonQuestions">Common questions</a></nav>
20
21
  <section class="summary-card" id="aboutCreator" aria-labelledby="creatorTitle">
21
22
  <p class="eyebrow">MEET THE CREATOR</p><h2 id="creatorTitle">Rogers Kitamirike</h2><p class="muted">Ugandan developer · Creator of DevSync</p>
22
- <dl class="review"><dt>Phone</dt><dd><a href="tel:+256757035774">+256757035774</a></dd><dt>Email</dt><dd><a href="mailto:kitarogz@gmail.com">kitarogz@gmail.com</a></dd><dt>Package</dt><dd>shared-hosting-sync <span id="aboutVersion"></span></dd></dl>
23
+ <dl class="review"><dt>Phone</dt><dd><a href="tel:+256757035774">+256757035774</a></dd><dt>Email</dt><dd><a href="mailto:kitarogz@gmail.com">kitarogz@gmail.com</a></dd><dt>Package</dt><dd id="aboutPackage">shared-hosting-sync</dd></dl>
23
24
  <div class="help-links"><a href="https://github.com/kitaroghope/shared-hosting-sync#readme" target="_blank" rel="noopener noreferrer">Documentation ↗</a><a href="https://github.com/kitaroghope/shared-hosting-sync/issues" target="_blank" rel="noopener noreferrer">Report an issue ↗</a></div>
24
25
  </section>
25
26
  <section class="summary-card" id="gettingStarted" aria-labelledby="gettingStartedTitle"><h2 id="gettingStartedTitle">Get your first project online</h2>
26
- <ol class="help-steps"><li><strong>Add your local folder.</strong> Choose Add project, then select the folder to upload. For a built website, choose its build or dist folder.</li><li><strong>Connect your hosting.</strong> Enter your FTP, FTPS, or SFTP details, or load DEVSYNC_* settings from the folder’s .env. Test the connection to continue.</li><li><strong>Choose the server folder.</strong> Browse to the destination, select Use server folder, review, and save.</li><li><strong>Preview, then deploy.</strong> Preview uploads shows the planned files. Deploy uploads all eligible files; Sync uploads changed files. Watch follows subsequent saves while DevSync runs.</li></ol>
27
+ <ol class="help-steps"><li><strong>Add your local folder.</strong> Choose Add project, then select the folder to upload. For a built website, choose its build or dist folder.</li><li><strong>Connect your hosting.</strong> Enter your FTP, FTPS, or SFTP details, or load DEVSYNC_* settings from the folder’s .env. Test the connection to continue.</li><li><strong>Choose the server folder.</strong> Browse to the destination, select Use server folder, review, and save.</li><li><strong>Preview, then deploy.</strong> Preview uploads shows the planned files. Deploy uploads all eligible files; Sync compares local sizes and timestamps with saved sync records. Watch follows subsequent saves while DevSync runs. If your files are already on the server, use Scan server / Initial sync once to save matching files before your first sync.</li></ol>
27
28
  </section>
28
29
  <section class="summary-card" id="commonQuestions" aria-labelledby="commonQuestionsTitle"><h2 id="commonQuestionsTitle">Common questions</h2>
29
30
  <details><summary>How do I change a project’s local folder or hosting settings?</summary><p>Open the saved project and choose Edit setup. Change or browse for the local folder, review your hosting settings and destination, then save. Stop any active watch or upload before editing.</p></details>
30
31
  <details><summary>Why can’t I connect to my hosting?</summary><p>Confirm the host, protocol, port, username, and credentials with your hosting provider. FTP and FTPS usually use port 21; SFTP usually uses 22. If your ISP blocks port 21, ask your host whether SFTP or an alternative port is available. The server must support the protocol and port you choose.</p></details>
31
- <details><summary>Why are my changes not uploading?</summary><p>Check the selected local folder and server destination. Use Preview uploads to see which files are included or excluded, check whether Preview only is enabled, and open the Activity log for errors. Watch requires DevSync to remain running.</p></details>
32
+ <details><summary>Why are my changes not uploading?</summary><p>Check the selected local folder and server destination. Use Preview uploads to see which files are included or excluded, check whether Preview only is enabled, and open the Activity log for errors. Sync trusts its saved records and does not check for edits made directly on the server. Deploy all files can restore your local files to the server. Watch requires DevSync to remain running.</p></details>
32
33
  <details><summary>Which settings take priority?</summary><p>Settings in the selected folder’s .env take priority over .devsync.env and saved settings. If an edit appears to revert, check those files. DevSync does not rewrite your application’s environment files.</p></details>
33
34
  <details><summary>Are credentials and server files protected?</summary><p>Saved credentials are encrypted on this computer. Environment files and other protected files are excluded from deployment. Local deletions are never mirrored to the server. Preview uploads before deploying to confirm your destination and file list.</p></details>
34
35
  <details><summary>Can I use DevSync from a terminal?</summary><p>Run <code>devsync help</code> for commands, <code>devsync ui</code> for this dashboard, or <code>devsync doctor</code> to check your local installation. The <code>shared-hosting-sync</code> command works as an alias.</p></details>
@@ -0,0 +1,7 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64" fill="none">
2
+ <title>DevSync</title>
3
+ <rect x="1" y="1" width="62" height="62" rx="17" fill="#142724" stroke="#32554D" stroke-width="2"/>
4
+ <path d="M17 26C20 17 29 12 38 15C41 16 44 18 46 21M46 12V22H36" stroke="#77D6C1" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
5
+ <path d="M47 38C44 47 35 52 26 49C23 48 20 46 18 43M18 52V42H28" stroke="#A4C7FF" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
6
+ <path d="M25 27L30 32L25 37M35 37H41" stroke="#E7EDF6" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
7
+ </svg>
package/src/ui/style.css CHANGED
@@ -8,8 +8,7 @@ button:disabled{opacity:.5;cursor:default}
8
8
  button:focus-visible,a:focus-visible,summary:focus-visible{outline:2px solid var(--accent);outline-offset:3px}
9
9
  a{color:var(--blue)}
10
10
  .topbar{height:70px;display:flex;align-items:center;gap:28px;padding:0 28px;border-bottom:1px solid var(--line)}
11
- .brand{font-size:24px;font-weight:750;letter-spacing:-1px;text-decoration:none;color:var(--text);display:flex;align-items:center;gap:7px}
12
- .brand-dot{width:7px;height:7px;border-radius:50%;background:var(--accent)}
11
+ .brand{font-size:24px;font-weight:750;letter-spacing:-1px;text-decoration:none;color:var(--text);display:flex;align-items:center;gap:11px}
13
12
  .topbar-note{color:var(--muted);font-size:13px}
14
13
  .connection-pill{margin-left:auto;border:1px solid #33554e;border-radius:30px;padding:4px 12px;color:var(--accent);font-size:12px}
15
14
  .layout{display:grid;grid-template-columns:240px minmax(0,1fr);min-height:calc(100vh - 70px)}
@@ -139,3 +138,12 @@ h1{font-size:25px}
139
138
  .about-help-dialog section{scroll-margin-top:16px}.about-help-dialog details p{margin:12px 0 0;color:var(--muted)}
140
139
  .about-help-dialog code{color:var(--accent);overflow-wrap:anywhere}.about-help-footer{margin:24px 0 0}
141
140
  @media(max-width:580px){.about-help-dialog{padding:20px;max-height:92vh}.about-help-dialog .summary-card{padding:18px}.about-help-button{margin-top:10px}.about-help-dialog .review{margin:18px 0}}
141
+
142
+ .sync-baseline{border:1px solid var(--line);border-radius:8px;padding:16px;margin:20px 0;background:#10161f}.sync-baseline p:last-child{margin:12px 0 0}
143
+
144
+ .brand-logo{display:block;flex:none}.brand-accent{color:var(--accent)}.brand{white-space:nowrap}.about-brand{display:flex;align-items:center;gap:12px;font-size:27px;font-weight:750;letter-spacing:-1px;margin-bottom:24px}.about-brand img{display:block}
145
+ @media(max-width:580px){.brand{font-size:21px;gap:9px}.brand-logo{width:34px;height:34px}.topbar{gap:12px}.connection-pill{font-size:11px;padding:4px 9px}}
146
+
147
+ .about-brand{flex-wrap:wrap}.app-version{font-size:12px;line-height:1.5;font-weight:600;letter-spacing:0;color:var(--accent);background:#203e38;border:1px solid #33554e;border-radius:999px;padding:3px 10px}
148
+
149
+ .upload-queues{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:10px;margin:16px 0}.upload-queues:empty{display:none}.upload-queue{min-width:0;padding:12px;border:1px solid var(--line);border-radius:8px;background:#10161f}.upload-queue strong,.upload-queue span,.upload-queue small{display:block}.upload-queue span{font-size:12px;color:var(--muted);margin-top:4px}.upload-queue small{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--muted);margin-top:6px}.queue-uploading{border-color:#397367}.queue-uploading strong{color:var(--accent)}.queue-failed span{color:var(--danger)}