webspresso 0.0.108 → 0.0.110
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +3 -3
- package/bin/commands/add-esbuild.js +7 -3
- package/bin/commands/add-tailwind.js +9 -5
- package/bin/commands/build.js +20 -4
- package/bin/commands/dev.js +57 -7
- package/bin/commands/doctor.js +42 -1
- package/bin/commands/favicon-generate.js +10 -3
- package/bin/commands/new.js +8 -3
- package/bin/commands/start.js +3 -1
- package/bin/utils/add-command.js +16 -0
- package/core/app.js +45 -3
- package/core/auth/authenticate.js +3 -3
- package/core/auth/hash.js +167 -43
- package/core/auth/index.js +13 -1
- package/core/auth/jwt.js +21 -2
- package/core/auth/manager.js +63 -14
- package/core/auth/middleware.js +4 -2
- package/core/auth/oauth.js +5 -1
- package/core/auth/tokens.js +7 -2
- package/core/auth/totp.js +42 -6
- package/core/auth/user-agent.js +2 -0
- package/core/client/adapter/datastar.js +1401 -0
- package/core/client/api.js +1337 -0
- package/core/client/controller.js +1706 -0
- package/core/client/debug.js +367 -0
- package/core/client/devtool.js +1134 -0
- package/core/client/forms.js +1164 -0
- package/core/client/fragments.js +894 -0
- package/core/client/index.d.ts +59 -0
- package/core/client/index.js +391 -0
- package/core/client/lite.js +175 -0
- package/core/client/server-fragments.js +868 -0
- package/core/client/storage.js +339 -0
- package/core/client/utils.js +281 -0
- package/core/compression/middleware.js +277 -26
- package/core/context/app-context.js +25 -3
- package/core/context/request.js +32 -4
- package/core/errors/middleware.js +14 -0
- package/core/events/dispatcher.js +33 -0
- package/core/forms/flash.js +136 -102
- package/core/health/middleware.js +36 -6
- package/core/http/pipeline.js +45 -6
- package/core/index.js +25 -7
- package/core/kernel/view.js +41 -10
- package/core/metrics/middleware.js +30 -6
- package/core/metrics/registry.js +13 -5
- package/core/orm/cache/fingerprint.js +32 -11
- package/core/orm/cache/layer.js +19 -2
- package/core/orm/hidden.js +145 -0
- package/core/orm/model.js +48 -2
- package/core/orm/query-builder.js +343 -6
- package/core/orm/query-filters.js +14 -2
- package/core/orm/repository.js +64 -13
- package/core/orm/schema-helpers.js +9 -6
- package/core/orm/transaction.js +50 -6
- package/core/orm/types.js +4 -0
- package/core/queue/adapters/database.js +184 -2
- package/core/queue/adapters/memory.js +153 -5
- package/core/queue/adapters/redis.js +59 -4
- package/core/queue/job.js +14 -1
- package/core/queue/manager.js +115 -0
- package/core/resilience/circuit-breaker.js +27 -8
- package/core/services/builtins/exchange.js +174 -7
- package/core/services/builtins/file-manager.js +36 -0
- package/core/services/builtins/mail.js +27 -0
- package/core/services/builtins/queue.js +144 -0
- package/core/services/builtins/security.js +118 -0
- package/core/services/builtins/webhook.js +110 -0
- package/core/services/executor.js +38 -16
- package/core/services/index.js +4 -1
- package/core/sse/stream.js +28 -5
- package/core/utils/timeout.js +8 -1
- package/core/validation/compiler.js +10 -7
- package/index.d.ts +1320 -74
- package/index.js +128 -8
- package/package.json +75 -27
- package/plugins/admin-panel/client/parts/08-record-list.js +717 -70
- package/plugins/admin-panel/index.js +19 -8
- package/plugins/csrf/index.js +3 -3
- package/plugins/data-exchange/export.js +214 -0
- package/plugins/data-exchange/import.js +48 -5
- package/plugins/data-exchange/index.js +70 -28
- package/plugins/data-exchange/preview.js +266 -0
- package/plugins/data-exchange/template.js +242 -0
- package/plugins/email/admin-component.js +783 -141
- package/plugins/email/api-handlers.js +51 -1
- package/plugins/email/index.js +5 -0
- package/plugins/email/service.js +48 -0
- package/plugins/file-manager/admin-component.js +1546 -70
- package/plugins/file-manager/api-handlers.js +166 -1
- package/plugins/file-manager/core.js +598 -8
- package/plugins/file-manager/index.js +8 -0
- package/plugins/index.js +7 -0
- package/plugins/mcp/auth.js +3 -3
- package/plugins/oauth/index.js +36 -3
- package/plugins/queue/admin-component.js +1092 -0
- package/plugins/queue/api-handlers.js +248 -0
- package/plugins/queue/index.js +69 -0
- package/plugins/rest-resources/index.js +7 -2
- package/plugins/security/admin-component.js +689 -0
- package/plugins/security/api-handlers.js +169 -0
- package/plugins/security/audit.js +153 -0
- package/plugins/security/bruteforce.js +244 -0
- package/plugins/security/firewall.js +459 -0
- package/plugins/security/headers.js +214 -0
- package/plugins/security/honeypot.js +234 -0
- package/plugins/security/incident-recorder.js +137 -0
- package/plugins/security/index.js +211 -0
- package/plugins/seo-checker/analyzer.js +20 -7
- package/plugins/upload/index.js +36 -0
- package/plugins/webhooks/admin-component.js +702 -175
- package/plugins/webhooks/api-handlers.js +75 -1
- package/plugins/webhooks/dispatcher.js +290 -11
- package/plugins/webhooks/index.js +37 -2
- package/plugins/webhooks/sender.js +56 -0
- package/plugins/xlsx/engine.js +19 -4
- package/src/api/api-loader.js +19 -1
- package/src/bundle/index.js +443 -17
- package/src/client-runtime/bootstrap-swup.js +9 -0
- package/src/client-runtime/mount.js +15 -20
- package/src/client-runtime/resolve.js +3 -2
- package/src/dev/api-typegen.js +1300 -0
- package/src/dev/banner.js +10 -1
- package/src/dev/colors.js +1 -1
- package/src/dev/index.js +7 -1
- package/src/dev/typegen.js +173 -17
- package/src/dev-reload/index.js +1 -1
- package/src/discovery/file-route-parser.js +17 -3
- package/src/discovery/scan-routes.js +4 -1
- package/src/file-router.js +253 -69
- package/src/helpers.js +46 -26
- package/src/njk-frontmatter.js +30 -4
- package/src/routing/cascading.js +26 -8
- package/src/routing/mount-discovered-routes.js +76 -0
- package/src/server.js +231 -70
- package/views/partials/webspresso-client-runtime.njk +1 -9
- package/.agents/ADMIN.md +0 -426
- package/.agents/AGENTS.md +0 -96
- package/.agents/ARCHITECTURE.md +0 -163
- package/.agents/AUTH.md +0 -581
- package/.agents/CACHE.md +0 -148
- package/.agents/CLI.md +0 -649
- package/.agents/COMPRESSION.md +0 -59
- package/.agents/CONTEXT.md +0 -152
- package/.agents/CONVENTIONS.md +0 -50
- package/.agents/EARLY_HINTS.md +0 -120
- package/.agents/EMAIL.md +0 -223
- package/.agents/ERRORS.md +0 -260
- package/.agents/EVENTS.md +0 -179
- package/.agents/FLAGS.md +0 -118
- package/.agents/HEALTH.md +0 -118
- package/.agents/LIMITS.md +0 -109
- package/.agents/LOGGING.md +0 -93
- package/.agents/MCP.md +0 -103
- package/.agents/METRICS.md +0 -127
- package/.agents/MIGRATION_JOBS.md +0 -95
- package/.agents/ORM.md +0 -700
- package/.agents/PLUGINS.md +0 -729
- package/.agents/QUEUE.md +0 -290
- package/.agents/RATE_LIMIT.md +0 -147
- package/.agents/REALTIME.md +0 -213
- package/.agents/RESILIENCE.md +0 -235
- package/.agents/ROUTING.md +0 -605
- package/.agents/SCALE_OUT.md +0 -109
- package/.agents/SECRETS.md +0 -117
- package/.agents/SERVICES.md +0 -341
- package/.agents/SHUTDOWN.md +0 -74
- package/.agents/STREAMING.md +0 -108
- package/.agents/WORKFLOW.md +0 -27
- package/.agents/internal/DOCUMENTATION_REVIEW.md +0 -485
- package/.agents/internal/TECHNICAL_REVIEW.md +0 -428
- package/.agents/skills/webspresso-admin-and-plugins/SKILL.md +0 -122
- package/.agents/skills/webspresso-framework/SKILL.md +0 -89
- package/.agents/skills/webspresso-orm-and-database/SKILL.md +0 -127
- package/.agents/skills/webspresso-routing-and-api/SKILL.md +0 -130
- package/.agents/skills/webspresso-services/SKILL.md +0 -134
- package/.cursorrules +0 -14
- package/AGENTS.md +0 -203
- package/CLAUDE.md +0 -54
- package/core/kernel/run-demo.js +0 -58
- package/plugins/admin-panel/styles.js +0 -9
- package/plugins/data-exchange/export-xlsx.js +0 -119
- package/src/client-runtime/bootstrap-alpine-swup.js +0 -34
|
@@ -0,0 +1,894 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { defaultStorage } = require('./storage');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Webspresso Client-Side SSR Fragment Coordinator & Invalidation Engine
|
|
7
|
+
*
|
|
8
|
+
* Responsibilities:
|
|
9
|
+
* - Discovers active `[data-w-fragment]` instances in the DOM
|
|
10
|
+
* - Separates fragment definition name (`data-w-fragment`) from instance ID (`data-w-fragment-id`)
|
|
11
|
+
* - Tracks `dependsOn` tags (`data-w-depends-on`) per fragment instance
|
|
12
|
+
* - Skips network refresh completely if no active fragment on the page matches invalidated tags
|
|
13
|
+
* - Deduplicates parent/child fragments when both are invalidated (parent refresh covers child)
|
|
14
|
+
* - Coalesces simultaneous invalidations into a single batch request (`POST /__webspresso/fragments`)
|
|
15
|
+
* - Queues follow-up refreshes when new invalidations arrive during an in-flight refresh so the
|
|
16
|
+
* latest mutation's invalidation is never lost
|
|
17
|
+
* - Enforces monotonic per-instance `refreshVersion` so stale responses never overwrite newer DOM
|
|
18
|
+
* - Supports retryable refresh (`retryFailed()` / `refresh()`) without re-sending mutations
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const DEFAULT_FRAGMENT_ENDPOINT = '/__webspresso/fragments';
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Parse `data-w-depends-on` attribute (comma-separated or JSON array).
|
|
25
|
+
*
|
|
26
|
+
* @param {string|null} raw
|
|
27
|
+
* @returns {string[]}
|
|
28
|
+
*/
|
|
29
|
+
function parseDependsOnAttr(raw) {
|
|
30
|
+
if (!raw || typeof raw !== 'string') return [];
|
|
31
|
+
const trimmed = raw.trim();
|
|
32
|
+
if (!trimmed) return [];
|
|
33
|
+
if (trimmed.startsWith('[')) {
|
|
34
|
+
try {
|
|
35
|
+
const parsed = JSON.parse(trimmed);
|
|
36
|
+
if (Array.isArray(parsed)) {
|
|
37
|
+
return parsed.map((s) => String(s).trim()).filter(Boolean);
|
|
38
|
+
}
|
|
39
|
+
} catch (_e) {
|
|
40
|
+
// Fallback to comma split
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return trimmed
|
|
44
|
+
.split(',')
|
|
45
|
+
.map((s) => s.trim())
|
|
46
|
+
.filter(Boolean);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Parse `data-w-fragment-input` JSON attribute safely.
|
|
51
|
+
*
|
|
52
|
+
* @param {string|null} raw
|
|
53
|
+
* @returns {Record<string, unknown>}
|
|
54
|
+
*/
|
|
55
|
+
function parseFragmentInputAttr(raw) {
|
|
56
|
+
if (!raw || typeof raw !== 'string') return {};
|
|
57
|
+
const trimmed = raw.trim();
|
|
58
|
+
if (!trimmed) return {};
|
|
59
|
+
try {
|
|
60
|
+
const parsed = JSON.parse(trimmed);
|
|
61
|
+
return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
62
|
+
} catch (_e) {
|
|
63
|
+
return {};
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Filter a list of fragment records so that if fragment B's DOM element is inside
|
|
69
|
+
* fragment A's DOM subtree, B is omitted from the batch because refreshing A will
|
|
70
|
+
* re-render B on the server.
|
|
71
|
+
*
|
|
72
|
+
* @param {Array<{ instanceId: string, el: Element }>} candidates
|
|
73
|
+
* @returns {Array<{ instanceId: string, el: Element }>}
|
|
74
|
+
*/
|
|
75
|
+
function deduplicateParentChildFragments(candidates) {
|
|
76
|
+
if (candidates.length <= 1) return candidates;
|
|
77
|
+
return candidates.filter((candidate) => {
|
|
78
|
+
if (!candidate.el) return true;
|
|
79
|
+
for (const other of candidates) {
|
|
80
|
+
if (other === candidate || !other.el) continue;
|
|
81
|
+
if (other.el !== candidate.el && typeof other.el.contains === 'function' && other.el.contains(candidate.el)) {
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return true;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Create a Fragment Coordinator instance.
|
|
91
|
+
*
|
|
92
|
+
* @param {object} [options]
|
|
93
|
+
* @param {Document|Element} [options.root] - Root document or container element
|
|
94
|
+
* @param {typeof fetch} [options.fetch] - Custom fetch function
|
|
95
|
+
* @param {string} [options.endpoint='/__webspresso/fragments'] - Server fragment refresh endpoint
|
|
96
|
+
* @param {object} [options.datastar] - Datastar adapter for DOM morphing
|
|
97
|
+
* @param {(el: Element) => void} [options.onBeforeNodeRemove] - Hook called before a node is removed during morph
|
|
98
|
+
* @param {(el: Element) => void} [options.onNodeAdded] - Hook called when a new node is added during morph
|
|
99
|
+
* @param {(el: Element) => void} [options.onAfterPatch] - Hook called after a fragment is patched
|
|
100
|
+
* @param {() => string|null} [options.getCsrfToken] - CSRF token getter
|
|
101
|
+
* @param {object} [options.debug] - Client debugger instance
|
|
102
|
+
*/
|
|
103
|
+
function createFragmentCoordinator(options = {}) {
|
|
104
|
+
const getRoot = () =>
|
|
105
|
+
options.root || options.document || (typeof document !== 'undefined' ? document : null);
|
|
106
|
+
const fetchImpl =
|
|
107
|
+
options.fetch || (typeof globalThis.fetch === 'function' ? globalThis.fetch.bind(globalThis) : null);
|
|
108
|
+
const endpoint = options.endpoint || DEFAULT_FRAGMENT_ENDPOINT;
|
|
109
|
+
const datastar = options.datastar || options.adapter;
|
|
110
|
+
const debug = options.debug || null;
|
|
111
|
+
const defaultTimeout = typeof options.timeout === 'number' ? options.timeout : 15000;
|
|
112
|
+
|
|
113
|
+
// Map<instanceId, { instanceId, name, pagePath, input, dependsOn: Set<string>, version: number, el: Element, abortController: AbortController|null }>
|
|
114
|
+
const instances = new Map();
|
|
115
|
+
|
|
116
|
+
// Coalescing & in-flight state for tag invalidations
|
|
117
|
+
const pendingTags = new Set();
|
|
118
|
+
const pendingChains = [];
|
|
119
|
+
let batchTimer = null;
|
|
120
|
+
let inFlightBatchCount = 0;
|
|
121
|
+
let followUpNeeded = false;
|
|
122
|
+
let lastFailedBatch = null;
|
|
123
|
+
const inflightBatchWaiters = [];
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Scan DOM and synchronize tracked `[data-w-fragment]` instances.
|
|
127
|
+
*/
|
|
128
|
+
function syncDomInstances(containerEl) {
|
|
129
|
+
const root = containerEl || getRoot();
|
|
130
|
+
if (!root || typeof root.querySelectorAll !== 'function') return [];
|
|
131
|
+
|
|
132
|
+
const elements = Array.from(root.querySelectorAll('[data-w-fragment]'));
|
|
133
|
+
if (root.nodeType === 1 && root.hasAttribute && root.hasAttribute('data-w-fragment')) {
|
|
134
|
+
elements.unshift(root);
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const seenIds = new Set();
|
|
138
|
+
|
|
139
|
+
for (let i = 0; i < elements.length; i++) {
|
|
140
|
+
const el = elements[i];
|
|
141
|
+
const name = (el.getAttribute('data-w-fragment') || '').trim();
|
|
142
|
+
if (!name) continue;
|
|
143
|
+
|
|
144
|
+
let instanceId = (el.getAttribute('data-w-fragment-id') || '').trim();
|
|
145
|
+
if (!instanceId) {
|
|
146
|
+
instanceId = i === 0 ? `${name}:default` : `${name}:${i}`;
|
|
147
|
+
el.setAttribute('data-w-fragment-id', instanceId);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
seenIds.add(instanceId);
|
|
151
|
+
const pagePath =
|
|
152
|
+
(el.getAttribute('data-w-fragment-page') || '').trim() ||
|
|
153
|
+
(typeof window !== 'undefined' && window.location ? window.location.pathname : '/');
|
|
154
|
+
const input = parseFragmentInputAttr(el.getAttribute('data-w-fragment-input'));
|
|
155
|
+
const dependsOn = new Set(parseDependsOnAttr(el.getAttribute('data-w-depends-on')));
|
|
156
|
+
|
|
157
|
+
// Fragment input persistence setup
|
|
158
|
+
const rawPersistInput =
|
|
159
|
+
el.getAttribute('data-w-persist-input') ||
|
|
160
|
+
(el.getAttribute('data-w-persist') === 'input' ? 'session' : null);
|
|
161
|
+
const isInputPersistEnabled = Boolean(rawPersistInput && rawPersistInput !== 'false');
|
|
162
|
+
const inputStorageType = rawPersistInput && rawPersistInput.toLowerCase() === 'local' ? 'local' : 'session';
|
|
163
|
+
const inputStorageKey =
|
|
164
|
+
el.getAttribute('data-w-persist-key') ||
|
|
165
|
+
el.getAttribute('data-w-input-key') ||
|
|
166
|
+
`frag_input:${name}`;
|
|
167
|
+
|
|
168
|
+
let effectiveInput = input;
|
|
169
|
+
if (isInputPersistEnabled) {
|
|
170
|
+
const store = inputStorageType === 'local' ? defaultStorage.local : defaultStorage.session;
|
|
171
|
+
if (!el.hasAttribute('data-w-fragment-input') || Object.keys(effectiveInput).length === 0) {
|
|
172
|
+
const stored = store.get(inputStorageKey, null);
|
|
173
|
+
if (stored && typeof stored === 'object' && !Array.isArray(stored)) {
|
|
174
|
+
effectiveInput = stored;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const existing = instances.get(instanceId);
|
|
180
|
+
if (existing) {
|
|
181
|
+
existing.name = name;
|
|
182
|
+
existing.pagePath = pagePath;
|
|
183
|
+
existing.el = el;
|
|
184
|
+
existing.dependsOn = dependsOn;
|
|
185
|
+
if (el.hasAttribute('data-w-fragment-input') || isInputPersistEnabled) {
|
|
186
|
+
existing.input = effectiveInput;
|
|
187
|
+
}
|
|
188
|
+
existing.persistInput = isInputPersistEnabled ? { type: inputStorageType, key: inputStorageKey } : null;
|
|
189
|
+
} else {
|
|
190
|
+
instances.set(instanceId, {
|
|
191
|
+
instanceId,
|
|
192
|
+
name,
|
|
193
|
+
pagePath,
|
|
194
|
+
input: effectiveInput,
|
|
195
|
+
dependsOn,
|
|
196
|
+
version: 0,
|
|
197
|
+
el,
|
|
198
|
+
abortController: null,
|
|
199
|
+
persistInput: isInputPersistEnabled ? { type: inputStorageType, key: inputStorageKey } : null,
|
|
200
|
+
});
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Prune disconnected instances if scanning full root
|
|
205
|
+
if (!containerEl || containerEl === getRoot()) {
|
|
206
|
+
for (const [id, inst] of instances.entries()) {
|
|
207
|
+
const disconnected =
|
|
208
|
+
!seenIds.has(id) || (inst.el && inst.el.isConnected === false);
|
|
209
|
+
if (disconnected) {
|
|
210
|
+
if (inst.abortController) {
|
|
211
|
+
try {
|
|
212
|
+
inst.abortController.abort();
|
|
213
|
+
} catch (_e) {
|
|
214
|
+
// Ignore
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
instances.delete(id);
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
return Array.from(instances.values());
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Apply a single server fragment result `{ instanceId, name, html, input, loadMs, renderMs }`
|
|
227
|
+
* to the DOM if and only if `reqVersion >= inst.version`.
|
|
228
|
+
*/
|
|
229
|
+
function applyFragmentPatch(inst, fragmentPayload, reqVersion, chainId = null) {
|
|
230
|
+
if (!inst || !inst.el) return false;
|
|
231
|
+
|
|
232
|
+
if (reqVersion < inst.version) {
|
|
233
|
+
if (debug) {
|
|
234
|
+
debug.trackDiscardedResponse({
|
|
235
|
+
source: 'fragment',
|
|
236
|
+
instanceId: inst.instanceId,
|
|
237
|
+
key: inst.name,
|
|
238
|
+
reason: 'stale-version',
|
|
239
|
+
version: reqVersion,
|
|
240
|
+
currentVersion: inst.version,
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
return false;
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const html = fragmentPayload && typeof fragmentPayload.html === 'string' ? fragmentPayload.html : '';
|
|
247
|
+
if (!html) return false;
|
|
248
|
+
|
|
249
|
+
const patchStart = Date.now();
|
|
250
|
+
|
|
251
|
+
if (
|
|
252
|
+
fragmentPayload.input &&
|
|
253
|
+
typeof fragmentPayload.input === 'object' &&
|
|
254
|
+
!followUpNeeded &&
|
|
255
|
+
pendingTags.size === 0
|
|
256
|
+
) {
|
|
257
|
+
inst.input = fragmentPayload.input;
|
|
258
|
+
inst.el.setAttribute('data-w-fragment-input', JSON.stringify(fragmentPayload.input));
|
|
259
|
+
if (inst.persistInput) {
|
|
260
|
+
const store = inst.persistInput.type === 'local' ? defaultStorage.local : defaultStorage.session;
|
|
261
|
+
store.set(inst.persistInput.key, fragmentPayload.input);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (datastar && typeof datastar.patchFragmentElement === 'function') {
|
|
266
|
+
datastar.patchFragmentElement(inst.el, html, {
|
|
267
|
+
onBeforeNodeRemove: options.onBeforeNodeRemove,
|
|
268
|
+
onNodeAdded: options.onNodeAdded,
|
|
269
|
+
});
|
|
270
|
+
} else {
|
|
271
|
+
inst.el.innerHTML = html;
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const patchMs = Math.max(0, Date.now() - patchStart);
|
|
275
|
+
|
|
276
|
+
// Re-sync nested fragment instances that may have been updated inside this parent fragment
|
|
277
|
+
syncDomInstances(inst.el);
|
|
278
|
+
|
|
279
|
+
if (typeof options.onAfterPatch === 'function') {
|
|
280
|
+
options.onAfterPatch(inst.el, inst);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
if (debug) {
|
|
284
|
+
debug.recordChainPatch(chainId, {
|
|
285
|
+
instanceId: inst.instanceId,
|
|
286
|
+
fragmentName: inst.name,
|
|
287
|
+
patchMs,
|
|
288
|
+
loadMs: fragmentPayload.loadMs !== undefined ? fragmentPayload.loadMs : null,
|
|
289
|
+
renderMs: fragmentPayload.renderMs !== undefined ? fragmentPayload.renderMs : null,
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return true;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/**
|
|
297
|
+
* Execute a network refresh for a list of target fragment descriptors:
|
|
298
|
+
* `Array<{ instanceId, name, pagePath, input, reqVersion }>`
|
|
299
|
+
*/
|
|
300
|
+
async function executeBatchRefresh(targets, chainIds = [], abortSignal = null, batchTimeout = defaultTimeout) {
|
|
301
|
+
if (!targets || targets.length === 0) {
|
|
302
|
+
return { refreshed: [], skipped: true };
|
|
303
|
+
}
|
|
304
|
+
if (!fetchImpl) {
|
|
305
|
+
throw new Error('Global fetch is not available for fragment refresh.');
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
const headers = {
|
|
309
|
+
Accept: 'application/json',
|
|
310
|
+
'Content-Type': 'application/json',
|
|
311
|
+
'X-Requested-With': 'XMLHttpRequest',
|
|
312
|
+
'X-Webspresso-Fragment-Request': '1',
|
|
313
|
+
};
|
|
314
|
+
|
|
315
|
+
if (typeof options.getCsrfToken === 'function') {
|
|
316
|
+
const token = options.getCsrfToken();
|
|
317
|
+
if (token) headers['X-CSRF-Token'] = token;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const pagePath =
|
|
321
|
+
targets[0].pagePath ||
|
|
322
|
+
(typeof window !== 'undefined' && window.location ? window.location.pathname : '/');
|
|
323
|
+
|
|
324
|
+
const requestPayload = {
|
|
325
|
+
pagePath,
|
|
326
|
+
fragments: targets.map((t) => ({
|
|
327
|
+
instanceId: t.instanceId,
|
|
328
|
+
name: t.name,
|
|
329
|
+
input: t.input || {},
|
|
330
|
+
version: t.reqVersion,
|
|
331
|
+
})),
|
|
332
|
+
};
|
|
333
|
+
|
|
334
|
+
const reqId = `frag_req_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`;
|
|
335
|
+
if (debug) {
|
|
336
|
+
debug.trackRequestStart({
|
|
337
|
+
requestId: reqId,
|
|
338
|
+
key: `fragments:${targets.map((t) => t.instanceId).join(',')}`,
|
|
339
|
+
method: 'POST',
|
|
340
|
+
url: endpoint,
|
|
341
|
+
policy: 'latest',
|
|
342
|
+
payload: { count: targets.length },
|
|
343
|
+
});
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const batchAbortController = new AbortController();
|
|
347
|
+
let timeoutTimer = null;
|
|
348
|
+
let timedOut = false;
|
|
349
|
+
const timeoutMs = typeof batchTimeout === 'number' ? batchTimeout : defaultTimeout;
|
|
350
|
+
|
|
351
|
+
if (timeoutMs > 0) {
|
|
352
|
+
timeoutTimer = setTimeout(() => {
|
|
353
|
+
timedOut = true;
|
|
354
|
+
batchAbortController.abort();
|
|
355
|
+
}, timeoutMs);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const onCallerAbort = () => batchAbortController.abort();
|
|
359
|
+
if (abortSignal) {
|
|
360
|
+
if (abortSignal.aborted) {
|
|
361
|
+
batchAbortController.abort();
|
|
362
|
+
} else {
|
|
363
|
+
abortSignal.addEventListener('abort', onCallerAbort, { once: true });
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
let response;
|
|
368
|
+
try {
|
|
369
|
+
response = await fetchImpl(endpoint, {
|
|
370
|
+
method: 'POST',
|
|
371
|
+
headers,
|
|
372
|
+
body: JSON.stringify(requestPayload),
|
|
373
|
+
credentials: 'same-origin',
|
|
374
|
+
signal: batchAbortController.signal,
|
|
375
|
+
});
|
|
376
|
+
} catch (err) {
|
|
377
|
+
if (timeoutTimer) {
|
|
378
|
+
clearTimeout(timeoutTimer);
|
|
379
|
+
timeoutTimer = null;
|
|
380
|
+
}
|
|
381
|
+
if (abortSignal) {
|
|
382
|
+
try {
|
|
383
|
+
abortSignal.removeEventListener('abort', onCallerAbort);
|
|
384
|
+
} catch (_e) {}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
if (timedOut) {
|
|
388
|
+
if (debug) {
|
|
389
|
+
debug.trackRequestEnd(reqId, {
|
|
390
|
+
status: 'failed',
|
|
391
|
+
errorKind: 'timeout',
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
const timeoutError = new Error(`Fragment refresh timed out after ${timeoutMs}ms.`);
|
|
395
|
+
timeoutError.code = 'FRAGMENT_REFRESH_TIMEOUT';
|
|
396
|
+
timeoutError.isTimedOut = true;
|
|
397
|
+
lastFailedBatch = { targets, chainIds };
|
|
398
|
+
for (const cid of chainIds) {
|
|
399
|
+
if (debug) {
|
|
400
|
+
debug.recordChainRefresh(cid, {
|
|
401
|
+
fragmentIds: targets.map((t) => t.instanceId),
|
|
402
|
+
status: 'failed',
|
|
403
|
+
error: timeoutError,
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
throw timeoutError;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
const isAbort =
|
|
411
|
+
(abortSignal && abortSignal.aborted) ||
|
|
412
|
+
batchAbortController.signal.aborted ||
|
|
413
|
+
(err && (err.name === 'AbortError' || err.code === 'ABORT_ERR'));
|
|
414
|
+
|
|
415
|
+
if (debug) {
|
|
416
|
+
debug.trackRequestEnd(reqId, {
|
|
417
|
+
status: isAbort ? 'canceled' : 'failed',
|
|
418
|
+
errorKind: isAbort ? 'canceled' : 'network',
|
|
419
|
+
});
|
|
420
|
+
}
|
|
421
|
+
if (isAbort) {
|
|
422
|
+
return { ok: false, refreshed: [], canceled: true };
|
|
423
|
+
}
|
|
424
|
+
lastFailedBatch = { targets, chainIds };
|
|
425
|
+
for (const cid of chainIds) {
|
|
426
|
+
if (debug) {
|
|
427
|
+
debug.recordChainRefresh(cid, {
|
|
428
|
+
fragmentIds: targets.map((t) => t.instanceId),
|
|
429
|
+
status: 'failed',
|
|
430
|
+
error: err,
|
|
431
|
+
});
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
throw err;
|
|
435
|
+
} finally {
|
|
436
|
+
if (timeoutTimer) {
|
|
437
|
+
clearTimeout(timeoutTimer);
|
|
438
|
+
timeoutTimer = null;
|
|
439
|
+
}
|
|
440
|
+
if (abortSignal) {
|
|
441
|
+
try {
|
|
442
|
+
abortSignal.removeEventListener('abort', onCallerAbort);
|
|
443
|
+
} catch (_e) {}
|
|
444
|
+
}
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
let body = null;
|
|
448
|
+
try {
|
|
449
|
+
if (typeof response.text === 'function') {
|
|
450
|
+
const text = await response.text();
|
|
451
|
+
body = text ? JSON.parse(text) : null;
|
|
452
|
+
} else if (typeof response.json === 'function') {
|
|
453
|
+
body = await response.json();
|
|
454
|
+
}
|
|
455
|
+
} catch (_e) {
|
|
456
|
+
body = null;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
if (!response.ok) {
|
|
460
|
+
if (debug) {
|
|
461
|
+
debug.trackRequestEnd(reqId, {
|
|
462
|
+
status: 'failed',
|
|
463
|
+
httpStatus: response.status,
|
|
464
|
+
errorKind: 'http',
|
|
465
|
+
});
|
|
466
|
+
}
|
|
467
|
+
const errMsg =
|
|
468
|
+
(body && body.error && body.error.message) ||
|
|
469
|
+
(body && body.message) ||
|
|
470
|
+
`Fragment refresh failed with HTTP ${response.status}`;
|
|
471
|
+
const refreshError = new Error(errMsg);
|
|
472
|
+
refreshError.status = response.status;
|
|
473
|
+
refreshError.data = body;
|
|
474
|
+
lastFailedBatch = { targets, chainIds };
|
|
475
|
+
for (const cid of chainIds) {
|
|
476
|
+
if (debug) {
|
|
477
|
+
debug.recordChainRefresh(cid, {
|
|
478
|
+
fragmentIds: targets.map((t) => t.instanceId),
|
|
479
|
+
status: 'failed',
|
|
480
|
+
error: refreshError,
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
throw refreshError;
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
if (debug) {
|
|
488
|
+
debug.trackRequestEnd(reqId, { status: 'completed', httpStatus: response.status });
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
lastFailedBatch = null;
|
|
492
|
+
const resultsMap = (body && body.fragments) || {};
|
|
493
|
+
const refreshedIds = [];
|
|
494
|
+
let totalLoadMs = 0;
|
|
495
|
+
let totalRenderMs = 0;
|
|
496
|
+
|
|
497
|
+
for (const target of targets) {
|
|
498
|
+
const inst = instances.get(target.instanceId);
|
|
499
|
+
const fragResult = resultsMap[target.instanceId] || resultsMap[target.name];
|
|
500
|
+
if (!inst || !fragResult) continue;
|
|
501
|
+
if (typeof fragResult.loadMs === 'number') totalLoadMs += fragResult.loadMs;
|
|
502
|
+
if (typeof fragResult.renderMs === 'number') totalRenderMs += fragResult.renderMs;
|
|
503
|
+
|
|
504
|
+
const applied = applyFragmentPatch(
|
|
505
|
+
inst,
|
|
506
|
+
fragResult,
|
|
507
|
+
target.reqVersion,
|
|
508
|
+
chainIds[0] || null
|
|
509
|
+
);
|
|
510
|
+
if (applied) {
|
|
511
|
+
refreshedIds.push(target.instanceId);
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
for (const cid of chainIds) {
|
|
516
|
+
if (debug) {
|
|
517
|
+
debug.recordChainRefresh(cid, {
|
|
518
|
+
fragmentIds: refreshedIds,
|
|
519
|
+
status: 'ok',
|
|
520
|
+
loadMs: totalLoadMs,
|
|
521
|
+
renderMs: totalRenderMs,
|
|
522
|
+
totalServerMs: body && typeof body.totalMs === 'number' ? body.totalMs : null,
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
return {
|
|
528
|
+
ok: true,
|
|
529
|
+
refreshed: refreshedIds,
|
|
530
|
+
errors: [],
|
|
531
|
+
timings: {
|
|
532
|
+
loadMs: totalLoadMs,
|
|
533
|
+
renderMs: totalRenderMs,
|
|
534
|
+
},
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
/**
|
|
539
|
+
* Flush pending invalidated tags in a single coalesced request.
|
|
540
|
+
* If a flush is currently in flight, sets `followUpNeeded = true` so that
|
|
541
|
+
* newly invalidated tags are flushed immediately when the in-flight request finishes.
|
|
542
|
+
*/
|
|
543
|
+
async function flushInvalidations() {
|
|
544
|
+
if (inFlightBatchCount > 0) {
|
|
545
|
+
followUpNeeded = true;
|
|
546
|
+
return new Promise((resolve, reject) => {
|
|
547
|
+
inflightBatchWaiters.push({ resolve, reject });
|
|
548
|
+
});
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (pendingTags.size === 0) {
|
|
552
|
+
return { ok: true, refreshed: [], skipped: true };
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const tagsToFlush = new Set(pendingTags);
|
|
556
|
+
const chainsToFlush = [...pendingChains];
|
|
557
|
+
pendingTags.clear();
|
|
558
|
+
pendingChains.length = 0;
|
|
559
|
+
|
|
560
|
+
syncDomInstances();
|
|
561
|
+
|
|
562
|
+
// Find all mounted fragment instances whose `dependsOn` intersects `tagsToFlush`
|
|
563
|
+
const matchingInstances = [];
|
|
564
|
+
for (const inst of instances.values()) {
|
|
565
|
+
let matched = false;
|
|
566
|
+
for (const tag of tagsToFlush) {
|
|
567
|
+
if (inst.dependsOn.has(tag) || inst.name === tag) {
|
|
568
|
+
matched = true;
|
|
569
|
+
break;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
if (matched) {
|
|
573
|
+
matchingInstances.push(inst);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
|
|
577
|
+
// If no active fragment on the open page matches, send ZERO network requests!
|
|
578
|
+
if (matchingInstances.length === 0) {
|
|
579
|
+
for (const cid of chainsToFlush) {
|
|
580
|
+
if (debug) {
|
|
581
|
+
debug.recordChainRefresh(cid, {
|
|
582
|
+
fragmentIds: [],
|
|
583
|
+
status: 'skipped-no-matching-fragment',
|
|
584
|
+
});
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
return { ok: true, refreshed: [], skipped: true };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// Parent/Child deduplication: if parent & child are both invalidated, parent refresh covers child
|
|
591
|
+
const dedupedInstances = deduplicateParentChildFragments(matchingInstances);
|
|
592
|
+
|
|
593
|
+
const targets = dedupedInstances.map((inst) => {
|
|
594
|
+
inst.version += 1;
|
|
595
|
+
return {
|
|
596
|
+
instanceId: inst.instanceId,
|
|
597
|
+
name: inst.name,
|
|
598
|
+
pagePath: inst.pagePath,
|
|
599
|
+
input: { ...inst.input },
|
|
600
|
+
reqVersion: inst.version,
|
|
601
|
+
};
|
|
602
|
+
});
|
|
603
|
+
|
|
604
|
+
inFlightBatchCount += 1;
|
|
605
|
+
try {
|
|
606
|
+
const result = await executeBatchRefresh(targets, chainsToFlush);
|
|
607
|
+
// If new invalidations arrived while this batch was in flight, run follow-up immediately!
|
|
608
|
+
if (followUpNeeded || pendingTags.size > 0) {
|
|
609
|
+
followUpNeeded = false;
|
|
610
|
+
inFlightBatchCount -= 1;
|
|
611
|
+
const followUpResult = await flushInvalidations();
|
|
612
|
+
const waiters = inflightBatchWaiters.splice(0, inflightBatchWaiters.length);
|
|
613
|
+
for (const w of waiters) w.resolve(followUpResult);
|
|
614
|
+
return followUpResult;
|
|
615
|
+
}
|
|
616
|
+
const waiters = inflightBatchWaiters.splice(0, inflightBatchWaiters.length);
|
|
617
|
+
for (const w of waiters) w.resolve(result);
|
|
618
|
+
return result;
|
|
619
|
+
} catch (err) {
|
|
620
|
+
const waiters = inflightBatchWaiters.splice(0, inflightBatchWaiters.length);
|
|
621
|
+
for (const w of waiters) w.reject(err);
|
|
622
|
+
throw err;
|
|
623
|
+
} finally {
|
|
624
|
+
if (inFlightBatchCount > 0) {
|
|
625
|
+
inFlightBatchCount -= 1;
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* Invalidate one or more dependency tags (e.g. `['notes']`).
|
|
632
|
+
* Coalesces multiple invalidation calls within the same microtask into a single batch request.
|
|
633
|
+
*
|
|
634
|
+
* @param {string|string[]} tags
|
|
635
|
+
* @param {object} [meta]
|
|
636
|
+
* @returns {Promise<{ refreshed: string[], skipped?: boolean }>}
|
|
637
|
+
*/
|
|
638
|
+
function invalidate(tags, meta = {}) {
|
|
639
|
+
const tagList = Array.isArray(tags) ? tags : [tags];
|
|
640
|
+
for (const raw of tagList) {
|
|
641
|
+
if (typeof raw === 'string' && raw.trim()) {
|
|
642
|
+
pendingTags.add(raw.trim());
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
if (meta && meta.chainId) {
|
|
646
|
+
pendingChains.push(meta.chainId);
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
if (batchTimer) {
|
|
650
|
+
return batchTimer.promise;
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
let resolveBatch;
|
|
654
|
+
let rejectBatch;
|
|
655
|
+
const promise = new Promise((resolve, reject) => {
|
|
656
|
+
resolveBatch = resolve;
|
|
657
|
+
rejectBatch = reject;
|
|
658
|
+
});
|
|
659
|
+
|
|
660
|
+
batchTimer = {
|
|
661
|
+
promise,
|
|
662
|
+
};
|
|
663
|
+
|
|
664
|
+
// Coalesce synchronous/microtask invalidations before flushing
|
|
665
|
+
Promise.resolve().then(async () => {
|
|
666
|
+
batchTimer = null;
|
|
667
|
+
try {
|
|
668
|
+
const res = await flushInvalidations();
|
|
669
|
+
resolveBatch(res);
|
|
670
|
+
} catch (err) {
|
|
671
|
+
rejectBatch(err);
|
|
672
|
+
}
|
|
673
|
+
});
|
|
674
|
+
|
|
675
|
+
return promise;
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Explicitly refresh a specific fragment instance (or all instances of a fragment name)
|
|
680
|
+
* with optional updated filter/pagination input.
|
|
681
|
+
* Enforces `'latest'` semantics per instance so rapid filter changes discard stale responses.
|
|
682
|
+
*
|
|
683
|
+
* @param {string} idOrName - `instanceId` (e.g. `'list:default'`) or fragment `name` (e.g. `'list'`)
|
|
684
|
+
* @param {Record<string, unknown>} [nextInput] - Partial or new input parameters
|
|
685
|
+
* @param {object} [refreshOpts]
|
|
686
|
+
*/
|
|
687
|
+
async function refresh(idOrName, nextInput, refreshOpts = {}) {
|
|
688
|
+
syncDomInstances();
|
|
689
|
+
|
|
690
|
+
const matched = [];
|
|
691
|
+
if (instances.has(idOrName)) {
|
|
692
|
+
matched.push(instances.get(idOrName));
|
|
693
|
+
} else {
|
|
694
|
+
for (const inst of instances.values()) {
|
|
695
|
+
if (inst.name === idOrName) {
|
|
696
|
+
matched.push(inst);
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
|
|
701
|
+
if (matched.length === 0) {
|
|
702
|
+
const skippedRes = { ok: true, refreshed: [], skipped: true };
|
|
703
|
+
if (typeof refreshOpts.onSuccess === 'function') {
|
|
704
|
+
await refreshOpts.onSuccess(skippedRes);
|
|
705
|
+
}
|
|
706
|
+
if (typeof refreshOpts.onSettled === 'function') {
|
|
707
|
+
await refreshOpts.onSettled(skippedRes, null);
|
|
708
|
+
} else if (typeof refreshOpts.onComplete === 'function') {
|
|
709
|
+
await refreshOpts.onComplete(skippedRes, null);
|
|
710
|
+
}
|
|
711
|
+
return skippedRes;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
const deduped = deduplicateParentChildFragments(matched);
|
|
715
|
+
const abortController = new AbortController();
|
|
716
|
+
|
|
717
|
+
const targets = deduped.map((inst) => {
|
|
718
|
+
// Abort previous direct refresh for this instance so rapid filter updates don't race
|
|
719
|
+
if (inst.abortController) {
|
|
720
|
+
try {
|
|
721
|
+
inst.abortController.abort();
|
|
722
|
+
} catch (_e) {
|
|
723
|
+
// Ignore
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
inst.abortController = abortController;
|
|
727
|
+
inst.version += 1;
|
|
728
|
+
|
|
729
|
+
if (nextInput && typeof nextInput === 'object') {
|
|
730
|
+
inst.input = refreshOpts.replaceInput
|
|
731
|
+
? { ...nextInput }
|
|
732
|
+
: { ...inst.input, ...nextInput };
|
|
733
|
+
if (inst.el && typeof inst.el.setAttribute === 'function') {
|
|
734
|
+
inst.el.setAttribute('data-w-fragment-input', JSON.stringify(inst.input));
|
|
735
|
+
}
|
|
736
|
+
if (inst.persistInput) {
|
|
737
|
+
const store = inst.persistInput.type === 'local' ? defaultStorage.local : defaultStorage.session;
|
|
738
|
+
store.set(inst.persistInput.key, inst.input);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
return {
|
|
743
|
+
instanceId: inst.instanceId,
|
|
744
|
+
name: inst.name,
|
|
745
|
+
pagePath: inst.pagePath,
|
|
746
|
+
input: { ...inst.input },
|
|
747
|
+
reqVersion: inst.version,
|
|
748
|
+
};
|
|
749
|
+
});
|
|
750
|
+
|
|
751
|
+
try {
|
|
752
|
+
const result = await executeBatchRefresh(targets, [], abortController.signal, refreshOpts.timeout);
|
|
753
|
+
const enrichedResult = { ok: true, ...result };
|
|
754
|
+
if (!enrichedResult.canceled && enrichedResult.ok !== false) {
|
|
755
|
+
if (typeof refreshOpts.onSuccess === 'function') {
|
|
756
|
+
await refreshOpts.onSuccess(enrichedResult);
|
|
757
|
+
}
|
|
758
|
+
}
|
|
759
|
+
if (typeof refreshOpts.onSettled === 'function') {
|
|
760
|
+
await refreshOpts.onSettled(enrichedResult, null);
|
|
761
|
+
} else if (typeof refreshOpts.onComplete === 'function') {
|
|
762
|
+
await refreshOpts.onComplete(enrichedResult, null);
|
|
763
|
+
}
|
|
764
|
+
return enrichedResult;
|
|
765
|
+
} catch (err) {
|
|
766
|
+
const failHandler = refreshOpts.onFailure || refreshOpts.onError;
|
|
767
|
+
if (typeof failHandler === 'function') {
|
|
768
|
+
try {
|
|
769
|
+
await failHandler(err);
|
|
770
|
+
} catch (callbackErr) {
|
|
771
|
+
throw callbackErr;
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
if (typeof refreshOpts.onSettled === 'function') {
|
|
775
|
+
await refreshOpts.onSettled(null, err);
|
|
776
|
+
} else if (typeof refreshOpts.onComplete === 'function') {
|
|
777
|
+
await refreshOpts.onComplete(null, err);
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
if (refreshOpts.throwOnError !== true && (typeof failHandler === 'function' || refreshOpts.throwOnError === false)) {
|
|
781
|
+
return {
|
|
782
|
+
ok: false,
|
|
783
|
+
error: err,
|
|
784
|
+
refreshed: [],
|
|
785
|
+
timings: { loadMs: 0, renderMs: 0 },
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
throw err;
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/**
|
|
793
|
+
* Retry the last failed fragment refresh without re-running any mutation.
|
|
794
|
+
*/
|
|
795
|
+
async function retryFailed() {
|
|
796
|
+
if (!lastFailedBatch || !lastFailedBatch.targets || lastFailedBatch.targets.length === 0) {
|
|
797
|
+
return { refreshed: [], skipped: true };
|
|
798
|
+
}
|
|
799
|
+
const { targets, chainIds } = lastFailedBatch;
|
|
800
|
+
lastFailedBatch = null;
|
|
801
|
+
|
|
802
|
+
// Bump versions to current + 1 for retry
|
|
803
|
+
const retryTargets = [];
|
|
804
|
+
for (const t of targets) {
|
|
805
|
+
const inst = instances.get(t.instanceId);
|
|
806
|
+
if (inst) {
|
|
807
|
+
inst.version += 1;
|
|
808
|
+
retryTargets.push({
|
|
809
|
+
...t,
|
|
810
|
+
input: { ...inst.input },
|
|
811
|
+
reqVersion: inst.version,
|
|
812
|
+
});
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
if (retryTargets.length === 0) {
|
|
817
|
+
return { refreshed: [], skipped: true };
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
return executeBatchRefresh(retryTargets, chainIds);
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
return {
|
|
824
|
+
syncDomInstances,
|
|
825
|
+
invalidate,
|
|
826
|
+
refresh,
|
|
827
|
+
refreshFragments(items = []) {
|
|
828
|
+
if (!Array.isArray(items) || items.length === 0) {
|
|
829
|
+
return Promise.resolve({ refreshed: [], skipped: true });
|
|
830
|
+
}
|
|
831
|
+
syncDomInstances();
|
|
832
|
+
for (const item of items) {
|
|
833
|
+
const key = item.instanceId || item.name;
|
|
834
|
+
const inst = instances.get(key) || Array.from(instances.values()).find((i) => i.name === key);
|
|
835
|
+
if (inst) {
|
|
836
|
+
if (item.input && typeof item.input === 'object') {
|
|
837
|
+
inst.input = { ...item.input };
|
|
838
|
+
if (inst.el && typeof inst.el.setAttribute === 'function') {
|
|
839
|
+
inst.el.setAttribute('data-w-fragment-input', JSON.stringify(inst.input));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
pendingTags.add(inst.name);
|
|
843
|
+
} else if (key) {
|
|
844
|
+
pendingTags.add(String(key).trim());
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
return flushInvalidations();
|
|
848
|
+
},
|
|
849
|
+
findFragmentsByTags(tags = []) {
|
|
850
|
+
syncDomInstances();
|
|
851
|
+
const tagSet = new Set((Array.isArray(tags) ? tags : [tags]).map((t) => String(t || '').trim()).filter(Boolean));
|
|
852
|
+
const matching = [];
|
|
853
|
+
for (const inst of instances.values()) {
|
|
854
|
+
for (const t of tagSet) {
|
|
855
|
+
if (inst.dependsOn.has(t) || inst.name === t) {
|
|
856
|
+
matching.push(inst);
|
|
857
|
+
break;
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
return deduplicateParentChildFragments(matching);
|
|
862
|
+
},
|
|
863
|
+
retryFailed,
|
|
864
|
+
retryLastFailed: retryFailed,
|
|
865
|
+
getInstance(instanceId) {
|
|
866
|
+
syncDomInstances();
|
|
867
|
+
return instances.get(instanceId) || null;
|
|
868
|
+
},
|
|
869
|
+
getInstances() {
|
|
870
|
+
syncDomInstances();
|
|
871
|
+
return Array.from(instances.values());
|
|
872
|
+
},
|
|
873
|
+
getStoredInput(instanceIdOrName, storageType = 'session') {
|
|
874
|
+
const store = storageType === 'local' ? defaultStorage.local : defaultStorage.session;
|
|
875
|
+
return store.get(`frag_input:${instanceIdOrName}`, null);
|
|
876
|
+
},
|
|
877
|
+
clearStoredInput(instanceIdOrName, storageType = 'session') {
|
|
878
|
+
const store = storageType === 'local' ? defaultStorage.local : defaultStorage.session;
|
|
879
|
+
return store.remove(`frag_input:${instanceIdOrName}`);
|
|
880
|
+
},
|
|
881
|
+
get hasFailedRefresh() {
|
|
882
|
+
return Boolean(lastFailedBatch);
|
|
883
|
+
},
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
module.exports = {
|
|
888
|
+
DEFAULT_FRAGMENT_ENDPOINT,
|
|
889
|
+
createFragmentCoordinator,
|
|
890
|
+
parseDependsOnAttr,
|
|
891
|
+
parseFragmentInputAttr,
|
|
892
|
+
deduplicateParentChildFragments,
|
|
893
|
+
};
|
|
894
|
+
|