@fgv/ts-web-extras 5.1.0-1 → 5.1.0-3
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/.rush/temp/61c1d4a91d98f048b475a5bb3e6541c5d27819de.tar.log +237 -0
- package/.rush/temp/chunked-rush-logs/ts-web-extras.build.chunks.jsonl +17 -37
- package/.rush/temp/operation/build/all.log +17 -37
- package/.rush/temp/operation/build/log-chunks.jsonl +17 -37
- package/.rush/temp/operation/build/state.json +1 -1
- package/dist/packlets/file-tree/httpTreeAccessors.js +68 -11
- package/dist/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/dist/test/unit/httpTreeAccessors.test.js +303 -74
- package/dist/test/unit/httpTreeAccessors.test.js.map +1 -1
- package/dist/ts-web-extras.d.ts +14 -0
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts +14 -0
- package/lib/packlets/file-tree/httpTreeAccessors.d.ts.map +1 -1
- package/lib/packlets/file-tree/httpTreeAccessors.js +68 -11
- package/lib/packlets/file-tree/httpTreeAccessors.js.map +1 -1
- package/lib/test/unit/httpTreeAccessors.test.js +303 -74
- package/lib/test/unit/httpTreeAccessors.test.js.map +1 -1
- package/package.json +24 -24
- package/rush-logs/ts-web-extras.build.cache.log +3 -0
- package/rush-logs/ts-web-extras.build.log +17 -37
- package/src/packlets/file-tree/httpTreeAccessors.ts +79 -12
- package/src/test/unit/httpTreeAccessors.test.ts +377 -84
- package/temp/build/typescript/ts_8nwakTlr.json +1 -1
- package/temp/coverage/crypto-utils/browserCryptoProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/crypto-utils/index.html +1 -1
- package/temp/coverage/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/file-tree/httpTreeAccessors.ts.html +369 -168
- package/temp/coverage/file-tree/index.html +11 -11
- package/temp/coverage/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/helpers/index.html +1 -1
- package/temp/coverage/index.html +11 -11
- package/temp/coverage/lcov-report/crypto-utils/browserCryptoProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/browserHashProvider.ts.html +1 -1
- package/temp/coverage/lcov-report/crypto-utils/index.html +1 -1
- package/temp/coverage/lcov-report/file-tree/directoryHandleStore.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileApiTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/fileSystemAccessTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/file-tree/httpTreeAccessors.ts.html +369 -168
- package/temp/coverage/lcov-report/file-tree/index.html +11 -11
- package/temp/coverage/lcov-report/file-tree/localStorageTreeAccessors.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/fileTreeHelpers.ts.html +1 -1
- package/temp/coverage/lcov-report/helpers/index.html +1 -1
- package/temp/coverage/lcov-report/index.html +11 -11
- package/temp/coverage/lcov-report/url-utils/index.html +1 -1
- package/temp/coverage/lcov-report/url-utils/urlParams.ts.html +1 -1
- package/temp/coverage/lcov.info +479 -379
- package/temp/coverage/url-utils/index.html +1 -1
- package/temp/coverage/url-utils/urlParams.ts.html +1 -1
- package/temp/test/jest/haste-map-7492f1b44480e0cdd1f220078fb3afd8-c8dd6c3430605adeb2f1cadf4f75e791-8c9336785555d572065b28c111982ba4 +0 -0
- package/temp/test/jest/perf-cache-7492f1b44480e0cdd1f220078fb3afd8-da39a3ee5e6b4b0d3255bfef95601890 +1 -0
- package/temp/ts-web-extras.api.json +1 -1
- package/.rush/temp/chunked-rush-logs/ts-web-extras.test.chunks.jsonl +0 -70
- package/.rush/temp/operation/build/error.log +0 -18
- package/.rush/temp/operation/test/all.log +0 -70
- package/.rush/temp/operation/test/error.log +0 -16
- package/.rush/temp/operation/test/log-chunks.jsonl +0 -70
- package/.rush/temp/operation/test/state.json +0 -3
- package/rush-logs/ts-web-extras.build.error.log +0 -18
- package/rush-logs/ts-web-extras.test.cache.log +0 -1
- package/rush-logs/ts-web-extras.test.error.log +0 -16
- package/rush-logs/ts-web-extras.test.log +0 -70
- package/temp/coverage/crypto/browserHashProvider.ts.html +0 -304
- package/temp/coverage/crypto/index.html +0 -116
- package/temp/coverage/lcov-report/crypto/browserHashProvider.ts.html +0 -304
- package/temp/coverage/lcov-report/crypto/index.html +0 -116
- package/temp/test/jest/haste-map-b931e4e63102f86c5bd4949f7dced44f-9d713eb41149188b4e5c0ae3d86d0a57-2ad8e16b24e391b8cdbe50b55c137169 +0 -0
- package/temp/test/jest/perf-cache-b931e4e63102f86c5bd4949f7dced44f-da39a3ee5e6b4b0d3255bfef95601890 +0 -1
- /package/temp/test/jest/{jest-transform-cache-b931e4e63102f86c5bd4949f7dced44f-79ef2876fae7ca75eedb2aa53dc48338/b5/package_b5f57afc9ec2c011239b1608ee5bdfa5 → jest-transform-cache-7492f1b44480e0cdd1f220078fb3afd8-79ef2876fae7ca75eedb2aa53dc48338/d6/package_d6e3b0fa94752e16b0b2a2777739b973} +0 -0
|
@@ -67,26 +67,47 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
67
67
|
}
|
|
68
68
|
/**
|
|
69
69
|
* Synchronizes all dirty files to the HTTP backend.
|
|
70
|
+
*
|
|
71
|
+
* Uses a concurrency guard: if a sync is already in progress, callers
|
|
72
|
+
* await the existing operation rather than starting a parallel one.
|
|
73
|
+
* This prevents the thundering herd that occurs when autoSync fires
|
|
74
|
+
* for every file written during a bulk operation (e.g. restore).
|
|
75
|
+
*
|
|
70
76
|
* @returns A promise that resolves to a result indicating success or failure.
|
|
71
77
|
*/
|
|
72
78
|
async syncToDisk() {
|
|
79
|
+
if (this._syncPromise) {
|
|
80
|
+
return this._syncPromise;
|
|
81
|
+
}
|
|
82
|
+
this._syncPromise = this._doSync().finally(() => {
|
|
83
|
+
this._syncPromise = undefined;
|
|
84
|
+
});
|
|
85
|
+
return this._syncPromise;
|
|
86
|
+
}
|
|
87
|
+
async _doSync() {
|
|
73
88
|
if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {
|
|
74
89
|
return succeed(undefined);
|
|
75
90
|
}
|
|
76
|
-
|
|
91
|
+
// Snapshot and clear dirty sets so that changes arriving during
|
|
92
|
+
// the async sync are not dropped when we finish.
|
|
93
|
+
const deletions = new Set(this._pendingDeletions);
|
|
94
|
+
const dirty = new Set(this._dirtyFiles);
|
|
95
|
+
this._pendingDeletions.clear();
|
|
96
|
+
this._dirtyFiles.clear();
|
|
97
|
+
for (const path of deletions) {
|
|
77
98
|
const query = new URLSearchParams();
|
|
78
99
|
query.set('path', path);
|
|
79
100
|
if (this._namespace) {
|
|
80
101
|
query.set('namespace', this._namespace);
|
|
81
102
|
}
|
|
82
|
-
const deleteResult = await this.
|
|
103
|
+
const deleteResult = await this._requestWithRetry(`/file?${query.toString()}`, {
|
|
83
104
|
method: 'DELETE'
|
|
84
105
|
});
|
|
85
106
|
if (deleteResult.isFailure()) {
|
|
86
107
|
return fail(`delete ${path}: ${deleteResult.message}`);
|
|
87
108
|
}
|
|
88
109
|
}
|
|
89
|
-
for (const path of
|
|
110
|
+
for (const path of dirty) {
|
|
90
111
|
const contentsResult = this.getFileContents(path);
|
|
91
112
|
if (contentsResult.isFailure()) {
|
|
92
113
|
return fail(`${path}: ${contentsResult.message}`);
|
|
@@ -98,7 +119,7 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
98
119
|
if (this._namespace) {
|
|
99
120
|
body.namespace = this._namespace;
|
|
100
121
|
}
|
|
101
|
-
const saveResult = await this.
|
|
122
|
+
const saveResult = await this._requestWithRetry('/file', {
|
|
102
123
|
method: 'PUT',
|
|
103
124
|
body: JSON.stringify(body)
|
|
104
125
|
});
|
|
@@ -106,13 +127,11 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
106
127
|
return fail(`sync ${path}: ${saveResult.message}`);
|
|
107
128
|
}
|
|
108
129
|
}
|
|
109
|
-
this._pendingDeletions.clear();
|
|
110
|
-
this._dirtyFiles.clear();
|
|
111
130
|
const syncBody = {};
|
|
112
131
|
if (this._namespace) {
|
|
113
132
|
syncBody.namespace = this._namespace;
|
|
114
133
|
}
|
|
115
|
-
const syncResult = await this.
|
|
134
|
+
const syncResult = await this._requestWithRetry('/sync', {
|
|
116
135
|
method: 'POST',
|
|
117
136
|
body: JSON.stringify(syncBody)
|
|
118
137
|
});
|
|
@@ -190,7 +209,10 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
190
209
|
return fail(message);
|
|
191
210
|
}
|
|
192
211
|
if (!response.ok) {
|
|
193
|
-
const
|
|
212
|
+
const body = await response.text().catch(() => '');
|
|
213
|
+
const message = body
|
|
214
|
+
? `HTTP ${response.status}: ${body}`
|
|
215
|
+
: `HTTP ${response.status} ${response.statusText}`;
|
|
194
216
|
return fail(message);
|
|
195
217
|
}
|
|
196
218
|
const json = await response.json().catch(() => undefined);
|
|
@@ -199,6 +221,39 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
199
221
|
}
|
|
200
222
|
return succeed(json);
|
|
201
223
|
}
|
|
224
|
+
/**
|
|
225
|
+
* Wraps `_request` with retry logic for transient failures
|
|
226
|
+
* (network errors, 503 service unavailable, etc.).
|
|
227
|
+
*/
|
|
228
|
+
async _requestWithRetry(resourcePath, init) {
|
|
229
|
+
var _a;
|
|
230
|
+
const maxAttempts = 3;
|
|
231
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
232
|
+
const result = await this._request(resourcePath, init);
|
|
233
|
+
if (result.isSuccess() || attempt === maxAttempts) {
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
// Retry on transient-looking errors
|
|
237
|
+
const msg = result.message;
|
|
238
|
+
const lowerMsg = msg.toLowerCase();
|
|
239
|
+
const isTransient = msg.includes('503') ||
|
|
240
|
+
msg.includes('502') ||
|
|
241
|
+
msg.includes('429') ||
|
|
242
|
+
lowerMsg.includes('disconnect') ||
|
|
243
|
+
lowerMsg.includes('econnreset') ||
|
|
244
|
+
lowerMsg.includes('failed to fetch') ||
|
|
245
|
+
lowerMsg.includes('network');
|
|
246
|
+
if (!isTransient) {
|
|
247
|
+
return result;
|
|
248
|
+
}
|
|
249
|
+
// Exponential backoff: 500ms, 1000ms
|
|
250
|
+
const delayMs = 500 * Math.pow(2, attempt - 1);
|
|
251
|
+
this._logger.detail(`Retrying ${(_a = init === null || init === void 0 ? void 0 : init.method) !== null && _a !== void 0 ? _a : 'GET'} ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`);
|
|
252
|
+
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
253
|
+
}
|
|
254
|
+
/* c8 ignore next 1 - defensive coding: loop always returns */
|
|
255
|
+
return fail('retry loop exited unexpectedly');
|
|
256
|
+
}
|
|
202
257
|
/**
|
|
203
258
|
* Loads files from the HTTP backend for the specified directory path.
|
|
204
259
|
* @param params - Configuration parameters for the HTTP tree accessors.
|
|
@@ -256,8 +311,7 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
256
311
|
}
|
|
257
312
|
}
|
|
258
313
|
const fetchImpl = normalizeFetch(params.fetchImpl);
|
|
259
|
-
/* c8 ignore next
|
|
260
|
-
const userIdHeaders = params.userId
|
|
314
|
+
const userIdHeaders = /* c8 ignore next */ params.userId
|
|
261
315
|
? { headers: { 'X-User-Id': params.userId } }
|
|
262
316
|
: undefined;
|
|
263
317
|
const response = await fetchImpl(`${params.baseUrl.replace(/\/$/, '')}${resourcePath}?${search.toString()}`, userIdHeaders).catch((err) => ({ err }));
|
|
@@ -266,7 +320,10 @@ export class HttpTreeAccessors extends FileTree.InMemoryTreeAccessors {
|
|
|
266
320
|
return fail(message);
|
|
267
321
|
}
|
|
268
322
|
if (!response.ok) {
|
|
269
|
-
const
|
|
323
|
+
const body = await response.text().catch(() => '');
|
|
324
|
+
const message = body
|
|
325
|
+
? `HTTP ${response.status}: ${body}`
|
|
326
|
+
: `HTTP ${response.status} ${response.statusText}`;
|
|
270
327
|
return fail(message);
|
|
271
328
|
}
|
|
272
329
|
const json = await response.json().catch(() => undefined);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAe,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACvG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAuB7C,SAAS,cAAc,CAAC,SAAwB;IAC9C,MAAM,QAAQ,GAAG,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAiB,CAAC;AACnD,CAAC;AAeD;;;GAGG;AACH,MAAM,OAAO,iBACX,SAAQ,QAAQ,CAAC,qBAA0B;IAY3C,YAAoB,KAAoC,EAAE,MAA4B;;QACpF,KAAK,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;QAPN,gBAAW,GAAgB,IAAI,GAAG,EAAE,CAAC;QACrC,sBAAiB,GAAgB,IAAI,GAAG,EAAE,CAAC;QAO1D,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC;QAClD,IAAI,CAAC,UAAU,GAAG,MAAM,CAAC,SAAS,CAAC;QACnC,IAAI,CAAC,UAAU,GAAG,cAAc,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;QACnD,IAAI,CAAC,SAA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,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,OAAO,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,QAAQ,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;YAC7E,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,OAAO,CAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {\n return succeed(undefined);\n }\n\n for (const path of this._pendingDeletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._request<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of this._dirtyFiles) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._request<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._request<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n return syncResult.isFailure() ? fail(syncResult.message) : succeed(undefined);\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const message = await response.text().catch(() => `HTTP ${response.status}`);\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n /* c8 ignore next 3 - userId header in static _requestWithParams; covered by userId tests via fromHttp */\n const userIdHeaders: RequestInit | undefined = params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const message = await response.text().catch(() => `HTTP ${response.status}`);\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"httpTreeAccessors.js","sourceRoot":"","sources":["../../../src/packlets/file-tree/httpTreeAccessors.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;GAoBG;AAEH,OAAO,EAAkB,IAAI,EAAe,OAAO,EAAE,iBAAiB,EAAE,OAAO,EAAE,MAAM,eAAe,CAAC;AACvG,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAC;AAuB7C,SAAS,cAAc,CAAC,SAAwB;IAC9C,MAAM,QAAQ,GAAG,SAAS,aAAT,SAAS,cAAT,SAAS,GAAI,UAAU,CAAC,KAAK,CAAC;IAC/C,OAAO,QAAQ,CAAC,IAAI,CAAC,UAAU,CAAiB,CAAC;AACnD,CAAC;AAeD;;;GAGG;A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C,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC5F,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,IAAI,CAAC,QAAQ,CAAC,EAAE,EAAE,CAAC;YACjB,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,EAAE,CAAC,CAAC;YACnD,MAAM,OAAO,GAAG,IAAI;gBAClB,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,KAAK,IAAI,EAAE;gBACpC,CAAC,CAAC,QAAQ,QAAQ,CAAC,MAAM,IAAI,QAAQ,CAAC,UAAU,EAAE,CAAC;YACrD,OAAO,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QAED,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;QAC1D,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YACvB,OAAO,IAAI,CAAC,uBAAuB,CAAC,CAAC;QACvC,CAAC;QAED,OAAO,OAAO,CAAC,IAAS,CAAC,CAAC;IAC5B,CAAC;CACF","sourcesContent":["/*\n * Copyright (c) 2026 Erik Fortune\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all\n * copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n */\n\nimport { DetailedResult, fail, type Result, succeed, succeedWithDetail, Logging } from '@fgv/ts-utils';\nimport { FileTree } from '@fgv/ts-json-base';\n\ninterface IHttpStorageTreeItem {\n readonly path: string;\n readonly name: string;\n readonly type: 'file' | 'directory';\n}\n\ninterface IHttpStorageTreeChildrenResponse {\n readonly path: string;\n readonly children: ReadonlyArray<IHttpStorageTreeItem>;\n}\n\ninterface IHttpStorageFileResponse {\n readonly path: string;\n readonly contents: string;\n readonly contentType?: string;\n}\n\ninterface IHttpStorageSyncResponse {\n readonly synced: number;\n}\n\nfunction normalizeFetch(fetchImpl?: typeof fetch): typeof fetch {\n const resolved = fetchImpl ?? globalThis.fetch;\n return resolved.bind(globalThis) as typeof fetch;\n}\n\n/**\n * Configuration for creating HTTP-backed tree accessors.\n * @public\n */\nexport interface IHttpTreeParams<TCT extends string = string> extends FileTree.IFileTreeInitParams<TCT> {\n readonly baseUrl: string;\n readonly namespace?: string;\n readonly autoSync?: boolean;\n readonly fetchImpl?: typeof fetch;\n readonly userId?: string;\n readonly logger?: Logging.LogReporter<unknown>;\n}\n\n/**\n * HTTP-backed file tree accessors that cache data in memory and persist via REST API.\n * @public\n */\nexport class HttpTreeAccessors<TCT extends string = string>\n extends FileTree.InMemoryTreeAccessors<TCT>\n implements FileTree.IPersistentFileTreeAccessors<TCT>\n{\n private readonly _baseUrl: string;\n private readonly _namespace: string | undefined;\n private readonly _fetchImpl: typeof fetch;\n private readonly _dirtyFiles: Set<string> = new Set();\n private readonly _pendingDeletions: Set<string> = new Set();\n private readonly _autoSync: boolean;\n private readonly _userId: string | undefined;\n private readonly _logger: Logging.LogReporter<unknown>;\n\n /** Guards against concurrent syncToDisk calls (thundering herd from autoSync). */\n private _syncPromise: Promise<Result<void>> | undefined;\n\n private constructor(files: FileTree.IInMemoryFile<TCT>[], params: IHttpTreeParams<TCT>) {\n super(files, params);\n this._baseUrl = params.baseUrl.replace(/\\/$/, '');\n this._namespace = params.namespace;\n this._fetchImpl = normalizeFetch(params.fetchImpl);\n this._autoSync = params.autoSync ?? false;\n this._userId = params.userId;\n this._logger = params.logger ?? new Logging.LogReporter<unknown>();\n }\n\n private async _runAutoSyncTask(path: string): Promise<void> {\n try {\n const result = await this.syncToDisk();\n if (result.isFailure()) {\n this._logger.error(`Auto-sync failed for ${path}: ${result.message}`);\n }\n } catch (err) {\n this._logger.error(`Auto-sync threw for ${path}: ${String(err)}`);\n }\n }\n\n /**\n * Creates a new HttpTreeAccessors instance from an HTTP backend.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @returns A promise that resolves to a result containing the new HttpTreeAccessors instance or an error message.\n */\n public static async fromHttp<TCT extends string = string>(\n params: IHttpTreeParams<TCT>\n ): Promise<Result<HttpTreeAccessors<TCT>>> {\n const filesResult = await this._loadFiles<TCT>(params, '/');\n if (filesResult.isFailure()) {\n return fail(filesResult.message);\n }\n return succeed(new HttpTreeAccessors<TCT>(filesResult.value, params));\n }\n\n /**\n * Synchronizes all dirty files to the HTTP backend.\n *\n * Uses a concurrency guard: if a sync is already in progress, callers\n * await the existing operation rather than starting a parallel one.\n * This prevents the thundering herd that occurs when autoSync fires\n * for every file written during a bulk operation (e.g. restore).\n *\n * @returns A promise that resolves to a result indicating success or failure.\n */\n public async syncToDisk(): Promise<Result<void>> {\n if (this._syncPromise) {\n return this._syncPromise;\n }\n\n this._syncPromise = this._doSync().finally(() => {\n this._syncPromise = undefined;\n });\n return this._syncPromise;\n }\n\n private async _doSync(): Promise<Result<void>> {\n if (this._dirtyFiles.size === 0 && this._pendingDeletions.size === 0) {\n return succeed(undefined);\n }\n\n // Snapshot and clear dirty sets so that changes arriving during\n // the async sync are not dropped when we finish.\n const deletions = new Set(this._pendingDeletions);\n const dirty = new Set(this._dirtyFiles);\n this._pendingDeletions.clear();\n this._dirtyFiles.clear();\n\n for (const path of deletions) {\n const query = new URLSearchParams();\n query.set('path', path);\n if (this._namespace) {\n query.set('namespace', this._namespace);\n }\n\n const deleteResult = await this._requestWithRetry<{ deleted: boolean }>(`/file?${query.toString()}`, {\n method: 'DELETE'\n });\n if (deleteResult.isFailure()) {\n return fail(`delete ${path}: ${deleteResult.message}`);\n }\n }\n\n for (const path of dirty) {\n const contentsResult = this.getFileContents(path);\n if (contentsResult.isFailure()) {\n return fail(`${path}: ${contentsResult.message}`);\n }\n\n const body: Record<string, unknown> = {\n path,\n contents: contentsResult.value\n };\n if (this._namespace) {\n body.namespace = this._namespace;\n }\n\n const saveResult = await this._requestWithRetry<IHttpStorageFileResponse>('/file', {\n method: 'PUT',\n body: JSON.stringify(body)\n });\n if (saveResult.isFailure()) {\n return fail(`sync ${path}: ${saveResult.message}`);\n }\n }\n\n const syncBody: Record<string, unknown> = {};\n if (this._namespace) {\n syncBody.namespace = this._namespace;\n }\n\n const syncResult = await this._requestWithRetry<IHttpStorageSyncResponse>('/sync', {\n method: 'POST',\n body: JSON.stringify(syncBody)\n });\n\n return syncResult.isFailure() ? fail(syncResult.message) : succeed(undefined);\n }\n\n /**\n * Checks if there are any dirty files that need synchronization.\n * @returns True if there are dirty files, false otherwise.\n */\n public isDirty(): boolean {\n return this._dirtyFiles.size > 0 || this._pendingDeletions.size > 0;\n }\n\n /**\n * Gets the list of paths for all dirty files.\n * @returns An array of file paths that have been modified but not yet synchronized.\n */\n public getDirtyPaths(): string[] {\n return [...Array.from(this._dirtyFiles), ...Array.from(this._pendingDeletions)];\n }\n\n public deleteFile(path: string): Result<boolean> {\n const result = super.deleteFile(path);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.delete(path);\n this._pendingDeletions.add(path);\n\n if (!this._autoSync) {\n return result;\n }\n\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Saves file contents and marks the file as dirty for synchronization.\n * @param path - The path to the file.\n * @param contents - The new contents of the file.\n * @returns A result indicating success or failure.\n */\n public saveFileContents(path: string, contents: string): Result<string> {\n const result = super.saveFileContents(path, contents);\n if (result.isFailure()) {\n return result;\n }\n\n this._dirtyFiles.add(path);\n if (!this._autoSync) {\n return result;\n }\n\n // fire-and-log-on-failure automatic sync for immediate persistence workflow\n void this._runAutoSyncTask(path);\n return result;\n }\n\n /**\n * Checks if a file is mutable (can be modified).\n * @param path - The path to the file.\n * @returns A detailed result indicating if the file is mutable and the reason.\n */\n public fileIsMutable(path: string): DetailedResult<boolean, FileTree.SaveDetail> {\n const result = super.fileIsMutable(path);\n if (result.isSuccess() && result.value === true) {\n return succeedWithDetail(true, 'persistent');\n }\n return result;\n }\n\n /**\n * Makes an HTTP request to the specified resource path.\n * @param resourcePath - The path to the resource.\n * @param init - Optional request initialization options.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private async _request<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const response = await this._fetchImpl(`${this._baseUrl}${resourcePath}`, {\n headers: {\n 'Content-Type': 'application/json',\n ...(this._userId ? { 'X-User-Id': this._userId } : {}),\n /* c8 ignore next 1 - defensive coding: init.headers is never set by current callers */\n ...(init?.headers ?? {})\n },\n ...init\n }).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n return succeed(json as T);\n }\n\n /**\n * Wraps `_request` with retry logic for transient failures\n * (network errors, 503 service unavailable, etc.).\n */\n private async _requestWithRetry<T>(resourcePath: string, init?: RequestInit): Promise<Result<T>> {\n const maxAttempts = 3;\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n const result = await this._request<T>(resourcePath, init);\n if (result.isSuccess() || attempt === maxAttempts) {\n return result;\n }\n // Retry on transient-looking errors\n const msg = result.message;\n const lowerMsg = msg.toLowerCase();\n const isTransient =\n msg.includes('503') ||\n msg.includes('502') ||\n msg.includes('429') ||\n lowerMsg.includes('disconnect') ||\n lowerMsg.includes('econnreset') ||\n lowerMsg.includes('failed to fetch') ||\n lowerMsg.includes('network');\n if (!isTransient) {\n return result;\n }\n // Exponential backoff: 500ms, 1000ms\n const delayMs = 500 * Math.pow(2, attempt - 1);\n this._logger.detail(\n `Retrying ${\n init?.method ?? 'GET'\n } ${resourcePath} after ${delayMs}ms (attempt ${attempt}/${maxAttempts})`\n );\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n }\n /* c8 ignore next 1 - defensive coding: loop always returns */\n return fail('retry loop exited unexpectedly');\n }\n\n /**\n * Loads files from the HTTP backend for the specified directory path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param directoryPath - The path to the directory to load files from.\n * @returns A promise that resolves to a result containing the loaded files or an error message.\n */\n private static async _loadFiles<TCT extends string = string>(\n params: IHttpTreeParams<TCT>,\n directoryPath: string\n ): Promise<Result<FileTree.IInMemoryFile<TCT>[]>> {\n const childrenResult = await this._requestWithParams<IHttpStorageTreeChildrenResponse>(\n params,\n '/tree/children',\n {\n path: directoryPath,\n namespace: params.namespace\n }\n );\n if (childrenResult.isFailure()) {\n return fail(childrenResult.message);\n }\n\n const allFiles: FileTree.IInMemoryFile<TCT>[] = [];\n\n for (const item of childrenResult.value.children) {\n if (item.type === 'directory') {\n const nestedResult = await this._loadFiles(params, item.path);\n if (nestedResult.isFailure()) {\n return fail(nestedResult.message);\n }\n allFiles.push(...nestedResult.value);\n } else {\n const fileResult = await this._requestWithParams<IHttpStorageFileResponse>(params, '/file', {\n path: item.path,\n namespace: params.namespace\n });\n if (fileResult.isFailure()) {\n return fail(fileResult.message);\n }\n\n const contentType = params.inferContentType?.(item.path, fileResult.value.contentType).orDefault();\n allFiles.push({\n path: item.path,\n contents: fileResult.value.contents,\n contentType\n });\n }\n }\n\n return succeed(allFiles);\n }\n\n /**\n * Makes an HTTP request with query parameters to the specified resource path.\n * @param params - Configuration parameters for the HTTP tree accessors.\n * @param resourcePath - The path to the resource.\n * @param query - Query parameters to include in the request.\n * @returns A promise that resolves to a result containing the response data or an error message.\n */\n private static async _requestWithParams<T>(\n params: IHttpTreeParams,\n resourcePath: string,\n query: Record<string, string | undefined>\n ): Promise<Result<T>> {\n const search = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value !== undefined) {\n search.set(key, value);\n }\n }\n\n const fetchImpl = normalizeFetch(params.fetchImpl);\n const userIdHeaders: RequestInit | undefined = /* c8 ignore next */ params.userId\n ? { headers: { 'X-User-Id': params.userId } }\n : undefined;\n const response = await fetchImpl(\n `${params.baseUrl.replace(/\\/$/, '')}${resourcePath}?${search.toString()}`,\n userIdHeaders\n ).catch((err: unknown) => ({ err } as const));\n\n if ('err' in response) {\n const message = response.err instanceof Error ? response.err.message : String(response.err);\n return fail(message);\n }\n\n if (!response.ok) {\n const body = await response.text().catch(() => '');\n const message = body\n ? `HTTP ${response.status}: ${body}`\n : `HTTP ${response.status} ${response.statusText}`;\n return fail(message);\n }\n\n const json = await response.json().catch(() => undefined);\n if (json === undefined) {\n return fail('invalid JSON response');\n }\n\n return succeed(json as T);\n }\n}\n"]}
|