Files
pages/static/js/city-generator-client.js
Anya Tokugawa c1175d389f Implement Knowledge City platform, organizer and DAV integration
Capture accumulated application, UI, CLI, regression tests and design documentation changes, including task project mapping and default CalDAV list naming.

Keep deployment data, backups, local credentials and build artifacts out of Git. Move the Compose enrollment token to an ignored local environment file.
2026-09-27 14:44:43 +09:00

106 lines
5.5 KiB
JavaScript

/* Geometry only: never put Page names, grants or topology into this cache. */
(() => {
'use strict';
const VERSION = 'gen-city-1.4.6-layout2';
const PREFIX = 'pageswiki:city-fabric:v2:';
const MAX_CACHE_ENTRIES = 3, MAX_CACHE_BYTES = 512 * 1024;
const workerURL = '/static/js/city-generator-worker.js?v=2';
const abortError = () => new DOMException('City generation cancelled', 'AbortError');
const validFabric = fabric => {
if (!fabric || !Number.isFinite(fabric.width) || !Number.isFinite(fabric.height) || fabric.width < 64 || fabric.width > 320 || fabric.height < 64 || fabric.height > 240) return false;
if (!Array.isArray(fabric.roads) || !Array.isArray(fabric.buildings) || fabric.roads.length > 4096 || fabric.buildings.length > 4096) return false;
const finite = value => Number.isFinite(value) && Math.abs(value) <= 2048;
return fabric.roads.every(road => Array.isArray(road) && road.length === 4 && road.every(finite)) &&
fabric.buildings.every(building => Array.isArray(building) && building.length >= 3 && building.length <= 16 && building.every(point => Array.isArray(point) && point.length === 2 && point.every(finite)));
};
class CityFabricClient {
constructor({workerFactory = url => new Worker(url), storage, timeout = 5000} = {}) {
this.workerFactory = workerFactory;
this.timeout = Math.max(20, Math.min(5000, timeout));
try { this.storage = storage === undefined ? sessionStorage : storage; } catch (_) { this.storage = null; }
this.memory = new Map(); this.pending = null; this.sequence = 0;
}
cacheKey(key, width, height) { return PREFIX + JSON.stringify([VERSION, key, width, height]); }
readCache(key) {
if (this.memory.has(key)) {
const value = this.memory.get(key); this.memory.delete(key); this.memory.set(key, value); return value;
}
try {
const raw = this.storage?.getItem(key);
if (raw && raw.length <= MAX_CACHE_BYTES) {
const value = JSON.parse(raw);
if (validFabric(value)) { this.remember(key, value); return value; }
}
if (raw) this.storage?.removeItem(key);
} catch (_) { /* Storage denial or corrupt cache must not break the map. */ }
return null;
}
remember(key, value) {
this.memory.delete(key); this.memory.set(key, value);
while (this.memory.size > MAX_CACHE_ENTRIES) this.memory.delete(this.memory.keys().next().value);
}
saveCache(key, value) {
this.remember(key, value);
try {
const raw = JSON.stringify(value);
if (raw.length > MAX_CACHE_BYTES || !this.storage) return;
// Only inspect our namespace; never clear another feature's storage.
const keys = [];
for (let i = 0; i < this.storage.length; i++) {
const item = this.storage.key(i);
if (item?.startsWith(PREFIX) && item !== key) keys.push(item);
}
while (keys.length >= MAX_CACHE_ENTRIES) this.storage.removeItem(keys.shift());
this.storage.setItem(key, raw);
} catch (_) { /* Quota exhaustion: the bounded in-memory cache still works. */ }
}
generateFabric(key, width = 180, height = 100, {signal} = {}) {
key = String(key || '');
if (!key || key.length > 256 || !Number.isInteger(width) || !Number.isInteger(height) || width < 64 || width > 320 || height < 64 || height > 240) return Promise.reject(new RangeError('City generation bounds exceeded'));
if (signal?.aborted) return Promise.reject(abortError());
const cacheKey = this.cacheKey(key, width, height);
if (this.pending?.key === cacheKey) return this.pending.promise;
this.cancel();
const cached = this.readCache(cacheKey);
if (cached && cached.width === width && cached.height === height) return Promise.resolve(cached);
let resolve, reject;
const promise = new Promise((yes, no) => { resolve = yes; reject = no; });
const job = {key: cacheKey, id: ++this.sequence, promise, resolve, reject, worker: null, timer: null, signal, abort: null};
this.pending = job;
const finish = (error, fabric) => {
if (this.pending !== job) return;
clearTimeout(job.timer); job.signal?.removeEventListener('abort', job.abort);
job.worker?.terminate(); this.pending = null;
if (error) reject(error); else { this.saveCache(cacheKey, fabric); resolve(fabric); }
};
job.abort = () => finish(abortError());
signal?.addEventListener('abort', job.abort, {once: true});
try {
job.worker = this.workerFactory(workerURL);
job.worker.onmessage = event => {
const message = event.data;
if (message?.id !== job.id) return;
if (message.error || !validFabric(message.fabric) || message.fabric.width !== width || message.fabric.height !== height) finish(new Error('Invalid City generation result'));
else finish(null, message.fabric);
};
job.worker.onerror = event => { event.preventDefault?.(); finish(new Error('City worker unavailable')); };
job.worker.onmessageerror = () => finish(new Error('Invalid City worker message'));
job.timer = setTimeout(() => finish(new Error('City generation timed out')), this.timeout);
job.worker.postMessage({id: job.id, key, width, height});
} catch (_) { finish(new Error('City worker unavailable')); }
return promise;
}
cancel() { this.pending?.abort(); }
}
window.PagesWikiCityFabricClient = CityFabricClient;
window.PagesWikiGenCity = new CityFabricClient();
})();