@fullstackunicorn/webapp 2.1.0 → 2.1.2

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/files.json CHANGED
@@ -71,13 +71,13 @@
71
71
  {
72
72
  "path": "imports/cache.js",
73
73
  "class": "byte-sacred",
74
- "sha256": "e6ca9335e558cc132fd42fe181157e4a50579b23d2a817a67a95eefc7e02eda3",
74
+ "sha256": "0ee910e9f06afa3ce43e11f9e439aa20eb20629ee571234e235f79e4e2008dbd",
75
75
  "referenceSha256": "0c89a1146701f65ea10cdf590630d7c6d43f402d13eb253a7065086cf7130071"
76
76
  },
77
77
  {
78
78
  "path": "imports/client.js",
79
79
  "class": "byte-sacred",
80
- "sha256": "3aaa21a1a159b204729e167bb9e773128310818fb4d5a38ea5de50b8052cccbe",
80
+ "sha256": "f9dfe083f494dcd721c37ced153cc96ee30b2a42510a50f9cb4ce0b87264659a",
81
81
  "referenceSha256": "a5cb8305485578f25126f7e7ad986cc66b2845066692929981a9589c8689397c"
82
82
  },
83
83
  {
@@ -395,13 +395,13 @@
395
395
  {
396
396
  "path": "load/Load.js",
397
397
  "class": "byte-sacred",
398
- "sha256": "7576e8af442008041df3316dd838cfd71771915ac8398adfb28a0e57a3bc46f0",
398
+ "sha256": "0e73a33c6c32554b94e12842051baa090612c3145492ac404abcd4a1bab041ae",
399
399
  "referenceSha256": "05347adb3df789c517f45401f44611e4ca3ec3c89bcdccfe9bc7a0da959d59d1"
400
400
  },
401
401
  {
402
402
  "path": "load/engine.js",
403
403
  "class": "byte-sacred",
404
- "sha256": "71e6e2a2fc488812bdff951e229ca020545f9be71ff85e6028a889ade217fe5b",
404
+ "sha256": "cb27149f1b2c4ef25141b3f795743cf38c9a254d1acc191049cab4a0a2cc5b9e",
405
405
  "referenceSha256": "4c2a7408cf53cb7d52e3acb2a97453bbd25fac9db036f2ba9a894a3c7e11fc3b"
406
406
  },
407
407
  {
@@ -419,13 +419,13 @@
419
419
  {
420
420
  "path": "load/resources.js",
421
421
  "class": "byte-sacred",
422
- "sha256": "934c7c68e74d8f42f4573d4caaf15d8173ad7a6e7919387bfc5d3036ce6e86a7",
422
+ "sha256": "51ce1329c894318e1502a6180d4a3a6e20a5cddee7c18a8e4aa082d542f8f054",
423
423
  "referenceSha256": "afb5f4fa8d67fa010860dff57eb74c9d6bff9a11d27f321b075ae88fec516573"
424
424
  },
425
425
  {
426
426
  "path": "load/use.js",
427
427
  "class": "byte-sacred",
428
- "sha256": "2eb2512c82544dab0be33a6196f6ea2979e3607a03336cee0edf7d9c73f287ce",
428
+ "sha256": "8bdc87bcb6a708db379a1d8238b2c214c943b42da509c6441dc9e7cb0e2b9d89",
429
429
  "referenceSha256": "d83ece7a21ade451003774c36bd87e275ee5bd873ba48de41578d1f118d90e40"
430
430
  },
431
431
  {
package/imports/cache.js CHANGED
@@ -11,10 +11,12 @@ class Cache {
11
11
  initialization = null
12
12
  generation = 0
13
13
  commits = new Map()
14
+ sources = new Map()
14
15
 
15
16
  initialize = () => {
16
17
  if (!this.initialization) this.initialization = entries().then(values => {
17
18
  for (const [key, value] of values) if (typeof key === 'string' && key.startsWith('version:') && value) this.versions.set(key.slice(8), value)
19
+ for (const [key, value] of values) if (typeof key === 'string' && key.startsWith('source:') && value) this.sources.set(key.slice(7), value)
18
20
  this.initialized = true
19
21
  }).catch(error => { this.initialization = null; throw error })
20
22
  return this.initialization
@@ -22,6 +24,36 @@ class Cache {
22
24
 
23
25
  version = key => this.initialized ? this.versions.get(key) : undefined
24
26
 
27
+ source = origin => this.sources.get(origin)?.revision
28
+
29
+ release = origin => this.sources.get(origin)?.cursor
30
+
31
+ observe = async (origin, revision, cursor) => {
32
+ await this.initialize()
33
+ if (this.source(origin) === revision && this.release(origin) === cursor) return false
34
+ const state = { revision, cursor }
35
+ await set('source:' + origin, state)
36
+ this.sources.set(origin, state)
37
+ return true
38
+ }
39
+
40
+ current = (record, origin) => {
41
+ const revision = this.source(origin)
42
+ if (record?.source !== origin || !/^[a-f0-9]{64}$/.test(record.hash || '') || !/^[a-f0-9]{64}$/.test(record.revision || '')) return false
43
+ return !revision || record.revision === revision
44
+ }
45
+
46
+ record = async (store, key, isBlob = false) => {
47
+ const response = await store.match(key)
48
+ if (!response) return null
49
+ return {
50
+ data: isBlob ? await response.blob() : await response.json(),
51
+ hash: response.headers.get('X-Cache-Hash'),
52
+ source: response.headers.get('X-Cache-Source'),
53
+ revision: response.headers.get('X-Cache-Revision'),
54
+ }
55
+ }
56
+
25
57
  commit = (key, work) => {
26
58
  const previous = this.commits.get(key) || Promise.resolve()
27
59
  const current = previous.catch(() => {}).then(work)
@@ -56,8 +88,19 @@ class Cache {
56
88
 
57
89
  set = async (cache, key, value, isBlob, metadata = {}) => {
58
90
 
59
- const headers = { headers: {'Content-Type': value?.type || 'application/octet-stream', 'X-Cache-Version': metadata.version || ''}}
60
- const headersJson = { headers: { 'Content-Type': 'application/json', 'X-Cache-Hash': metadata.hash || '' } }
91
+ const headers = { headers: {
92
+ 'Content-Type': value?.type || 'application/octet-stream',
93
+ 'X-Cache-Version': metadata.version || '',
94
+ 'X-Cache-Hash': metadata.hash || '',
95
+ 'X-Cache-Source': metadata.source || '',
96
+ 'X-Cache-Revision': metadata.revision || '',
97
+ } }
98
+ const headersJson = { headers: {
99
+ 'Content-Type': 'application/json',
100
+ 'X-Cache-Hash': metadata.hash || '',
101
+ 'X-Cache-Source': metadata.source || '',
102
+ 'X-Cache-Revision': metadata.revision || '',
103
+ } }
61
104
 
62
105
  const response = isBlob
63
106
  ? new Response(value, headers)
package/imports/client.js CHANGED
@@ -4,6 +4,7 @@ import { abs } from '#@/abstracts/abs.js'
4
4
  import { err } from '#@/abstracts/err.js'
5
5
  import { cache } from '#imports/cache.js'
6
6
  import { requestFailure } from '#imports/request.js'
7
+ import { requests } from '#load/requests.js'
7
8
 
8
9
  class Client {
9
10
 
@@ -14,6 +15,29 @@ class Client {
14
15
  this.cacheStale = constants.cache.stale
15
16
  }
16
17
 
18
+ source = (endpoint, isFile = false) => {
19
+ if (typeof endpoint !== 'string') return null
20
+ const origins = Object.entries(constants.env || {}).filter(([name, value]) => /^CDN\d+$/.test(name) && typeof value === 'string' && /^https?:\/\//.test(value))
21
+ .map(([name, value]) => ({ id: name === 'CDN0' ? 'site' : name, origin: value.replace(/\/+$/, '') }))
22
+ .sort((a, b) => b.origin.length - a.origin.length)
23
+ for (const source of origins) {
24
+ if (!endpoint.startsWith(source.origin + '/')) continue
25
+ const path = endpoint.slice(source.origin.length + 1).split('#')[0]
26
+ if ((/^(data|page|site|lookup|menu)\//.test(path) || isFile && /^(media|icons|fonts)\//.test(path))
27
+ && !path.includes('..') && !path.includes('?')) return { ...source, path }
28
+ }
29
+ return null
30
+ }
31
+
32
+ etagHash = value => /^(?:W\/)?"([a-f0-9]{64})"$/.exec(String(value || ''))?.[1]
33
+
34
+ identity = (headers, source) => {
35
+ const hash = this.etagHash(headers['etag'])
36
+ const revision = headers['x-data-revision']
37
+ if (!/^[a-f0-9]{64}$/.test(hash) || !/^[a-f0-9]{64}$/.test(revision || '')) throw new Error('Invalid public JSON identity')
38
+ return { hash, source: source.origin, revision }
39
+ }
40
+
17
41
  validate = ({ response = {}, is = {} }) => {
18
42
  if (!F3.obj.isGood(response)) return { isError: true, error: 'no-response' }
19
43
  if (F3.err.is400(response.status)) return { isError: true, error: 'client-error' }
@@ -52,6 +76,8 @@ class Client {
52
76
  const params = isGet ? undefined : payload.data
53
77
  payload.key = abs.makeKey(payload.endpoint, payload.method, params)
54
78
  if (isNoCache) return await this.directFile(payload, isGet)
79
+ if (isGet && this.source(payload.endpoint, true)) return await requests.get('file:' + payload.key,
80
+ signal => this.cacheFile({ ...payload, config: { ...payload.config, signal } }, isGet), { signal: payload.config?.signal })
55
81
  return await this.cacheFile(payload, isGet)
56
82
  }
57
83
 
@@ -101,48 +127,92 @@ class Client {
101
127
  cacheData = async ({ key, method, endpoint, data = {}, config = {}, revalidate = false, cacheOnly = false, isVersion = false }, isGet) => {
102
128
 
103
129
  const cacheStore = await cache.open(this.cacheNameObjects)
104
- const cachedItem = await cache.get(cacheStore, key, false)
130
+ const source = isGet && !isVersion ? this.source(endpoint) : null
131
+ if (source) await cache.initialize()
132
+ let cachedRecord
133
+ try { cachedRecord = source ? await cache.record(cacheStore, key) : null }
134
+ catch (error) {
135
+ if (!(error instanceof SyntaxError)) throw error
136
+ await cache.remove(cacheStore, key)
137
+ }
138
+ const cachedItem = source ? cachedRecord?.data : await cache.get(cacheStore, key, false)
105
139
  const cachedResponse = cachedItem ? { key, data: cachedItem } : undefined
106
140
  const { etag, timestamp } = await cache.getMeta(key)
141
+ const pulse = source ? cache.source(source.origin) : undefined
142
+ const cursor = source ? cache.release(source.origin) : undefined
143
+ const url = cursor ? endpoint + '?release=' + encodeURIComponent(cursor) : endpoint
144
+ const retry = () => this.cacheData({ key, method, endpoint, data, config: { ...config, headers: { ...config.headers, 'If-None-Match': undefined } }, revalidate, cacheOnly, isVersion }, isGet)
107
145
 
108
146
  const age = (Date.now() - timestamp) / 1000
109
- if (cachedItem && !revalidate && (cacheOnly || age < this.cacheStale)) return cachedResponse
147
+ if (cachedItem && (source ? cache.current(cachedRecord, source.origin) : !revalidate && (cacheOnly || age < this.cacheStale))) return cachedResponse
110
148
 
111
149
  config.timeout = 10000
112
- if (etag && cachedItem) {
150
+ if (etag && cachedItem && (!source || cachedRecord?.hash === this.etagHash(etag))) {
113
151
  if (!config.headers) config.headers = {}
114
- config.headers['If-None-Match'] = etag
152
+ config.headers['If-None-Match'] = source ? '"' + cachedRecord.hash + '"' : etag
115
153
  config.validateStatus = status => (status >= 200 && status < 300) || status === 304
116
154
  }
117
155
 
118
156
  try {
119
157
 
120
158
  const response = isGet
121
- ? await axios.get(endpoint, config)
159
+ ? await axios.get(url, config)
122
160
  : await axios[method](endpoint, data, config)
123
161
 
124
162
  if (config.signal?.aborted) throw new DOMException('Aborted', 'AbortError')
163
+ const identity = source ? this.identity(response.headers, source) : undefined
125
164
  if (cachedItem && response.status === 304) {
126
- await cache.setMeta(key, response.headers['etag'] || etag)
127
- return cachedResponse
165
+ let data = cachedItem
166
+ let superseded = false
167
+ await cache.commit(key, async () => {
168
+ if (config.signal?.aborted) throw new DOMException('Aborted', 'AbortError')
169
+ const record = source ? await cache.record(cacheStore, key) : null
170
+ const current = source ? record?.data : await cache.get(cacheStore, key, false)
171
+ if (source && pulse !== cache.source(source.origin) && identity.revision !== cache.source(source.origin)) {
172
+ if (current && cache.current(record, source.origin)) data = current
173
+ else superseded = true
174
+ return
175
+ }
176
+ if (pulse && identity.revision !== pulse) throw new Error('Public JSON revision does not match Pulse')
177
+ if (current) data = current
178
+ else await cache.set(cacheStore, key, cachedItem, false, identity)
179
+ if (!current || JSON.stringify(current) === JSON.stringify(cachedItem)) {
180
+ if (source) await cache.set(cacheStore, key, data, false, identity)
181
+ await cache.setMeta(key, response.headers['etag'] || etag, data?.version)
182
+ }
183
+ })
184
+ if (superseded) return await retry()
185
+ return { key, data }
128
186
  }
129
187
 
130
188
  const validated = this.validate({ response, key })
131
189
  if (!validated.isValid) return validated
132
190
 
191
+ let data = response.data
192
+ let superseded = false
133
193
  await cache.commit(key, async () => {
134
194
  if (config.signal?.aborted) throw new DOMException('Aborted', 'AbortError')
135
- const saved = cache.version(key)
136
- const version = /^[a-f0-9]{64}$/.test(saved || '') ? (await cache.get(cacheStore, key, false))?.version : saved
137
- if (!isVersion && version && response.data.version && version > response.data.version) throw new Error('Superseded JSON version')
138
- await cache.set(cacheStore, key, response.data, false)
139
- await cache.setMeta(key, response.headers['etag'], response.data?.version)
195
+ const record = source ? await cache.record(cacheStore, key) : null
196
+ const current = source ? record?.data : await cache.get(cacheStore, key, false)
197
+ if (source && pulse !== cache.source(source.origin) && identity.revision !== cache.source(source.origin)) {
198
+ if (current && cache.current(record, source.origin)) data = current
199
+ else superseded = true
200
+ return
201
+ }
202
+ if (pulse && identity.revision !== pulse) throw new Error('Public JSON revision does not match Pulse')
203
+ if (!isVersion && (!source || cache.current(record, source.origin)) && current?.version && data.version && current.version > data.version) {
204
+ data = current
205
+ return
206
+ }
207
+ await cache.set(cacheStore, key, data, false, identity)
208
+ await cache.setMeta(key, response.headers['etag'], data?.version)
140
209
  })
141
210
 
142
- return { key, data: response.data }
211
+ if (superseded) return await retry()
212
+ return { key, data }
143
213
 
144
214
  } catch (error) {
145
- if (revalidate || config.signal?.aborted) throw error
215
+ if (source || revalidate || config.signal?.aborted) throw error
146
216
  return await err.cache(error, cachedResponse)
147
217
  }
148
218
  }
@@ -197,30 +267,75 @@ class Client {
197
267
  return { key, blob, version, isUpdated: true }
198
268
  }
199
269
 
270
+ fileHash = async blob => [...new Uint8Array(await crypto.subtle.digest('SHA-256', await blob.arrayBuffer()))]
271
+ .map(value => value.toString(16).padStart(2, '0')).join('')
272
+
273
+ fileRecord = async (store, key) => {
274
+ const record = await cache.record(store, key, true)
275
+ if (!record) return null
276
+ if (!record.data.size || /^[a-f0-9]{64}$/.test(record.hash || '') && await this.fileHash(record.data) !== record.hash) {
277
+ await cache.remove(store, key)
278
+ return null
279
+ }
280
+ return record
281
+ }
282
+
200
283
  cacheFile = async ({ key, method, endpoint, data = {}, config = {} }, isGet) => {
201
284
 
202
285
  const cacheStore = await cache.open(this.cacheNameFiles)
203
- const cachedBlob = await cache.get(cacheStore, key, true)
286
+ const source = isGet ? this.source(endpoint, true) : null
287
+ if (source) await cache.initialize()
288
+ const cachedRecord = source ? await this.fileRecord(cacheStore, key) : null
289
+ const cachedBlob = source ? cachedRecord?.data : await cache.get(cacheStore, key, true)
204
290
  const cachedResponse = cachedBlob?.size ? { key, blob: cachedBlob } : undefined
205
291
  const { etag, timestamp } = await cache.getMeta(key)
292
+ const pulse = source ? cache.source(source.origin) : undefined
293
+ const cursor = source ? cache.release(source.origin) : undefined
294
+ const url = cursor ? endpoint + '?release=' + encodeURIComponent(cursor) : endpoint
295
+ const retry = () => this.cacheFile({ key, method, endpoint, data,
296
+ config: { ...config, headers: { ...config.headers, 'If-None-Match': undefined } } }, isGet)
206
297
 
207
298
  const age = (Date.now() - timestamp) / 1000
208
- const isFresh = cachedResponse && age < this.cacheStale
299
+ const isFresh = cachedResponse && (source ? cache.current(cachedRecord, source.origin) : age < this.cacheStale)
209
300
  if (isFresh) return cachedResponse
210
301
 
211
302
  config.responseType = 'arraybuffer'
212
303
  config.timeout = 10000
213
304
 
214
- if (etag && cachedResponse) {
305
+ if (etag && cachedResponse && (!source || cachedRecord?.hash === this.etagHash(etag))) {
215
306
  if (!config.headers) config.headers = {}
216
- config.headers['If-None-Match'] = etag
307
+ config.headers['If-None-Match'] = source ? '"' + cachedRecord.hash + '"' : etag
217
308
  }
218
309
 
219
310
  try {
220
311
  const response = isGet
221
- ? await axios.get(endpoint, config)
312
+ ? await axios.get(url, config)
222
313
  : await axios[method](endpoint, data, config)
223
314
 
315
+ if (source) {
316
+ if (config.signal?.aborted) throw new DOMException('Aborted', 'AbortError')
317
+ const identity = this.identity(response.headers, source)
318
+ const confirmed = response.status === 304 && cachedResponse
319
+ let blob = confirmed ? cachedBlob : cache.getBlob(response.data, response.headers['content-type'])
320
+ if (!blob.size || await this.fileHash(blob) !== identity.hash) throw new Error('File bytes do not match publication: ' + endpoint)
321
+ let superseded = false
322
+ await cache.commit(key, async () => {
323
+ if (config.signal?.aborted) throw new DOMException('Aborted', 'AbortError')
324
+ const current = await this.fileRecord(cacheStore, key)
325
+ if (pulse !== cache.source(source.origin) && identity.revision !== cache.source(source.origin)) {
326
+ if (cache.current(current, source.origin)) blob = current.data
327
+ else superseded = true
328
+ return
329
+ }
330
+ if (pulse && identity.revision !== pulse) throw new Error('Public file revision does not match Pulse')
331
+ if (cache.current(current, source.origin)) { blob = current.data; return }
332
+ await cache.set(cacheStore, key, blob, true, identity)
333
+ await cache.setMeta(key, response.headers['etag'] || etag)
334
+ })
335
+ if (superseded) return await retry()
336
+ return { key, blob }
337
+ }
338
+
224
339
  if (cachedResponse && response.status === 304) {
225
340
  await cache.setMeta(key, response.headers['etag'] || etag)
226
341
  return cachedResponse
@@ -232,7 +347,10 @@ class Client {
232
347
 
233
348
  return { key, blob }
234
349
 
235
- } catch (error) { return await err.cache(error, cachedResponse) }
350
+ } catch (error) {
351
+ if (source) throw error
352
+ return await err.cache(error, cachedResponse)
353
+ }
236
354
  }
237
355
 
238
356
  cacheRemove = async ({ method, endpoint, cacheName }) => {
@@ -241,16 +359,55 @@ class Client {
241
359
  await cache.remove(cacheStore, key)
242
360
  }
243
361
 
244
- cacheDataSet = async ({ endpoint, value, version }) => {
362
+ cacheDataSet = async ({ endpoint, value, version, sourceRevision }) => {
245
363
  const key = abs.makeKey(endpoint, 'get')
246
364
  const cacheStore = await cache.open(this.cacheNameObjects)
365
+ const source = this.source(endpoint)
366
+ await cache.initialize()
247
367
  await cache.commit(key, async () => {
248
- await cache.set(cacheStore, key, value, false, { hash: version })
249
- await cache.setMeta(key, undefined, value?.version || null)
368
+ const record = source ? await cache.record(cacheStore, key) : null
369
+ const current = source ? record?.data : await cache.get(cacheStore, key, false)
370
+ if (source && cache.source(source.origin) && sourceRevision !== cache.source(source.origin)) throw new DOMException('Superseded Data revision', 'AbortError')
371
+ if ((!source || cache.current(record, source.origin)) && current?.version && value?.version && current.version > value.version) throw new Error('Superseded JSON version')
372
+ await cache.set(cacheStore, key, value, false, { hash: version, source: source?.origin, revision: sourceRevision })
373
+ await cache.setMeta(key, /^[a-f0-9]{64}$/.test(version || '') ? '"' + version + '"' : undefined, value?.version || null)
250
374
  })
251
375
  return key
252
376
  }
253
377
 
378
+ cacheDataConfirm = async ({ endpoint, version, sourceRevision }) => {
379
+ const key = abs.makeKey(endpoint, 'get')
380
+ const store = await cache.open(this.cacheNameObjects)
381
+ const source = this.source(endpoint)
382
+ return await cache.commit(key, async () => {
383
+ const record = await cache.record(store, key)
384
+ if (!record || record.hash !== version) return false
385
+ if (source && cache.source(source.origin) && sourceRevision !== cache.source(source.origin)) throw new DOMException('Superseded Data revision', 'AbortError')
386
+ if (record.source === source?.origin && record.revision === sourceRevision) return true
387
+ await cache.set(store, key, record.data, false, { hash: version, source: source?.origin, revision: sourceRevision })
388
+ return true
389
+ })
390
+ }
391
+
392
+ cacheDataEntries = async () => {
393
+ const store = await cache.open(this.cacheNameObjects)
394
+ const result = []
395
+ for (const request of await store.keys()) {
396
+ const endpoint = request.url.split('#')[0]
397
+ const source = this.source(endpoint)
398
+ if (!source) continue
399
+ const key = abs.makeKey(endpoint, 'get')
400
+ try {
401
+ const record = await cache.record(store, key)
402
+ if (record && /^[a-f0-9]{64}$/.test(record.hash || '')) result.push({ endpoint, path: source.path, source: source.id, sha256: record.hash })
403
+ } catch (error) {
404
+ if (!(error instanceof SyntaxError)) throw error
405
+ await cache.remove(store, key)
406
+ }
407
+ }
408
+ return result
409
+ }
410
+
254
411
  cacheDataHas = async ({ endpoint, version }) => {
255
412
  await cache.initialize()
256
413
  const key = abs.makeKey(endpoint, 'get')
package/load/Load.js CHANGED
@@ -6,28 +6,22 @@ import { useWindowDimensions } from '#imports/use.js'
6
6
  import { visibility } from '#imports/visibility.js'
7
7
  import { useUrl } from '#@/base/router/@use.js'
8
8
  import { engine } from '#load/engine.js'
9
- import { useRefreshContent } from '#load/use.js'
9
+ import { usePulse, useSetPulse, useRefreshContent } from '#load/use.js'
10
10
  import { loadGeometry } from '#load/Geometry.js'
11
11
 
12
12
  const ready = () => {}
13
13
 
14
- export const Load = ({ onReady = ready }) => {
14
+ export const Pulse = () => {
15
15
 
16
16
  const { lang } = useUrl()
17
17
  const refresh = useRefreshContent()
18
18
  const refreshRef = useRef(refresh)
19
- const onReadyRef = useRef(onReady)
20
- const dimensions = useWindowDimensions()
21
- const geometry = loadGeometry.signature(dimensions.width, img.pixelRatio())
22
- const dimensionsRef = useRef(dimensions)
19
+ const setPulse = useSetPulse()
23
20
  refreshRef.current = refresh
24
- onReadyRef.current = onReady
25
- dimensionsRef.current = dimensions
26
21
 
27
22
  useEffect(() => {
28
23
  let active = true
29
- const controller = new AbortController()
30
- let timer, running = false, prepared = false
24
+ let timer, running = false, refreshed, sequence = 0
31
25
  const schedule = () => {
32
26
  clearTimeout(timer)
33
27
  if (active && visibility.isVisible()) timer = setTimeout(check, engine.interval)
@@ -36,21 +30,20 @@ export const Load = ({ onReady = ready }) => {
36
30
  if (running || !visibility.isVisible()) return schedule()
37
31
  running = true
38
32
  try {
39
- await priority.ready()
33
+ const current = await engine.pulse(lang, true)
40
34
  if (!active) return
41
- await engine.run(lang, dimensionsRef.current.width, controller.signal, async refreshNeeded => {
42
- if (!active) return
43
- if (refreshNeeded) await refreshRef.current(lang)
44
- if (!prepared && active) {
45
- prepared = true
46
- onReadyRef.current(true)
35
+ const signature = engine.signature(current)
36
+ const done = priority.begin()
37
+ try {
38
+ setPulse({ lang, current, sequence: ++sequence })
39
+ if (refreshed !== signature) {
40
+ await refreshRef.current(lang)
41
+ refreshed = signature
47
42
  }
48
- })
49
- if (!prepared && active) {
50
- prepared = true
51
- onReadyRef.current(true)
43
+ } finally {
44
+ done()
52
45
  }
53
- } catch (error) { if (error.name !== 'AbortError') console.error('load-failed', error) }
46
+ } catch (error) { if (error.name !== 'AbortError') console.error('pulse-failed', error) }
54
47
  finally {
55
48
  running = false
56
49
  schedule()
@@ -65,12 +58,51 @@ export const Load = ({ onReady = ready }) => {
65
58
  check()
66
59
  return () => {
67
60
  active = false
68
- controller.abort()
69
- requests.pause()
70
61
  clearTimeout(timer)
71
62
  stop()
72
63
  }
73
- }, [lang, geometry])
64
+ }, [lang, setPulse])
65
+
66
+ return null
67
+ }
68
+
69
+ export const Load = ({ onReady = ready }) => {
70
+
71
+ const { lang } = useUrl()
72
+ const pulse = usePulse()
73
+ const onReadyRef = useRef(onReady)
74
+ const prepared = useRef(false)
75
+ const dimensions = useWindowDimensions()
76
+ const geometry = loadGeometry.signature(dimensions.width, img.pixelRatio())
77
+ const dimensionsRef = useRef(dimensions)
78
+ onReadyRef.current = onReady
79
+ dimensionsRef.current = dimensions
80
+
81
+ useEffect(() => {
82
+ if (pulse?.lang !== lang) return
83
+ let active = true
84
+ const controller = new AbortController()
85
+ const notify = () => {
86
+ if (!prepared.current && active) {
87
+ prepared.current = true
88
+ onReadyRef.current(true)
89
+ }
90
+ }
91
+ const check = async () => {
92
+ try {
93
+ await priority.ready(controller.signal)
94
+ if (!active) return
95
+ await engine.run(lang, dimensionsRef.current.width, controller.signal, notify, pulse.current)
96
+ notify()
97
+ } catch (error) { if (error.name !== 'AbortError') console.error('load-failed', error) }
98
+ }
99
+ check()
100
+ return () => {
101
+ active = false
102
+ controller.abort()
103
+ requests.pause()
104
+ }
105
+ }, [lang, geometry, pulse])
74
106
 
75
107
  return null
76
108
  }
package/load/engine.js CHANGED
@@ -7,6 +7,7 @@ import { resources } from '#load/resources.js'
7
7
  import { uri } from '#@/App.uri.js'
8
8
  import settings from '#@/configure/load.json'
9
9
  import { loadGeometry } from '#load/Geometry.js'
10
+ import { constants } from '#@/root/constants.js'
10
11
 
11
12
  class Engine {
12
13
 
@@ -17,9 +18,9 @@ class Engine {
17
18
  key = lang => 'load:' + lang
18
19
 
19
20
  signature = state => JSON.stringify({
20
- site: state?.site ? { version: state.site.version, fingerprint: state.site.fingerprint } : null,
21
+ site: state?.site ? { revision: state.site.revision, version: state.site.version, fingerprint: state.site.fingerprint } : null,
21
22
  sources: Object.fromEntries(Object.entries(state?.sources || {}).sort(([a], [b]) => a.localeCompare(b))
22
- .map(([name, value]) => [name, { version: value.version, fingerprint: value.fingerprint }])),
23
+ .map(([name, value]) => [name, { revision: value.revision, version: value.version, fingerprint: value.fingerprint }])),
23
24
  })
24
25
 
25
26
  pulse = (lang, force = false) => {
@@ -27,9 +28,14 @@ class Engine {
27
28
  if (previous && (previous.pending || (!force && Date.now() - previous.time < this.interval))) return previous.promise
28
29
  const entry = { pending: true, time: Date.now() }
29
30
  const endpoint = uri.pulse + '?locale=' + encodeURIComponent(lang)
30
- entry.promise = json.read(endpoint, true, { isVersion: true }).then(response => {
31
+ entry.promise = json.read(endpoint, true, { isVersion: true }).then(async response => {
31
32
  if (!response?.data?.current?.site) throw new Error('Invalid Data pulse')
32
- return response.data.current
33
+ const current = response.data.current
34
+ for (const [source, state] of Object.entries({ CDN0: current.site, ...current.sources })) {
35
+ const origin = constants.env[source]?.replace(/\/$/, '')
36
+ if (origin && /^[a-f0-9]{64}$/.test(state.revision || '')) await cache.observe(origin, state.revision, state.cursor)
37
+ }
38
+ return current
33
39
  }).catch(error => { this.pulses.delete(lang); throw error })
34
40
  .finally(() => { entry.pending = false })
35
41
  this.pulses.set(lang, entry)
@@ -44,20 +50,20 @@ class Engine {
44
50
  return !resourcesReady || this.signature(previous.state) !== this.signature(current)
45
51
  }
46
52
 
47
- run = async (lang, width, signal, onResources) => {
53
+ run = async (lang, width, signal, onResources, current) => {
48
54
  const previous = this.jobs.get(lang)
49
55
  if (previous) await previous.catch(error => { if (error.name !== 'AbortError') throw error })
50
56
  if (signal?.aborted) throw new DOMException('Aborted', 'AbortError')
51
- const job = this.check(lang, width, signal, onResources).finally(() => { if (this.jobs.get(lang) === job) this.jobs.delete(lang) })
57
+ const job = this.check(lang, width, signal, onResources, current).finally(() => { if (this.jobs.get(lang) === job) this.jobs.delete(lang) })
52
58
  this.jobs.set(lang, job)
53
59
  return job
54
60
  }
55
61
 
56
- check = async (lang, width, signal, onResources) => {
62
+ check = async (lang, width, signal, onResources, observed) => {
57
63
  await cache.initialize()
58
64
  const key = this.key(lang)
59
65
  const before = await get(key) || { state: null, complete: false, items: {}, geometry: null }
60
- const current = await this.pulse(lang, true)
66
+ const current = observed || await this.pulse(lang)
61
67
  const geometry = loadGeometry.signature(width, img.pixelRatio())
62
68
  const signature = this.signature(current)
63
69
  const completion = key + ':' + signature + ':' + geometry + ':' + cache.generation
@@ -72,11 +78,12 @@ class Engine {
72
78
  let refresh = false
73
79
 
74
80
  if (changed) {
81
+ nextItems = { ...nextItems, ...await resources.inventory() }
75
82
  const inventory = Object.fromEntries(Object.entries(nextItems).map(([itemKey, item]) => [itemKey, item.sha256]))
76
83
  const response = await client.post(uri.data.update, {
77
84
  locale: lang,
78
85
  from: before.state,
79
- cache: { complete: before.complete === true && inventoryComplete, items: inventory },
86
+ cache: { complete: before.complete === true && inventoryComplete && this.signature(before.state) !== signature, items: inventory },
80
87
  }, { headers: { 'Content-Type': 'application/json' }, signal })
81
88
  const preload = response?.preload
82
89
  if (!response?.current?.site || !preload || !Array.isArray(preload.delete)
@@ -88,7 +95,7 @@ class Engine {
88
95
  nextItems = await resources.apply(preload, width, nextItems, signal, async resourceItems => {
89
96
  await set(key, { state: response.current, complete: false, resources: true, items: resourceItems, geometry })
90
97
  await onResources?.(refresh)
91
- })
98
+ }, { current: response.current })
92
99
  await set(key, { state: response.current, complete: true, resources: true, items: nextItems, geometry })
93
100
  } else if (geometryChanged) {
94
101
  await onResources?.(false)
package/load/resources.js CHANGED
@@ -49,6 +49,12 @@ class Resources {
49
49
  return verified
50
50
  }
51
51
 
52
+ inventory = async () => Object.fromEntries((await client.cacheDataEntries())
53
+ .filter(item => resource.url(item.path) === item.endpoint)
54
+ .map(item => ['resource:' + item.path, { key: 'resource:' + item.path, kind: 'resource', path: item.path, source: item.source, sha256: item.sha256 }]))
55
+
56
+ revision = (state, source) => source && source !== 'site' ? state?.sources?.[source]?.revision : state?.site?.revision
57
+
52
58
  image = async (item, width, current, signal) => {
53
59
  const selected = img.getImage(item.picture, loadGeometry.width(item, width), current?.size)
54
60
  if (current?.url === selected.src && current?.hash === selected.hash) {
@@ -63,10 +69,9 @@ class Resources {
63
69
  return { ...item, size: selected.size, url: selected.src, version: selected.version, hash: selected.hash }
64
70
  }
65
71
 
66
- apply = async (preload, width, current = {}, signal, onResources) => {
72
+ apply = async (preload, width, current = {}, signal, onResources, context = {}) => {
67
73
  const next = { ...current }
68
74
  for (const key of preload.delete || []) {
69
- await this.remove(next[key])
70
75
  delete next[key]
71
76
  }
72
77
 
@@ -74,8 +79,15 @@ class Resources {
74
79
  const resources = changed.filter(item => item.kind === 'resource')
75
80
  await this.queue(resources, settings.concurrency, async item => {
76
81
  if (!/^(data|page|site|lookup|menu)\//.test(item.path || '') || item.path.includes('..')) throw new Error('Invalid load resource: ' + item.path)
77
- await client.cacheDataSet({ endpoint: resource.url(item.path), value: item.value, version: item.sha256 })
78
- next[item.key] = item
82
+ await client.cacheDataSet({ endpoint: resource.url(item.path), value: item.value, version: item.sha256,
83
+ sourceRevision: this.revision(context.current, item.source) })
84
+ const { value, ...descriptor } = item
85
+ next[item.key] = descriptor
86
+ })
87
+ await this.queue(Object.values(next).filter(item => item.kind === 'resource'), settings.concurrency, async item => {
88
+ const confirmed = await client.cacheDataConfirm({ endpoint: resource.url(item.path), version: item.sha256,
89
+ sourceRevision: this.revision(context.current, item.source) })
90
+ if (!confirmed) throw new DOMException('Load inventory changed', 'AbortError')
79
91
  })
80
92
  await onResources?.(next)
81
93
 
package/load/use.js CHANGED
@@ -5,15 +5,18 @@ import { useSetLookups } from '#@/base/lookups/@use.js'
5
5
 
6
6
  const revision = atom(0)
7
7
  export const useContentRevision = () => useGetAtom(revision)
8
+ const pulse = atom(null)
9
+ export const usePulse = () => useGetAtom(pulse)
10
+ export const useSetPulse = () => useSetAtom(pulse)
8
11
 
9
12
  export const useRefreshContent = () => {
10
13
  const setRevision = useSetAtom(revision)
11
14
  const setStatics = useSetStatics()
12
15
  const setLookups = useSetLookups()
13
16
  return useCallback(async lang => {
17
+ setRevision(value => value + 1)
14
18
  const data = await tools.loadData(lang)
15
19
  setStatics(data.statics)
16
20
  setLookups(data.lookups)
17
- setRevision(value => value + 1)
18
21
  }, [setLookups, setRevision, setStatics])
19
22
  }
package/package.json CHANGED
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.1.0",
2
+ "version": "2.1.2",
3
3
  "name": "@fullstackunicorn/webapp",
4
4
  "author": "lucanigido (https://fullstackunicorn.dev/author/lucanigido)",
5
5
  "description": "Shared Web and Native runtime engines and core components for Fullstack Unicorn applications",
package/package.md CHANGED
@@ -7,26 +7,37 @@ Shared Web and Native runtime engines and React core components used by Fullstac
7
7
  Applications import this package only through their canonical dependency barrel. Package-internal third-party imports are centralized in `index.dep.js`. Host-specific configuration, data, pages, routes and styles remain in the application.
8
8
 
9
9
  The load engine lives in `load/` and its component entry point is `load/Load.js`.
10
- It reads host settings from `configure/load.json`, checks `/pulse`, reports a
11
- complete or partial cache inventory to `POST /api/data/load/get`, applies only
12
- `delete`, `replace` and `new` operations from the one BFF response, and resolves
13
- initial image sizes through the host's `load/geometry.scope.js`. Before reporting
14
- an inventory as complete, it verifies that every declared JSON resource and image
15
- binary is actually present at the declared version in browser cache. Hosts may use
16
- the `Load` component's `onReady` callback to initialize page content only after
17
- the required JSON resources have been reconciled. Image warming continues in
18
- parallel and shares the same requests and cache with mounted `Img` components.
19
- The resource-ready state is committed before content initialization, while the
20
- complete state is committed only after image warming finishes.
21
- Parent renders keep the active Load job alive, and a cancelled request propagates
22
- as `AbortError` instead of being validated as a Data bundle.
23
- Later Data updates refresh mounted content after the initial `onReady` notification.
24
- Load resource hashes are stored separately from chronological JSON versions;
25
- existing caches that stored a hash as the version remain readable and recover on
26
- normal revalidation without clearing other cached resources or images.
27
- Every subsequent check verifies the physical cache before reusing a completed
28
- state. Missing records are reconciled through the existing partial inventory;
29
- unchanged valid records require no additional bundle request.
10
+ `Pulse` owns the single visibility-aware scheduler and observes every active Data
11
+ source independently of optional prefetch. `Load` reads host settings from
12
+ `configure/load.json`; `enabled: false` leaves only that prefetch component
13
+ unmounted. Normal content never waits for Pulse, a bundle or `onReady`.
14
+
15
+ Public CDN JSON from normal GETs and bundled values shares the same physical
16
+ cache entry, keyed by the canonical endpoint and method. Each entry retains the
17
+ origin SHA, source URL and Data revision. A qualified entry has no TTL: repeated
18
+ reads perform no HTTP until Pulse observes a different source revision or the
19
+ physical entry is missing. Legacy entries without that identity validate once
20
+ through the normal reader, without clearing unrelated cache. Conditional 304
21
+ responses and HTTP 200 writes share the existing serialized per-key commit.
22
+ The observed source state stores revision and publication cursor. Reads use the
23
+ existing `?release=<cursor>` transport when available, preserving the canonical
24
+ cache key, and reject contradictory response revisions. A Code-only cursor
25
+ change does not invalidate content at the same Data revision. A cold request
26
+ already in flight is shared when the first Pulse confirms its response.
27
+
28
+ Load projects its inventory from the same physical JSON cache plus its selected
29
+ image descriptors and sends that exact snapshot to `POST /api/data/load/get`.
30
+ The single response carries only `delete`, `replace` and `new` operations.
31
+ `delete` removes selection membership, preserving ordinary cached resources.
32
+ Already-cached raw JSON is advertised by the same origin SHA, so it is not sent
33
+ again in the bundle. Host readers qualify media from that resource's CDN and
34
+ explicit source mappings; bundled JSON remains identical to ordinary GET data.
35
+ The resources-ready state records JSON completion; complete state also includes
36
+ image warming. Neither state gates page content. Every subsequent check verifies
37
+ physical presence before reusing a completed state. Geometry comes from the
38
+ host's `load/geometry.scope.js`, and warming shares the transport/cache used by
39
+ mounted images. Parent renders retain the current Load job; cancellation remains
40
+ an `AbortError` rather than an invalid bundle.
30
41
  The shared
31
42
  `Img` component measures its mounted container, treats `src + hash` as binary
32
43
  identity and keeps the decoded displayed image visible until a changed pending
@@ -60,3 +71,27 @@ The existing wildcard exports expose these modules without a new export surface.
60
71
  Only those four feature files were transferred from the older 2.0.0-based
61
72
  candidate; subsequent shared runtime corrections were retained. Metadata and
62
73
  the choice of title source remain unchanged, pending Luca's decision.
74
+
75
+ Version 2.1.1 implements Luca's explicit single-registry, Pulse-only invalidation
76
+ contract. The six reviewed runtime deltas are `imports/cache.js`,
77
+ `imports/client.js`, `load/Load.js`, `load/engine.js`, `load/resources.js` and
78
+ `load/use.js`. The existing request ownership module is unchanged. Tests cover
79
+ legacy migration, no-TTL hits, source isolation, cold-request sharing, release
80
+ pinning, Code-only reuse, optional prefetch, raw inventory deduplication,
81
+ deselection without eviction, and physical-cache recovery. A bundle of another
82
+ observed revision cannot replace current data. Within the same observed revision,
83
+ an older completion cannot replace newer committed JSON, including conditional
84
+ 304 responses; an explicitly Pulse-selected rollback remains valid.
85
+
86
+ Version 2.1.2 applies the same observed-source identity to versionable public
87
+ files requested through `client.file`, including font CSS from the declared
88
+ CDNs. These Blob responses reuse `cache-files`, source/revision/hash metadata,
89
+ the existing `Requests` ownership and per-key commits. They have no TTL; Pulse
90
+ changes source validity, and the existing release cursor pins validation. Blob
91
+ bytes are checked against the origin SHA, including after physical corruption
92
+ or eviction. Concurrent file readers share one transport; late 200/304 responses
93
+ cannot replace current data. The previous external-file TTL behavior, POST and
94
+ explicit direct downloads, Native adapters, and browser-owned DOM/CSS asset
95
+ requests remain unchanged. This does not introduce font prefetch or a new cache.
96
+ The focused permanent file suite covers the demonstrated font path and is part
97
+ of the package's maintainer tests.