@wcstack/fetch 4.23.0 → 4.24.0

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/README.ja.md CHANGED
@@ -259,23 +259,36 @@ get fieldErrors() {
259
259
 
260
260
  ### 5. `<wcs-infinite-scroll>` による無限スクロール
261
261
 
262
- `<wcs-infinite-scroll>` は、sentinel 要素が表示領域に入ったときに既存の `<wcs-fetch>` を実行します。
263
- ページ番号、次の URL、レスポンスの append などは `@wcstack/state` 側で宣言し、スクロール検知だけをこのタグに任せます。
264
-
265
- 動作規約:
266
-
267
- - target の `<wcs-fetch>` が `loading` 中なら重複起動しません
268
- - `once` は厳密な一回限りです。一度発火した後は属性を変更しても再監視しません
269
- - `target` の id が未解決、または対象が `<wcs-fetch>` でない場合は何も読み込まず、`target` の値ごとに 1 回 `[wcs/infinite-scroll-target]` で警告します
262
+ `<wcs-infinite-scroll>` は一覧の後ろに置く番兵(sentinel)です。画面に入ったときに、既存の `<wcs-fetch>` を実行します。
263
+ ページ番号、次の URL、レスポンスの append などは `@wcstack/state` 側で宣言し、「次のページをいつ取りに行くか」をこのタグに任せます。
270
264
 
271
265
  ```html
266
+ <style>
267
+ /* 番兵は、監視されるために自分の箱を持つ必要があります */
268
+ wcs-infinite-scroll { display: block; min-height: 1px; }
269
+ </style>
270
+
272
271
  <wcs-state>
273
272
  <script type="module">
274
273
  export default {
275
- page: 1,
274
+ pageSize: 20,
275
+ page: 1, // 次に取りに行くページ
276
276
  users: [],
277
+ noMore: false,
278
+ listLoading: false,
279
+ listError: null,
280
+ $eventTokens: ["pageArrived"],
277
281
  get nextUsersUrl() {
278
- return "/api/users?page=" + this.page;
282
+ return "/api/users?page=" + this.page + "&limit=" + this.pageSize;
283
+ },
284
+ $on: {
285
+ pageArrived(state, event) {
286
+ const { status, value } = event.detail;
287
+ if (status < 200 || status >= 300) return; // 失敗: ページ番号はそのまま
288
+ state.users = state.users.concat(value);
289
+ state.page = state.page + 1;
290
+ if (value.length < state.pageSize) state.noMore = true; // 短いページが最後
291
+ },
279
292
  },
280
293
  };
281
294
  </script>
@@ -284,7 +297,7 @@ get fieldErrors() {
284
297
  <wcs-fetch
285
298
  id="next-page-fetch"
286
299
  manual
287
- data-wcs="url: nextUsersUrl; loading: listLoading; error: listError">
300
+ data-wcs="url: nextUsersUrl; loading: listLoading; error: listError; eventToken.value: pageArrived">
288
301
  </wcs-fetch>
289
302
 
290
303
  <ul>
@@ -295,16 +308,42 @@ get fieldErrors() {
295
308
 
296
309
  <wcs-infinite-scroll
297
310
  target="next-page-fetch"
298
- root-margin="240px 0px">
311
+ root-margin="240px 0px"
312
+ data-wcs="disabled: noMore">
299
313
  </wcs-infinite-scroll>
300
314
  ```
301
315
 
316
+ 動作規約:
317
+
318
+ - 番兵が画面に入ると、target の要求を実行します。最後に実行した `url` と同じでも実行します: 利用者がスクロールで離れて戻れば、失敗した要求をもう一度試せます。
319
+ - target の `<wcs-fetch>` が `loading` 中なら実行しません。
320
+ - **番兵が画面に残っている間は、次の要求を自分で実行します**(4.24 から):
321
+ - 要求が飛んでいないときに target の `url` が書かれた・変わったとき —— 最初のページ(番兵はふつう、state が `url` を書くより先に報告します)と、一覧を空にする絞り込み
322
+ - 要求が終わり、その間に `url` が変わっていたとき —— 読み込み中に打たれた絞り込み。または、応答なしで終わり(中断)、`url` が別のものになっているとき
323
+ - 要求が終わり、ページが行を足して `url` を進めたとき —— 背の高いウィンドウ、縮小表示、短いページ: 番兵が画面の外へ出るまで続けます
324
+
325
+ そこから同じ `url` をもう一度実行することはないので、失敗した要求は繰り返しません: 利用者がスクロールで離れて戻るか、ページ側の再試行(`trigger`)を待ちます。また、行を 1 つも足さなかった応答でそこで終わります(ページが `url` をどう変えても)—— 空の応答でページ番号を進めるページが、いつまでも取りに行くことはありません。4.23 までは、番兵が画面に入ったときにしか動きませんでした: 最初のページが読み込まれないことが多く(番兵が、state が `url` を書くより先に報告し、要求は `[wcs/command-not-ready]` で断られました)、番兵を画面に残したページが最後のページになりました。
326
+ - **target の `url` は、上のように state から書いてください。** 1 ページ目の URL を静的な属性で書くと、state が要素をバインドする前に最初の要求が始まり、その応答が `eventToken.value` のハンドラより先に届くことがあります(Firefox)。
327
+ - **絞り込みが変わったら、取りに行っているページを中断します。** `manual` の `<wcs-fetch>` は、`url` が変わっても飛んでいる要求を中断しません: 前の絞り込みで頼んだページは届き、その行が新しい一覧に入ります。`<wcs-fetch>` に `command.abort: $command.cancelPage` を束ね、絞り込みを変えるハンドラの最初で emit してから(コマンドはその場で走ります)、一覧を空にしてページ番号を戻してください —— 新しい一覧の最初のページは、要素が取りに行きます:
328
+
329
+ ```javascript
330
+ setFilter(event) {
331
+ this.$command.cancelPage.emit(); // 取りに行っているページは、前の一覧のもの
332
+ this.filter = event.target.value;
333
+ this.users = [];
334
+ this.page = 1;
335
+ this.noMore = false;
336
+ },
337
+ ```
338
+ - `once` は厳密な一回限りです。一度発火した後は属性を変更しても再監視しません
339
+ - `target` の id が未解決、または対象が `<wcs-fetch>` でない場合は何も読み込まず、`target` の値ごとに 1 回 `[wcs/infinite-scroll-target]` で警告します
340
+
302
341
  主な属性:
303
342
 
304
343
  - `target`: 実行する `<wcs-fetch>` の `id`
305
- - `root`: スクロールコンテナの `id`。未指定時は viewport
306
- - `root-margin`: 先読み距離。`IntersectionObserver` の `rootMargin`
307
- - `threshold`: 交差しきい値。未指定時は `0`
344
+ - `root`: スクロールコンテナ。その `id`、または(4.24 から)`<wcs-intersect root>` と同じくセレクタ。未指定時は viewport。4.24 から、見つからない root と、スクロールしない root(`overflow: visible` —— 中にあるものがすべて画面内として数えられ、ページが次々に読み込まれます)は、値ごとに 1 回 `[wcs/infinite-scroll-root]` で警告します。それまでは、見つからない root の代わりに黙って viewport が使われました
345
+ - `root-margin`: 先読み距離。`IntersectionObserver` の `rootMargin` に渡します: 長さはそれぞれ `px` か `%` 付きで書きます。単位の無い長さ(`200`、`0 0 900 0`。`0` だけでも)はブラウザが拒み、何も読み込まれません: 4.24 から、要素が `[wcs/root-margin-unit]`(lint と同じ code)で警告します。それまでは、ブラウザの例外が要素から捕まえられずに出ました
346
+ - `threshold`: 交差しきい値(`0` 〜 `1`)。未指定時は `0`
308
347
  - `disabled`: 監視を停止
309
348
  - `once`: 最初の実行後に監視を解除し、その後は再武装しない
310
349
 
@@ -344,6 +383,28 @@ HTML、JS、または `@wcstack/state` バインディングからリクエス
344
383
 
345
384
  **`null` と `undefined`。** 属性に対応する入力(`url`・`method`・`target`・`manual`・`responseType`)は、`null` を「クリア」として扱います。属性を外し、入力は既定値に戻ります。`undefined` は「値が無い」で、属性を最初の書き込みの前の状態 — マークアップに書かれた値、無ければ属性なし — に戻します。どちらも文字列 `"null"` / `"undefined"` として書くことはありません(`@wcstack/state` は `undefined` を書きませんが、React 19 は値のあった prop を外したときに書き、直接の代入でも届きます)。`body` はどちらも「JS の body なし」、`trigger` はどちらも無視します。
346
385
 
386
+ ### コマンドに url を渡す
387
+
388
+ `fetch(url, init)` は、渡されたもので要求を 1 回実行し、要素の属性は変えません。コマンドトークンが運ぶのがこれです(4.24 から):
389
+
390
+ ```html
391
+ <wcs-fetch manual data-wcs="command.fetch: $command.loadUsers; value: users"></wcs-fetch>
392
+ ```
393
+
394
+ ```javascript
395
+ loadPage(event, page) {
396
+ this.$command.loadUsers.emit("/api/users?page=" + page);
397
+ },
398
+ save() {
399
+ this.$command.saveUser.emit("/api/users/" + this.user.id, { method: "PUT", body: this.user });
400
+ },
401
+ ```
402
+
403
+ - `url` はその要求のものです。渡さないとき、または文字列でないものがその位置にあるとき(`onclick: $command.x` のバインディングが先頭に渡すイベントなど)は、要素自身の `url` を取りに行き、`init` は無視します。
404
+ - `init.method` は要素の `method` の代わりになり、`init.headers` は `<wcs-fetch-header>` のヘッダに足され(同じ名前は置き換え)、`init.body` は要素の `body` の代わりに送られます。そのとき要素の `body` は次の要求まで残ります。
405
+ - **なぜあるのか。** コマンドは、同じ更新のバインディングより先に走ります。`url: pageUrl; command.fetch: $command.load` と書き、ハンドラが `pageUrl` の読む値を変えて同時に `load` を emit すると、変更**前**の url を取りに行きます —— 一覧が 1 ページ遅れ、何も知らせません。url をコマンドに渡すか、`url` を先に書いて `trigger` で実行してください(バインディングは書いた順に適用されます)。4.23 までの `fetch()` は引数を無視しました。
406
+ - こうして渡した url は「最後に取りに行った url」として数えます: その後で同じ url を要素に書くバインディングが、もう一度取りに行くことはありません。
407
+
347
408
  ## `:state()` による CSS スタイリング
348
409
 
349
410
  `<wcs-fetch>` は 2 つの boolean 出力ステートを
@@ -602,7 +663,7 @@ wcstack アプリケーションでは、**`trigger` によるステート駆動
602
663
 
603
664
  | メソッド | 説明 |
604
665
  |----------|------|
605
- | `fetch()` | HTTP リクエストを実行 |
666
+ | `fetch(url?, init?)` | HTTP リクエストを実行。引数なしなら要素自身の要求。4.24 から、`url` と `init`(`{ method?, headers?, body? }`)はその要求だけのもの —— [コマンドに url を渡す](#コマンドに-url-を渡す) |
606
667
  | `abort()` | 実行中のリクエストをキャンセル |
607
668
 
608
669
  ### `<wcs-fetch-header>`
package/README.md CHANGED
@@ -261,23 +261,36 @@ and bind `textContent: fieldErrors.name` next to the field. `error` goes back to
261
261
 
262
262
  ### 5. Infinite scroll with `<wcs-infinite-scroll>`
263
263
 
264
- `<wcs-infinite-scroll>` runs an existing `<wcs-fetch>` when its sentinel element enters the viewport.
265
- Keep page numbers, next URLs, and response append behavior in `@wcstack/state`; this tag only owns scroll detection.
266
-
267
- Behavior rules:
268
-
269
- - it does not trigger again while the target `<wcs-fetch>` is `loading`
270
- - `once` is strict: after the first execution, changing attributes does not re-arm observation
271
- - if `target` does not resolve, or resolves to a non-`<wcs-fetch>` element, nothing is loaded, and it warns `[wcs/infinite-scroll-target]` once per `target` value
264
+ `<wcs-infinite-scroll>` is a sentinel placed after a list: it runs an existing `<wcs-fetch>` when it comes on screen.
265
+ Keep page numbers, next URLs, and response append behavior in `@wcstack/state`; this tag owns when the next page is asked for.
272
266
 
273
267
  ```html
268
+ <style>
269
+ /* the sentinel needs a box of its own to be observed */
270
+ wcs-infinite-scroll { display: block; min-height: 1px; }
271
+ </style>
272
+
274
273
  <wcs-state>
275
274
  <script type="module">
276
275
  export default {
277
- page: 1,
276
+ pageSize: 20,
277
+ page: 1, // the next page to ask for
278
278
  users: [],
279
+ noMore: false,
280
+ listLoading: false,
281
+ listError: null,
282
+ $eventTokens: ["pageArrived"],
279
283
  get nextUsersUrl() {
280
- return "/api/users?page=" + this.page;
284
+ return "/api/users?page=" + this.page + "&limit=" + this.pageSize;
285
+ },
286
+ $on: {
287
+ pageArrived(state, event) {
288
+ const { status, value } = event.detail;
289
+ if (status < 200 || status >= 300) return; // a failure: the page number stays where it is
290
+ state.users = state.users.concat(value);
291
+ state.page = state.page + 1;
292
+ if (value.length < state.pageSize) state.noMore = true; // a short page is the last one
293
+ },
281
294
  },
282
295
  };
283
296
  </script>
@@ -286,7 +299,7 @@ Behavior rules:
286
299
  <wcs-fetch
287
300
  id="next-page-fetch"
288
301
  manual
289
- data-wcs="url: nextUsersUrl; loading: listLoading; error: listError">
302
+ data-wcs="url: nextUsersUrl; loading: listLoading; error: listError; eventToken.value: pageArrived">
290
303
  </wcs-fetch>
291
304
 
292
305
  <ul>
@@ -297,16 +310,42 @@ Behavior rules:
297
310
 
298
311
  <wcs-infinite-scroll
299
312
  target="next-page-fetch"
300
- root-margin="240px 0px">
313
+ root-margin="240px 0px"
314
+ data-wcs="disabled: noMore">
301
315
  </wcs-infinite-scroll>
302
316
  ```
303
317
 
318
+ Behavior rules:
319
+
320
+ - The sentinel coming on screen runs the target's request — also for the `url` it ran last: a user who scrolls away and back tries a failed request again.
321
+ - It does not run a request while the target `<wcs-fetch>` is `loading`.
322
+ - **With the sentinel still on screen, it runs the next request by itself** (since 4.24):
323
+ - when the target's `url` is written or changed while no request is in flight — the first page (the sentinel usually reports before state has written `url`) and a filter that empties the list;
324
+ - when a request ends and the `url` changed while it was in flight — a filter typed meanwhile — or it ended with no answer (aborted) and the `url` is another one;
325
+ - when a request ends, the page has added rows and moved the `url` on — a tall window, a zoomed-out page, a short page: it goes on until the sentinel is off screen.
326
+
327
+ It never runs a `url` again from there, so a failed request is not repeated: it waits for the user to scroll away and back, or for your retry (`trigger`). And a response that added no row ends it, whatever the page does to the `url` — a page that counts its page number up on an empty answer does not ask for ever. Up to 4.23 the element acted only on the sentinel coming on screen: the first page was often never loaded (the sentinel reported before state had written `url`, and the request was refused with `[wcs/command-not-ready]`), and a page that left the sentinel on screen was the last one.
328
+ - **Write the target's `url` from state**, as above, not as a static attribute for page 1: a static `url` lets the first request start before state has bound the element, and its answer can arrive before your `eventToken.value` handler is attached (Firefox).
329
+ - **When a filter changes, abort the page on its way.** A `manual` `<wcs-fetch>` does not abort on a new `url`: a page asked for the old filter still arrives, and its rows land in the new list. Bind `command.abort: $command.cancelPage` on the `<wcs-fetch>` and emit it first in the handler that changes the filter (a command runs at once), then empty the list and reset the page number — the element asks for the new list's first page:
330
+
331
+ ```javascript
332
+ setFilter(event) {
333
+ this.$command.cancelPage.emit(); // the page on its way is another list's
334
+ this.filter = event.target.value;
335
+ this.users = [];
336
+ this.page = 1;
337
+ this.noMore = false;
338
+ },
339
+ ```
340
+ - `once` is strict: after the first execution, changing attributes does not re-arm observation
341
+ - if `target` does not resolve, or resolves to a non-`<wcs-fetch>` element, nothing is loaded, and it warns `[wcs/infinite-scroll-target]` once per `target` value
342
+
304
343
  Attributes:
305
344
 
306
345
  - `target`: `id` of the `<wcs-fetch>` to run
307
- - `root`: `id` of the scroll container. Defaults to the viewport
308
- - `root-margin`: preload distance. Passed to `IntersectionObserver.rootMargin`
309
- - `threshold`: intersection threshold. Defaults to `0`
346
+ - `root`: the scroll container — its `id`, or (since 4.24) a selector, as `<wcs-intersect root>` takes. Defaults to the viewport. Since 4.24, a root that is not found, or one that does not scroll (`overflow: visible` — everything inside it counts as on screen, and page after page is loaded), warns `[wcs/infinite-scroll-root]` once per value; before, the viewport took the place of a root that was not found without a word
347
+ - `root-margin`: preload distance. Passed to `IntersectionObserver.rootMargin`: each length with `px` or `%`. A length with no unit (`200`, `0 0 900 0` — a bare `0` too) is refused by the browser and nothing is loaded: since 4.24 the element warns `[wcs/root-margin-unit]` (the lint's code); before, the browser's exception came out of the element uncaught
348
+ - `threshold`: intersection threshold, `0` to `1`. Defaults to `0`
310
349
  - `disabled`: stops observing
311
350
  - `once`: disconnects after the first execution and does not re-arm afterwards
312
351
 
@@ -347,6 +386,28 @@ These properties control request execution from HTML, JS, or `@wcstack/state` bi
347
386
 
348
387
  **`null` and `undefined`.** The inputs backed by an attribute (`url`, `method`, `target`, `manual`, `responseType`) take `null` as "clear": the attribute is removed and the input falls back to its default. `undefined` means "no value supplied": the attribute goes back to what it was before the first write — the value written in the markup, or none. Neither is ever written as the string `"null"` / `"undefined"`. (`@wcstack/state` never writes `undefined`; React 19 does when a prop that had a value is removed, and so can a direct assignment.) `body` takes both as "no JS body"; `trigger` ignores both.
349
388
 
389
+ ### A url with the command
390
+
391
+ `fetch(url, init)` runs one request with what it is given, and leaves the element's attributes as they are. It is what a command token carries (since 4.24):
392
+
393
+ ```html
394
+ <wcs-fetch manual data-wcs="command.fetch: $command.loadUsers; value: users"></wcs-fetch>
395
+ ```
396
+
397
+ ```javascript
398
+ loadPage(event, page) {
399
+ this.$command.loadUsers.emit("/api/users?page=" + page);
400
+ },
401
+ save() {
402
+ this.$command.saveUser.emit("/api/users/" + this.user.id, { method: "PUT", body: this.user });
403
+ },
404
+ ```
405
+
406
+ - `url` is this request's. With none — or with something that is not a string in its place, as the event an `onclick: $command.x` binding emits first — the element's own `url` is fetched, and `init` is ignored.
407
+ - `init.method` replaces the element's `method`; `init.headers` are added to the `<wcs-fetch-header>` ones (a same name replaces it); `init.body` is sent in place of the element's `body`, which is then kept for the next request.
408
+ - **Why it exists.** A command runs before the bindings of its update. With `url: pageUrl; command.fetch: $command.load`, a handler that changes what `pageUrl` reads and emits `load` in the same breath fetches the url **before** the change — the list is one page behind, and nothing says so. Give the url to the command, or write `url` first and run the request with `trigger` (bindings apply in the order written). Up to 4.23 `fetch()` ignored its arguments.
409
+ - A url given this way counts as the last one fetched: the binding that writes the same url to the element afterwards does not fetch it again.
410
+
350
411
  ## CSS styling with `:state()`
351
412
 
352
413
  `<wcs-fetch>` reflects two boolean output states onto its
@@ -612,7 +673,7 @@ In wcstack applications, **state-driven triggering via `trigger`** is usually th
612
673
 
613
674
  | Method | Description |
614
675
  |--------|-------------|
615
- | `fetch()` | Execute the HTTP request |
676
+ | `fetch(url?, init?)` | Execute the HTTP request. With no argument, the element's own. Since 4.24, `url` and `init` (`{ method?, headers?, body? }`) are for that request only — see [A url with the command](#a-url-with-the-command) |
616
677
  | `abort()` | Cancel the in-flight request |
617
678
 
618
679
  ### `<wcs-fetch-header>`
package/dist/auto.min.js CHANGED
@@ -1,2 +1,2 @@
1
- const t={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};var e="@wcstack/fetch",s="4.23.0";class i{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,s={}){this.laneKey=t,this.policy=e,this._withSignal=s.withSignal??!1,this._trace=s.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._attempts.size}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,s={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(s),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._attempts.set(e,1);const i=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:s,attempt:i}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;const e=this._attempts.get(t.operationId);if(void 0===e||this._claimedOutcome.has(t.operationId))return null;if(!this._isEligible(t))return null;const s=e+1;this._attempts.set(t.operationId,s),this._releaseController(t.operationId);const i=this._makeAttempt(t.operationId,s);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:s}),i}canCommit(t){return t.ownerGeneration===this._ownerGeneration&&(!!this._attempts.has(t.operationId)&&this._isEligible(t))}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&(!(!this._attempts.has(t.operationId)||this._claimedOutcome.has(t.operationId))&&(!!this._isEligible(t)&&(this._claimedOutcome.set(t.operationId,e),!0)))}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId;if(!this._attempts.has(e))return;const s=this._claimedOutcome.get(e)??"stale";this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===s?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:s}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);if(void 0!==this._trace)for(const t of this._attempts.keys())this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._attempts.clear(),this._claimedOutcome.clear(),this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0}_makeAttempt(t,e){let s;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),s=e.signal}return{operationId:t,attempt:e,signal:s}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}}function r(t,e){const s=new Map,i=e=>{const s=t.get(e);return void 0===s?"unknown":s.probe()?"available":"missing"};let r=!0;for(const t of e.required){const e=i(t);s.set(t,e),"available"!==e&&(r=!1)}let n=!0;for(const t of e.optional??[]){const e=i(t);s.set(t,e),"available"!==e&&(n=!1)}const o=r?n?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],c=a.some(e=>!0===t.get(e)?.requiresSecureContext),l=a.some(e=>!0===t.get(e)?.requiresUserActivation),h=c?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",u=l?"required":"not-applicable";return{availability:s,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:u},epoch:e.epoch??0,lastError:e.lastError}}function n(t,e){return e.every(e=>"available"===t.availability.get(e))}const o="capability-missing",a="invalid-argument",c="network",l="http-error",h="timeout",u=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]),d=new Set(["GET","HEAD","OPTIONS"]);class p extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new i("fetch","latest",{withSignal:!0});_inFlight=null;_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return n(this.platformAssessment,p.REQUIRED_CAPABILITIES)}get platformAssessment(){return r(u,{required:p.REQUIRED_CAPABILITIES,optional:p.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,s,i,r){this._commitErrorInfo({code:t,phase:e,recoverable:s,message:i,...void 0===r?{}:{capabilityId:r}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,s=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=s,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:s},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(t,e={}){if(!t)return this._setErrorInfo(a,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const s=this.platformAssessment;if(!n(s,p.REQUIRED_CAPABILITIES)){const t=p.REQUIRED_CAPABILITIES.find(t=>"available"!==s.availability.get(t));return this._setErrorInfo(o,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,e);return this._promise=i,i}async _doFetch(t,e){const s=this._inFlight;null===s||d.has(s.method)||console.warn(`[@wcstack/fetch] [wcs/fetch-request-superseded] A ${s.method} request to "${s.url}" was still in flight when another request started on the same element: it was aborted and its response dropped (the server may have applied it). Give each change its own <wcs-fetch>, or wait for loading to end before starting the next request.`);const i=this._lane.begin(),{ticket:r,attempt:n}=i,o=n.signal,a={method:String(e.method??"GET").toUpperCase(),url:t};this._inFlight=a,this._commitStep(r,()=>this._setLoading(!0)),this._commitStep(r,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:u="GET",body:p=null,contentType:_=null,forceText:g=!1,responseType:f="auto",timeout:m=0}=e;let b=null;m>0&&(b=setTimeout(()=>{if(!this._lane.claimTerminal(r,"timeout"))return;const t=`Request timed out after ${m}ms.`;this._commitStep(r,()=>{this._setErrorInfo(h,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),this._lane.abort(r),this._lane.finalize(r)},m));const y={...e.headers??{}};try{_&&!y["Content-Type"]&&(y["Content-Type"]=_);const e={method:u,headers:y,signal:o};"GET"!==u&&"HEAD"!==u&&null!==p&&(e.body=p);const s=await globalThis.fetch(t,e);let i=null;if("HEAD"===u);else if(s.ok)if(g)i=await s.text();else if("blob"===f)i=await s.blob();else if("arrayBuffer"===f)i=await s.arrayBuffer();else if("text"===f)i=await s.text();else if("json"===f)i=await s.json();else{const t=s.headers.get("Content-Type")||"";i=t.includes("application/json")?await s.json():await s.text()}else;if(!s.ok){const t=await s.text().catch(()=>""),e={status:s.status,statusText:s.statusText,body:t};return this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{this._setErrorInfo(l,"execute",!0,`HTTP ${s.status} ${s.statusText}`),this._setError(e)}),this._commitStep(r,()=>this._setResponse(null,s.status)),this._commitStep(r,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(r,"success"))return null;const n=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(r,()=>this._setResponse(i,s.status,n)),this._commitStep(r,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(r,"aborted")&&this._commitStep(r,()=>this._setLoading(!1)),null):this._lane.claimTerminal(r,"error")?(this._commitStep(r,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(c,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(r,()=>this._setResponse(null,0)),this._commitStep(r,()=>this._setLoading(!1)),null):null}finally{this._inFlight===a&&(this._inFlight=null),null!==b&&clearTimeout(b),this._lane.finalize(r)}}}let _=!1;function g(e){const s=e.target;if(!(s instanceof Element))return;const i=s.closest(`[${t.triggerAttribute}]`);if(!i)return;const r=i.getAttribute(t.triggerAttribute);if(!r)return;const n=customElements.get(t.tagNames.fetch),o=document.getElementById(r);if(!(n&&o instanceof n))return;const a=o;a.url&&(e.preventDefault(),a.fetch())}function f(t,e){let s=Object.getPrototypeOf(t);for(;null!==s;){const t=Object.getOwnPropertyDescriptor(s,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;s=Object.getPrototypeOf(s)}return!1}const m=new WeakSet;function b(t,e,s){if(m.has(t))return;m.add(t);const i=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${i}> has the attribute ${e}="${s}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const y=new WeakMap;function w(t,e){let s=y.get(t);return void 0===s&&(s=new Map,y.set(t,s)),s.has(e)||s.set(e,t.getAttribute(e)),s.get(e)}function v(t,e,s){null===s?t.removeAttribute(e):t.setAttribute(e,s)}function I(t,e,s){const i=w(t,e);v(t,e,void 0===s?i:null===s?null:String(s))}const T=Symbol.for("wcstack.trustedTypes.policy");function A(){const t=globalThis[T];return null===t||"object"!=typeof t?null:t}let E,O=!1;function k(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=A(),s=e?.createHTML;return"function"!=typeof s?t:s.call(e,t)}(e)}catch(t){if(function(){if(void 0!==E)return E;if(!("trustedTypes"in globalThis))return E=!1,E;try{document.createElement("div").innerHTML="<i></i>",E=!1}catch{E=!0}return E}())return void function(){if(O)return;O=!0;const t="function"==typeof A()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}class C extends HTMLElement{static hasConnectedCallbackPromise=!0;static hasPendingPromise=!0;static wcBindable={...p.wcBindable,properties:[...p.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_toldTriggerWithoutUrl=!1;_toldUndefinedHelper=!1;_sentBody=!1;_toldBodyGone=!1;_auto=!1;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new p(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[s,i]of Object.entries(t))this.addEventListener(s,t=>{const s=this.hasAttribute("debug-states");for(const[r,n]of Object.entries(i(t.detail))){try{n?e.add(r):e.delete(r)}catch{}s&&this.toggleAttribute(`data-wcs-state-${r}`,n)}})}get url(){return this.getAttribute("url")||""}set url(t){I(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){I(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){I(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){I(this,"response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get pendingPromise(){return this._autoPending&&!this.manual&&this.url?Promise.resolve().then(()=>this.pendingPromise??void 0):this.loading?this._core.promise.then(()=>{}):null}get manual(){return this.hasAttribute("manual")}set manual(t){!function(t,e,s){const i=w(t,e);v(t,e,void 0===s?i:s?"":null)}(this,"manual",t)}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(!!t){if(!this.url)return void this._warnTriggerWithoutUrl();this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const e={},s=this.querySelectorAll(t.tagNames.fetchHeader);for(const i of s)"boolean"==typeof i.hasHeader?i.hasHeader&&(e[i.headerName]=i.headerValue):this._warnUndefinedHelper(t.tagNames.fetchHeader,"header");return e}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const s=this.querySelector(t.tagNames.fetchBody);if(s&&"string"!=typeof s.bodyContent)this._warnUndefinedHelper(t.tagNames.fetchBody,"body");else if(s)return{body:s.bodyContent||null,contentType:s.contentType};return{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;e||(this._lastFetchedUrl=null),this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?(null===t&&this._warnUnsafeAutoFetch(),this._auto=!0,this.fetch().finally(()=>t?.())):t?.()}))}_warnTriggerWithoutUrl(){this._toldTriggerWithoutUrl||(this._toldTriggerWithoutUrl=!0,console.warn("[@wcstack/fetch] [wcs/command-not-ready] trigger was refused: there is no url, so nothing is fetched. Write url before trigger (bindings apply in the order written), and write trigger again once there is one. (Said once until a request is sent again.)",this))}_warnUndefinedHelper(e,s){this._toldUndefinedHelper||(this._toldUndefinedHelper=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-helper-undefined] <${e}> inside this <${t.tagNames.fetch}> is not defined, so its ${s} is not sent. Load @wcstack/fetch/auto, or define WcsFetchHeader and WcsFetchBody with WcsFetch when the page defines the tags itself. (Said once per element.)`,this))}_warnUnsafeAutoFetch(){const e=this.method;"GET"!==e&&"HEAD"!==e&&"OPTIONS"!==e&&null===this._body&&null===this.querySelector(t.tagNames.fetchBody)&&console.warn(`[@wcstack/fetch] [wcs/fetch-auto-unsafe] The url changed to "${this.url}", so this <wcs-fetch> sent a ${e} with no body (its method stays ${e}; a body is sent once). Give loading and each change its own <wcs-fetch>, or set \`manual\` on the one that changes data.`)}_warnBodyGone(){const e=this.method;!this._sentBody||this._toldBodyGone||"POST"!==e&&"PUT"!==e&&"PATCH"!==e||(this._toldBodyGone=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-body-gone] This <${t.tagNames.fetch}> sent a ${e} with no body: a body is sent once, and none was written since the last request. A binding does not write a value equal to the one it wrote last, so the same string on a retry never arrives: write a new object each time (this.payload = { ...entry }), or null between two sends. (Said once until a body is sent again.)`,this))}async fetch(){this._lastFetchedUrl=this.url,this.url&&(this._toldTriggerWithoutUrl=!1);const t=this._collectHeaders(),e=this._body;this._body=null;const{body:s,contentType:i}=this._collectBody(e),r=this._auto;this._auto=!1,null!==s?(this._sentBody=!0,this._toldBodyGone=!1):r||this._warnBodyGone(),s instanceof FormData&&Object.keys(t).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const n=await this._core.fetch(this.url,{method:this.method,headers:t,body:s,contentType:i,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==n){const t=document.getElementById(this.target);t&&k(t,n)}return n}attributeChangedCallback(t,e,s){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,s=e?.inputs;if(void 0===s)return;const i=t.getAttribute;for(const e of s){const s=e.name,r="function"==typeof i?i.call(t,s.toLowerCase()):null;if(null!==r&&r.startsWith("[object ")&&b(t,s,r),!Object.prototype.hasOwnProperty.call(t,s))continue;if(!f(t,s))continue;const n=t,o=n[s];delete n[s],n[s]=o}}(this),this.style.display="none",_||(_=!0,document.addEventListener("click",g)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}connectedMoveCallback(){}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}}class L extends HTMLElement{connectedCallback(){for(const t of["name","value"])if(Object.prototype.hasOwnProperty.call(this,t)){const e=this[t];delete this[t],this[t]=e}this.style.display="none"}get name(){return this.getAttribute("name")??""}set name(t){I(this,"name",t)}get value(){return this.getAttribute("value")??""}set value(t){I(this,"value",t)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class S extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class U extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;_warnedTarget=null;get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver()}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){this._disconnectObserver(),this._done||this.disabled||!this.target||"undefined"==typeof IntersectionObserver||(this._observer=new IntersectionObserver(t=>{t.some(t=>t.isIntersecting)&&this._triggerFetch()},{root:this._resolveRoot(),rootMargin:this.rootMargin,threshold:this.threshold}),this._observer.observe(this))}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null)}_resolveRoot(){return this.root&&document.getElementById(this.root)||null}_triggerFetch(){const e=document.getElementById(this.target);e instanceof C?e.loading||(e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver())):this._warnedTarget!==this.target&&(this._warnedTarget=this.target,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-target] <${t.tagNames.infiniteScroll} target="${this.target}"> came into view, but no <${t.tagNames.fetch}> has that id, so no page was loaded.`))}}const R=Symbol.for("wcstack.package"),P=new WeakSet;function j(t,e){Object.defineProperty(t,R,{value:e,configurable:!0})}function B(t,e,s,i,r){if(void 0!==i&&(s===i||s.prototype instanceof i))return;const n=s[R];if(n===r||P.has(t))return;P.add(t);const o=r.slice(0,r.lastIndexOf("@"));console.warn(`[${o}] [wcs/package-twice] <${e}> is already defined by ${n??`another copy of ${o} that does not name its version`}; this copy, ${r}, does nothing. Load each package once.`)}function q(i=customElements){!function(t,e,s){for(const[i,r]of s){const s=t.get(i);void 0===s?(j(r,e),t.define(i,r)):B(t,i,s,r,e)}}(i,`${e}@${s}`,[[t.tagNames.fetch,C],[t.tagNames.fetchHeader,L],[t.tagNames.fetchBody,S],[t.tagNames.infiniteScroll,U]])}var H;q(H);
1
+ const t={triggerAttribute:"data-fetchtarget",tagNames:{fetch:"wcs-fetch",fetchHeader:"wcs-fetch-header",fetchBody:"wcs-fetch-body",infiniteScroll:"wcs-infinite-scroll"}};var e="@wcstack/fetch",s="4.24.0";class i{laneKey;policy;_ownerGeneration=0;_latestEpoch=0;_nextOperationId=1;_activeOperationId=void 0;_activeOperationIds=new Set;_queue=[];_claimedOutcome=new Map;_controllers=new Map;_attempts=new Map;_withSignal;_trace;constructor(t,e,s={}){this.laneKey=t,this.policy=e,this._withSignal=s.withSignal??!1,this._trace=s.trace}get ownerGeneration(){return this._ownerGeneration}get inFlightCount(){return this._attempts.size}get latestEpoch(){return this._latestEpoch}get activeOperationId(){return this._activeOperationId}begin(){let t;switch(this.policy){case"latest":t=++this._latestEpoch,void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);break;case"exhaust":if(void 0!==this._activeOperationId)return null}const e=this._nextOperationId++,s={operationId:e,ownerGeneration:this._ownerGeneration,laneKey:this.laneKey,policy:this.policy,supersedeEpoch:t};switch(this.policy){case"latest":case"exhaust":this._activeOperationId=e;break;case"queue":this._queue.push(s),void 0===this._activeOperationId&&(this._activeOperationId=e);break;case"overlap":this._activeOperationIds.add(e)}this._attempts.set(e,1);const i=this._makeAttempt(e,1);return void 0!==this._trace&&this._trace({type:"io:operation-started",operationId:e,laneKey:this.laneKey,policy:this.policy}),{ticket:s,attempt:i}}retry(t){if(t.ownerGeneration!==this._ownerGeneration)return null;const e=this._attempts.get(t.operationId);if(void 0===e||this._claimedOutcome.has(t.operationId))return null;if(!this._isEligible(t))return null;const s=e+1;this._attempts.set(t.operationId,s),this._releaseController(t.operationId);const i=this._makeAttempt(t.operationId,s);return void 0!==this._trace&&this._trace({type:"io:operation-retried",operationId:t.operationId,laneKey:this.laneKey,attempt:s}),i}canCommit(t){return t.ownerGeneration===this._ownerGeneration&&(!!this._attempts.has(t.operationId)&&this._isEligible(t))}claimTerminal(t,e){return t.ownerGeneration===this._ownerGeneration&&(!(!this._attempts.has(t.operationId)||this._claimedOutcome.has(t.operationId))&&(!!this._isEligible(t)&&(this._claimedOutcome.set(t.operationId,e),!0)))}claimedOutcome(t){return this._claimedOutcome.get(t.operationId)}finalize(t){const e=t.operationId;if(!this._attempts.has(e))return;const s=this._claimedOutcome.get(e)??"stale";this._claimedOutcome.delete(e),this._releaseController(e),this._attempts.delete(e),this._advanceBookkeeping(e),void 0!==this._trace&&("stale"===s?this._trace({type:"io:stale-dropped",operationId:e,laneKey:this.laneKey}):this._trace({type:"io:operation-settled",operationId:e,laneKey:this.laneKey,outcome:s}))}signalOf(t){return this._controllers.get(t.operationId)?.signal}abort(t){this._abortController(t.operationId)}abortActive(){void 0!==this._activeOperationId&&this._abortController(this._activeOperationId);for(const t of this._activeOperationIds)this._abortController(t)}disposeOwner(){this._ownerGeneration+=1;for(const t of Array.from(this._controllers.keys()))this._abortController(t),this._releaseController(t);if(void 0!==this._trace)for(const t of this._attempts.keys())this._trace({type:"io:stale-dropped",operationId:t,laneKey:this.laneKey});this._attempts.clear(),this._claimedOutcome.clear(),this._activeOperationId=void 0,this._activeOperationIds.clear(),this._queue.length=0}_makeAttempt(t,e){let s;if(this._withSignal&&"function"==typeof AbortController){const e=new AbortController;this._controllers.set(t,e),s=e.signal}return{operationId:t,attempt:e,signal:s}}_isEligible(t){switch(this.policy){case"latest":return t.supersedeEpoch===this._latestEpoch;case"queue":case"exhaust":return this._activeOperationId===t.operationId;case"overlap":return this._activeOperationIds.has(t.operationId)}}_advanceBookkeeping(t){switch(this.policy){case"latest":case"exhaust":this._activeOperationId===t&&(this._activeOperationId=void 0);break;case"queue":{const e=this._queue.filter(e=>e.operationId!==t);this._queue.length=0,this._queue.push(...e),this._activeOperationId=this._queue.length>0?this._queue[0].operationId:void 0;break}case"overlap":this._activeOperationIds.delete(t)}}_abortController(t){const e=this._controllers.get(t);void 0===e||e.signal.aborted||e.abort()}_releaseController(t){this._controllers.delete(t)}}function n(t,e){const s=new Map,i=e=>{const s=t.get(e);return void 0===s?"unknown":s.probe()?"available":"missing"};let n=!0;for(const t of e.required){const e=i(t);s.set(t,e),"available"!==e&&(n=!1)}let r=!0;for(const t of e.optional??[]){const e=i(t);s.set(t,e),"available"!==e&&(r=!1)}const o=n?r?"ready":"degraded":"idle",a=[...e.required,...e.optional??[]],l=a.some(e=>!0===t.get(e)?.requiresSecureContext),c=a.some(e=>!0===t.get(e)?.requiresUserActivation),h=l?!0===globalThis.isSecureContext?"satisfied":"required":"not-applicable",d=c?"required":"not-applicable";return{availability:s,permission:e.permission??"not-applicable",readiness:o,activity:e.activity??"inactive",preconditions:{secureContext:h,userActivation:d},epoch:e.epoch??0,lastError:e.lastError}}function r(t,e){return e.every(e=>"available"===t.availability.get(e))}const o="capability-missing",a="invalid-argument",l="network",c="http-error",h="timeout",d=new Map([["web.fetch",{probe:()=>"function"==typeof globalThis.fetch,compatKey:"api.fetch"}],["web.abort-controller",{probe:()=>"function"==typeof globalThis.AbortController,compatKey:"api.AbortController"}]]),u=new Set(["GET","HEAD","OPTIONS"]);class _ extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"value",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.value},{name:"loading",event:"wcs-fetch:loading-changed",semantics:"state"},{name:"error",event:"wcs-fetch:error",semantics:"state"},{name:"status",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.status},{name:"objectURL",event:"wcs-fetch:response",semantics:"state",getter:t=>t.detail.objectURL},{name:"errorInfo",event:"wcs-fetch:error-info-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"}],commands:[{name:"fetch",async:!0},{name:"abort"}]};_target;_value=null;_loading=!1;_error=null;_status=0;_objectURL=null;_promise=Promise.resolve(null);_lane=new i("fetch","latest",{withSignal:!0});_inFlight=null;_ready=Promise.resolve();_errorInfo=null;static REQUIRED_CAPABILITIES=["web.fetch"];static OPTIONAL_CAPABILITIES=["web.abort-controller"];constructor(t){super(),this._target=t??this}get ready(){return this._ready}observe(){return this._ready}dispose(){this._lane.disposeOwner(),null!==this._objectURL&&(this._revokeObjectURL(this._objectURL),this._objectURL=null)}get value(){return this._value}get loading(){return this._loading}get error(){return this._error}get status(){return this._status}get objectURL(){return this._objectURL}get promise(){return this._promise}get errorInfo(){return this._errorInfo}get supported(){return r(this.platformAssessment,_.REQUIRED_CAPABILITIES)}get platformAssessment(){return n(d,{required:_.REQUIRED_CAPABILITIES,optional:_.OPTIONAL_CAPABILITIES,activity:this._loading?"active":"inactive",lastError:this._errorInfo??void 0})}_setErrorInfo(t,e,s,i,n){this._commitErrorInfo({code:t,phase:e,recoverable:s,message:i,...void 0===n?{}:{capabilityId:n}})}_commitErrorInfo(t){this._errorInfo!==t&&(this._errorInfo=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error-info-changed",{detail:t,bubbles:!0})))}_setLoading(t){this._loading=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:loading-changed",{detail:t,bubbles:!0}))}_setError(t){this._error!==t&&(this._error=t,this._target.dispatchEvent(new CustomEvent("wcs-fetch:error",{detail:t,bubbles:!0})))}_setResponse(t,e,s=null){null!==this._objectURL&&this._revokeObjectURL(this._objectURL),this._objectURL=s,this._value=t,this._status=e,this._target.dispatchEvent(new CustomEvent("wcs-fetch:response",{detail:{value:t,status:e,objectURL:s},bubbles:!0}))}_createObjectURL(t){return"undefined"!=typeof URL&&"function"==typeof URL.createObjectURL?URL.createObjectURL(t):null}_revokeObjectURL(t){"undefined"!=typeof URL&&"function"==typeof URL.revokeObjectURL&&URL.revokeObjectURL(t)}abort(){this._lane.abortActive()}_commitStep(t,e){this._lane.canCommit(t)&&e()}async fetch(t,e={}){if(!t)return this._setErrorInfo(a,"start",!1,"url attribute is required."),this._setError({message:"url attribute is required."}),null;const s=this.platformAssessment;if(!r(s,_.REQUIRED_CAPABILITIES)){const t=_.REQUIRED_CAPABILITIES.find(t=>"available"!==s.availability.get(t));return this._setErrorInfo(o,"start",!1,`Required capability "${t}" is unavailable.`,t),this._setError({message:`Required capability "${t}" is unavailable.`}),null}const i=this._doFetch(t,e);return this._promise=i,i}async _doFetch(t,e){const s=this._inFlight;null===s||u.has(s.method)||console.warn(`[@wcstack/fetch] [wcs/fetch-request-superseded] A ${s.method} request to "${s.url}" was still in flight when another request started on the same element: it was aborted and its response dropped (the server may have applied it). Give each change its own <wcs-fetch>, or wait for loading to end before starting the next request.`);const i=this._lane.begin(),{ticket:n,attempt:r}=i,o=r.signal,a={method:String(e.method??"GET").toUpperCase(),url:t};this._inFlight=a,this._commitStep(n,()=>this._setLoading(!0)),this._commitStep(n,()=>{this._commitErrorInfo(null),this._setError(null)});const{method:d="GET",body:_=null,contentType:g=null,forceText:p=!1,responseType:f="auto",timeout:m=0}=e;let b=null;m>0&&(b=setTimeout(()=>{if(!this._lane.claimTerminal(n,"timeout"))return;const t=`Request timed out after ${m}ms.`;this._commitStep(n,()=>{this._setErrorInfo(h,"execute",!0,t),this._setError({name:"TimeoutError",message:t})}),this._commitStep(n,()=>this._setResponse(null,0)),this._commitStep(n,()=>this._setLoading(!1)),this._lane.abort(n),this._lane.finalize(n)},m));const w={...e.headers??{}};try{g&&!w["Content-Type"]&&(w["Content-Type"]=g);const e={method:d,headers:w,signal:o};"GET"!==d&&"HEAD"!==d&&null!==_&&(e.body=_);const s=await globalThis.fetch(t,e);let i=null;if("HEAD"===d);else if(s.ok)if(p)i=await s.text();else if("blob"===f)i=await s.blob();else if("arrayBuffer"===f)i=await s.arrayBuffer();else if("text"===f)i=await s.text();else if("json"===f)i=await s.json();else{const t=s.headers.get("Content-Type")||"";i=t.includes("application/json")?await s.json():await s.text()}else;if(!s.ok){const t=await s.text().catch(()=>""),e={status:s.status,statusText:s.statusText,body:t};return this._lane.claimTerminal(n,"error")?(this._commitStep(n,()=>{this._setErrorInfo(c,"execute",!0,`HTTP ${s.status} ${s.statusText}`),this._setError(e)}),this._commitStep(n,()=>this._setResponse(null,s.status)),this._commitStep(n,()=>this._setLoading(!1)),null):null}if(!this._lane.claimTerminal(n,"success"))return null;const r=i instanceof Blob?this._createObjectURL(i):null;return this._commitStep(n,()=>this._setResponse(i,s.status,r)),this._commitStep(n,()=>this._setLoading(!1)),this._value}catch(t){return t&&"AbortError"===t.name?(this._lane.claimTerminal(n,"aborted")&&this._commitStep(n,()=>this._setLoading(!1)),null):this._lane.claimTerminal(n,"error")?(this._commitStep(n,()=>{const e=String(t?.message??"Network request failed.");this._setErrorInfo(l,"execute",!0,e),this._setError(t??{message:e})}),this._commitStep(n,()=>this._setResponse(null,0)),this._commitStep(n,()=>this._setLoading(!1)),null):null}finally{this._inFlight===a&&(this._inFlight=null),null!==b&&clearTimeout(b),this._lane.finalize(n)}}}let g=!1;function p(e){const s=e.target;if(!(s instanceof Element))return;const i=s.closest(`[${t.triggerAttribute}]`);if(!i)return;const n=i.getAttribute(t.triggerAttribute);if(!n)return;const r=customElements.get(t.tagNames.fetch),o=document.getElementById(n);if(!(r&&o instanceof r))return;const a=o;a.url&&(e.preventDefault(),a.fetch())}function f(t,e){let s=Object.getPrototypeOf(t);for(;null!==s;){const t=Object.getOwnPropertyDescriptor(s,e);if(void 0!==t)return"function"==typeof t.get||"function"==typeof t.set;s=Object.getPrototypeOf(s)}return!1}const m=new WeakSet;function b(t,e,s){if(m.has(t))return;m.add(t);const i=t.localName??"element";console.warn(`[wcs/input-as-attribute] <${i}> has the attribute ${e}="${s}": an object was written as an attribute, so the element did not receive it. A framework does that when the property is set before the element's definition loads (React 19), or when told to (Vue's .attr). Load the definition before rendering, or assign the property through a ref (Vue: .prop). (Said once per element.)`,t)}const w=new WeakMap;function y(t,e){let s=w.get(t);return void 0===s&&(s=new Map,w.set(t,s)),s.has(e)||s.set(e,t.getAttribute(e)),s.get(e)}function v(t,e,s){null===s?t.removeAttribute(e):t.setAttribute(e,s)}function I(t,e,s){const i=y(t,e);v(t,e,void 0===s?i:null===s?null:String(s))}const T=Symbol.for("wcstack.trustedTypes.policy");function E(){const t=globalThis[T];return null===t||"object"!=typeof t?null:t}let A,O=!1;function k(t,e){try{t.innerHTML=function(t){if("string"!=typeof t)return t;const e=E(),s=e?.createHTML;return"function"!=typeof s?t:s.call(e,t)}(e)}catch(t){if(function(){if(void 0!==A)return A;if(!("trustedTypes"in globalThis))return A=!1,A;try{document.createElement("div").innerHTML="<i></i>",A=!1}catch{A=!0}return A}())return void function(){if(O)return;O=!0;const t="function"==typeof E()?.createHTML?"The injected policy's createHTML() did not return a TrustedHTML.":"No sanitizing policy is installed, and @wcstack/fetch deliberately does not pass responses through an identity policy — that would defeat the CSP.";console.error(`[@wcstack/fetch] The "target" HTML replace mode was blocked by Trusted Types (require-trusted-types-for 'script'). ${t}\nInstall a sanitizing policy before the first fetch:\n globalThis[Symbol.for("wcstack.trustedTypes.policy")] =\n trustedTypes.createPolicy("my-app", { createHTML: (s) => DOMPurify.sanitize(s) });\nOr drop "target" and bind the response through @wcstack/state. See docs/csp.md section 7.`)}();throw t}}class C extends HTMLElement{static hasConnectedCallbackPromise=!0;static hasPendingPromise=!0;static wcBindable={..._.wcBindable,properties:[..._.wcBindable.properties,{name:"trigger",event:"wcs-fetch:trigger-changed",semantics:"state"}],inputs:[{name:"url"},{name:"method"},{name:"target"},{name:"manual"},{name:"body"},{name:"responseType"},{name:"trigger"}]};static get observedAttributes(){return["url"]}_core;_body=null;_trigger=!1;_connectedCallbackPromise=Promise.resolve();_autoPending=!1;_connectResolve=null;_lastFetchedUrl=null;_toldTriggerWithoutUrl=!1;_toldUndefinedHelper=!1;_sentBody=!1;_toldBodyGone=!1;_auto=!1;_internals=null;constructor(){super(),this._internals=this._initInternals(),this._wireStates({"wcs-fetch:loading-changed":t=>({loading:!0===t}),"wcs-fetch:error":t=>({error:null!=t})}),this._core=new _(this)}get debugStates(){return this._internals?[...this._internals.states]:[]}_initInternals(){try{if("function"!=typeof this.attachInternals)return null;const t=this.attachInternals();return t.states.add("wcs-probe"),t.states.delete("wcs-probe"),t}catch{return null}}_wireStates(t){if(null===this._internals)return;const e=this._internals.states;for(const[s,i]of Object.entries(t))this.addEventListener(s,t=>{const s=this.hasAttribute("debug-states");for(const[n,r]of Object.entries(i(t.detail))){try{r?e.add(n):e.delete(n)}catch{}s&&this.toggleAttribute(`data-wcs-state-${n}`,r)}})}get url(){return this.getAttribute("url")||""}set url(t){I(this,"url",t)}get method(){return(this.getAttribute("method")||"GET").toUpperCase()}set method(t){I(this,"method",t)}get target(){return this.getAttribute("target")}set target(t){I(this,"target",t)}get responseType(){return this.getAttribute("response-type")||"auto"}set responseType(t){I(this,"response-type",t)}get value(){return this._core.value}get loading(){return this._core.loading}get error(){return this._core.error}get status(){return this._core.status}get objectURL(){return this._core.objectURL}get errorInfo(){return this._core.errorInfo}get promise(){return this._core.promise}get connectedCallbackPromise(){return this._connectedCallbackPromise}get pendingPromise(){return this._autoPending&&!this.manual&&this.url?Promise.resolve().then(()=>this.pendingPromise??void 0):this.loading?this._core.promise.then(()=>{}):null}get manual(){return this.hasAttribute("manual")}set manual(t){!function(t,e,s){const i=y(t,e);v(t,e,void 0===s?i:s?"":null)}(this,"manual",t)}get body(){return this._body}set body(t){this._body=t??null}get trigger(){return this._trigger}set trigger(t){if(!!t){if(!this.url)return void this._warnTriggerWithoutUrl();this._trigger=!0,this.fetch().finally(()=>{this._trigger=!1,this.dispatchEvent(new CustomEvent("wcs-fetch:trigger-changed",{detail:!1,bubbles:!0}))})}}_collectHeaders(){const e={},s=this.querySelectorAll(t.tagNames.fetchHeader);for(const i of s)"boolean"==typeof i.hasHeader?i.hasHeader&&(e[i.headerName]=i.headerValue):this._warnUndefinedHelper(t.tagNames.fetchHeader,"header");return e}_isNativeBodyInit(t){return t instanceof Blob||t instanceof FormData||t instanceof URLSearchParams||t instanceof ArrayBuffer||ArrayBuffer.isView(t)}_collectBody(e){if(null!==e)return"string"==typeof e||this._isNativeBodyInit(e)?{body:e,contentType:null}:{body:JSON.stringify(e),contentType:"application/json"};const s=this.querySelector(t.tagNames.fetchBody);if(s&&"string"!=typeof s.bodyContent)this._warnUndefinedHelper(t.tagNames.fetchBody,"body");else if(s)return{body:s.bodyContent||null,contentType:s.contentType};return{body:null,contentType:null}}abort(){this._core.abort()}_scheduleAutoFetch(){this._autoPending||(this._autoPending=!0,queueMicrotask(()=>{this._autoPending=!1;const t=this._connectResolve;this._connectResolve=null;const e=this.url;e||(this._lastFetchedUrl=null),this.isConnected&&!this.manual&&e&&e!==this._lastFetchedUrl?(null===t&&this._warnUnsafeAutoFetch(),this._auto=!0,this.fetch().finally(()=>t?.())):t?.()}))}_warnTriggerWithoutUrl(){this._toldTriggerWithoutUrl||(this._toldTriggerWithoutUrl=!0,console.warn("[@wcstack/fetch] [wcs/command-not-ready] trigger was refused: there is no url, so nothing is fetched. Write url before trigger (bindings apply in the order written), and write trigger again once there is one. (Said once until a request is sent again.)",this))}_warnUndefinedHelper(e,s){this._toldUndefinedHelper||(this._toldUndefinedHelper=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-helper-undefined] <${e}> inside this <${t.tagNames.fetch}> is not defined, so its ${s} is not sent. Load @wcstack/fetch/auto, or define WcsFetchHeader and WcsFetchBody with WcsFetch when the page defines the tags itself. (Said once per element.)`,this))}_warnUnsafeAutoFetch(){const e=this.method;"GET"!==e&&"HEAD"!==e&&"OPTIONS"!==e&&null===this._body&&null===this.querySelector(t.tagNames.fetchBody)&&console.warn(`[@wcstack/fetch] [wcs/fetch-auto-unsafe] The url changed to "${this.url}", so this <wcs-fetch> sent a ${e} with no body (its method stays ${e}; a body is sent once). Give loading and each change its own <wcs-fetch>, or set \`manual\` on the one that changes data.`)}_warnBodyGone(){const e=this.method;!this._sentBody||this._toldBodyGone||"POST"!==e&&"PUT"!==e&&"PATCH"!==e||(this._toldBodyGone=!0,console.warn(`[@wcstack/fetch] [wcs/fetch-body-gone] This <${t.tagNames.fetch}> sent a ${e} with no body: a body is sent once, and none was written since the last request. A binding does not write a value equal to the one it wrote last, so the same string on a retry never arrives: write a new object each time (this.payload = { ...entry }), or null between two sends. (Said once until a body is sent again.)`,this))}async fetch(t,e){const s="string"==typeof t&&""!==t,i=s?t:this.url,n=s&&null!==e&&"object"==typeof e?e:{};this._lastFetchedUrl=i,i&&(this._toldTriggerWithoutUrl=!1);const r={...this._collectHeaders(),..."object"==typeof n.headers?n.headers:null};let o=n.body??null;null===o&&(o=this._body,this._body=null);const{body:a,contentType:l}=this._collectBody(o),c=this._auto;this._auto=!1,null!==a?(this._sentBody=!0,this._toldBodyGone=!1):c||this._warnBodyGone(),a instanceof FormData&&Object.keys(r).some(t=>"content-type"===t.toLowerCase())&&console.warn("[@wcstack/fetch] A manual Content-Type header was set alongside a FormData body. This drops the multipart boundary the browser adds automatically; remove the Content-Type header (e.g. the <wcs-fetch-header>) to fix multipart uploads.");const h=await this._core.fetch(i,{method:"string"==typeof n.method&&n.method?n.method.toUpperCase():this.method,headers:r,body:a,contentType:l,forceText:!!this.target,responseType:this.responseType});if(this.target&&null!==h){const t=document.getElementById(this.target);t&&k(t,h)}return h}attributeChangedCallback(t,e,s){"url"===t&&this._scheduleAutoFetch()}connectedCallback(){!function(t){const e=t.constructor?.wcBindable,s=e?.inputs;if(void 0===s)return;const i=t.getAttribute;for(const e of s){const s=e.name,n="function"==typeof i?i.call(t,s.toLowerCase()):null;if(null!==n&&n.startsWith("[object ")&&b(t,s,n),!Object.prototype.hasOwnProperty.call(t,s))continue;if(!f(t,s))continue;const r=t,o=r[s];delete r[s],r[s]=o}}(this),this.style.display="none",g||(g=!0,document.addEventListener("click",p)),!this.manual&&this.url&&(this._connectedCallbackPromise=new Promise(t=>{this._connectResolve=t})),this._scheduleAutoFetch()}connectedMoveCallback(){}disconnectedCallback(){this.abort(),this._lastFetchedUrl=null,this._connectResolve?.(),this._connectResolve=null}}class L extends HTMLElement{connectedCallback(){for(const t of["name","value"])if(Object.prototype.hasOwnProperty.call(this,t)){const e=this[t];delete this[t],this[t]=e}this.style.display="none"}get name(){return this.getAttribute("name")??""}set name(t){I(this,"name",t)}get value(){return this.getAttribute("value")??""}set value(t){I(this,"value",t)}get headerName(){return this.name}get headerValue(){return this.value}get hasHeader(){return""!==this.name&&this.hasAttribute("value")}}class R extends HTMLElement{constructor(){super(),this.attachShadow({mode:"open"})}get contentType(){return this.getAttribute("type")||"application/json"}get bodyContent(){return this.textContent?.trim()||""}}class S extends HTMLElement{static get observedAttributes(){return["target","root","root-margin","threshold","disabled"]}_observer=null;_done=!1;_warnedTarget=null;_warnedRoot=null;_warnedMargin=null;_rootElement=null;_inView=!1;_fetch=null;_urlObserver=null;_asked=null;_startedAt=0;_changedInFlight=!1;_answered=!1;_settling=!1;_onResponse=()=>{this._answered=!0};_onLoadingChanged=t=>{t.detail?this._started():this._ended()};get target(){return this.getAttribute("target")||""}set target(t){this.setAttribute("target",t)}get root(){return this.getAttribute("root")}set root(t){null===t?this.removeAttribute("root"):this.setAttribute("root",t)}get rootMargin(){return this.getAttribute("root-margin")||"0px"}set rootMargin(t){this.setAttribute("root-margin",t)}get threshold(){const t=Number(this.getAttribute("threshold")??"0");return Number.isFinite(t)?t:0}set threshold(t){this.setAttribute("threshold",String(t))}get disabled(){return this.hasAttribute("disabled")}set disabled(t){t?this.setAttribute("disabled",""):this.removeAttribute("disabled")}get once(){return this.hasAttribute("once")}set once(t){t?this.setAttribute("once",""):this.removeAttribute("once")}connectedCallback(){this._observe()}disconnectedCallback(){this._disconnectObserver(),this._follow(null)}attributeChangedCallback(){this.isConnected&&this._observe()}_observe(){if(this._disconnectObserver(),!this._done&&!this.disabled&&this.target&&"undefined"!=typeof IntersectionObserver){this._rootElement=this._resolveRoot();try{this._observer=new IntersectionObserver(t=>{this._inView=t[t.length-1].isIntersecting,this._inView&&this._run(!0)},{root:this._rootElement,rootMargin:this.rootMargin,threshold:Math.min(1,Math.max(0,this.threshold))})}catch(e){const s=this.rootMargin;return void(this._warnedMargin!==s&&(this._warnedMargin=s,console.warn(`[@wcstack/fetch] [wcs/root-margin-unit] <${t.tagNames.infiniteScroll} root-margin="${s}"> is not a margin the browser takes (${e.message}): write each length with px or %, as "240px 0px". Nothing is observed, so no page is loaded.`)))}this._observer.observe(this)}}_disconnectObserver(){this._observer&&(this._observer.disconnect(),this._observer=null),this._inView=!1}_resolveRoot(){const e=this.root;if(!e)return null;let s=document.getElementById(e);if(!s)try{s=document.querySelector(e)}catch{}if(this._warnedRoot!==e){const i=`<${t.tagNames.infiniteScroll} root="${e}">`;s?function(t){const e=getComputedStyle(t);return"visible"===e.overflowX&&"visible"===e.overflowY}(s)&&(this._warnedRoot=e,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-root] ${i} is <${s.localName}>, which does not scroll (overflow: visible): everything inside it counts as on screen, so page after page is loaded. Name the element that scrolls, or leave root out for the viewport.`)):(this._warnedRoot=e,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-root] ${i}: no element has that id, and none matches it as a selector, so the viewport is the scroll root.`))}return s}_resolveTarget(){const e=document.getElementById(this.target);return e instanceof C?(this._follow(e),e):(this._warnedTarget!==this.target&&(this._warnedTarget=this.target,console.warn(`[@wcstack/fetch] [wcs/infinite-scroll-target] <${t.tagNames.infiniteScroll} target="${this.target}"> came into view, but no <${t.tagNames.fetch}> has that id, so no page was loaded.`)),this._follow(null),null)}_follow(t){this._fetch!==t&&(this._fetch?.removeEventListener("wcs-fetch:loading-changed",this._onLoadingChanged),this._fetch?.removeEventListener("wcs-fetch:response",this._onResponse),this._urlObserver?.disconnect(),this._urlObserver=null,this._fetch=t,this._settling=!1,this._changedInFlight=!1,t&&(t.addEventListener("wcs-fetch:loading-changed",this._onLoadingChanged),t.addEventListener("wcs-fetch:response",this._onResponse),this._urlObserver=new MutationObserver(()=>this._urlChanged()),this._urlObserver.observe(t,{attributes:!0,attributeFilter:["url"]})))}_position(){return this.getBoundingClientRect().top+(this._rootElement?this._rootElement.scrollTop:window.scrollY)}_started(){this._asked=this._fetch.url,this._startedAt=this._position(),this._changedInFlight=!1,this._answered=!1,this._settling=!1}_ended(){this._settling=!0,U(3,()=>{this._settling&&(this._settling=!1,!this._inView||!this._changedInFlight&&this._answered&&this._position()===this._startedAt||this._run(!1))})}_urlChanged(){this._fetch.loading?this._changedInFlight=!0:!this._settling&&this._inView&&(null!==this._asked?U(2,()=>{this._inView&&this._run(!1)}):this._run(!1))}_run(t){const e=this._resolveTarget();e&&!e.loading&&e.url&&(t||e.url!==this._asked)&&(this._asked=e.url,e.trigger=!0,this.once&&(this._done=!0,this._disconnectObserver(),this._follow(null)))}}function U(t,e){requestAnimationFrame(()=>t>1?U(t-1,e):e())}const j=Symbol.for("wcstack.package"),B=new WeakSet;function P(t,e){Object.defineProperty(t,j,{value:e,configurable:!0})}function $(t,e,s,i,n){if(void 0!==i&&(s===i||s.prototype instanceof i))return;const r=s[j];if(r===n||B.has(t))return;B.add(t);const o=n.slice(0,n.lastIndexOf("@"));console.warn(`[${o}] [wcs/package-twice] <${e}> is already defined by ${r??`another copy of ${o} that does not name its version`}; this copy, ${n}, does nothing. Load each package once.`)}function q(i=customElements){!function(t,e,s){for(const[i,n]of s){const s=t.get(i);void 0===s?(P(n,e),t.define(i,n)):$(t,i,s,n,e)}}(i,`${e}@${s}`,[[t.tagNames.fetch,C],[t.tagNames.fetchHeader,L],[t.tagNames.fetchBody,R],[t.tagNames.infiniteScroll,S]])}var x;q(x);
2
2
  //# sourceMappingURL=auto.min.js.map