@wcstack/magnetometer 1.16.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 ADDED
@@ -0,0 +1,139 @@
1
+ # @wcstack/magnetometer
2
+
3
+ `@wcstack/magnetometer` は wcstack エコシステム向けのヘッドレスな Generic Sensor API(Magnetometer)コンポーネントです。
4
+
5
+ 視覚的な UI ウィジェットではありません。デバイスの磁束密度読み取りをリアクティブな state に変える**非同期プリミティブノード**です。
6
+
7
+ `@wcstack/state` と組み合わせると、`<wcs-magnetometer>` はパス契約で直接バインドできます:
8
+
9
+ - **入力サーフェス**: `frequency`(サンプリングレート、Hz)
10
+ - **出力 state サーフェス**: `x`、`y`、`z`、`error`
11
+
12
+ `@wcstack/magnetometer` は [CSBC](https://github.com/csbc-dev/arch/blob/main/README.md)(Core / Shell / Binding Contract)アーキテクチャに従います:
13
+
14
+ - **Core**(`MagnetometerCore`)がプラットフォームの`Magnetometer`を構築し、live な`reading`/`error`イベントを追従
15
+ - **Shell**(`<wcs-magnetometer>`)がその state を DOM ライフサイクルに接続
16
+ - **Binding Contract**(`static wcBindable`)が観測可能な`properties`と`start`/`stop`の`commands`を宣言
17
+
18
+ ## なぜ存在するか — プラットフォームAPI自体がnever-throwと最初から一致する稀な例
19
+
20
+ Generic Sensor API の`Accelerometer`/`Gyroscope`/`Magnetometer`/`AmbientLightSensor`族は全て共通の形状を持ちます: `.start()`/`.stop()`、サンプルごとの`'reading'`イベント、そして——注目すべき点として——失敗は例外ではなく**`'error'`イベント**で通知されます。これは wcstack の never-throw 方針と最初から噛み合っています。唯一防御的な`try/catch`が要るのは、権限拒否やPermissions-Policyブロックで**同期的に例外を投げうる**`Magnetometer`のコンストラクタ自体です。
21
+
22
+ > **`@wcstack/permission`との合成を推奨。** `navigator.permissions.query({name:"magnetometer"})`が既に存在するため、`<wcs-magnetometer>`は`<wcs-permission name="magnetometer">`と併置して`granted`/`denied`/`prompt`状態を得てください(権限状態はこのノード自身では重複実装しません、`docs/sensor-tag-design.md`参照)。
23
+
24
+ > **Chromium/Android中心の対応。** デスクトップでは`Magnetometer`クラスが存在しても`SecurityError`になりがちです。unsupported/deniedを既定状態として設計してください。
25
+
26
+ ## インストール
27
+
28
+ ```bash
29
+ npm install @wcstack/magnetometer
30
+ ```
31
+
32
+ ## クイックスタート
33
+
34
+ ### 1. 磁束密度をライブ表示
35
+
36
+ `<wcs-magnetometer>`は接続時に**自動開始しません** — バインドしただけでは
37
+ `x`/`y`/`z`は初期値`null`のままです。読み取りを流すには(例えばボタンから)
38
+ `start`コマンドを発火する必要があります:
39
+
40
+ ```html
41
+ <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
42
+ <script type="module" src="https://esm.run/@wcstack/magnetometer/auto"></script>
43
+
44
+ <wcs-state>
45
+ <script type="module">
46
+ export default {
47
+ $commandTokens: ["startMagnet"],
48
+ x: null, y: null, z: null,
49
+ };
50
+ </script>
51
+ </wcs-state>
52
+
53
+ <wcs-magnetometer
54
+ data-wcs="x: x; y: y; z: z; command.start: $command.startMagnet"
55
+ ></wcs-magnetometer>
56
+
57
+ <button data-wcs="onclick: $command.startMagnet">開始</button>
58
+ <p data-wcs="textContent: x"></p>
59
+ ```
60
+
61
+ ボタンは`<wcs-magnetometer>`に直接触れません: クリックは`startMagnet`コマンドトークンを発火し(`$commandTokens: ["startMagnet"]`で名前を宣言)、`<wcs-magnetometer>`は`command.start: $command.startMagnet`でそれを購読します([command-token プロトコル](../state/) — コマンドメソッドを持つ要素が*subscriber*であり、emitter ではありません)。
62
+
63
+ ### 2. 権限を確認してから start する
64
+
65
+ この例では`@wcstack/permission`の登録も必要です(例1の`@wcstack/state` /
66
+ `@wcstack/magnetometer`の script に加えて)。`magnetGranted`を宣言する
67
+ 独立した`<wcs-state>`を持ちます:
68
+
69
+ ```html
70
+ <script type="module" src="https://esm.run/@wcstack/permission/auto"></script>
71
+
72
+ <wcs-state>
73
+ <script type="module">
74
+ export default {
75
+ $commandTokens: ["startMagnet"],
76
+ magnetGranted: false,
77
+ };
78
+ </script>
79
+ </wcs-state>
80
+
81
+ <wcs-permission name="magnetometer" data-wcs="granted: magnetGranted"></wcs-permission>
82
+ <wcs-magnetometer data-wcs="command.start: $command.startMagnet"></wcs-magnetometer>
83
+
84
+ <button data-wcs="onclick: $command.startMagnet; disabled: magnetGranted|not">開始</button>
85
+ ```
86
+
87
+ バインドする state パスは事前にすべて宣言する必要があります — 未宣言のパスへのバインドは初期化時に例外を投げます。`data-wcs`パス内の否定は先頭`!`ではなく`|not`フィルタ(`magnetGranted|not`)で行います。
88
+
89
+ ## 属性 / 入力
90
+
91
+ | 属性 | 型 | 既定値 | 説明 |
92
+ | ----------- | ------ | ------ | ---- |
93
+ | `frequency` | number | — | サンプリングレート(Hz)。`Magnetometer`コンストラクタへそのまま渡る。読み取られるのは`start()`実行時のみ — 稼働中に変更しても`stop()`+`start()`し直すまで反映されない(注意・制限を参照)。 |
94
+
95
+ ## 観測可能プロパティ(出力)
96
+
97
+ | プロパティ | イベント | 説明 |
98
+ | ---------- | --------------------------- | ---- |
99
+ | `x` | `wcs-magnetometer:reading` | x軸方向の磁束密度。初回読み取り前は`null`。 |
100
+ | `y` | `wcs-magnetometer:reading` | y軸方向の磁束密度。 |
101
+ | `z` | `wcs-magnetometer:reading` | z軸方向の磁束密度。 |
102
+ | `error` | `wcs-magnetometer:error` | 正規化された`{ error, message }`、無ければ`null`。 |
103
+
104
+ `x`/`y`/`z`は単一の`wcs-magnetometer:reading`イベントから派生します(ネイティブの1回の`reading`イベントで3軸が同時に更新される)。
105
+
106
+ ## コマンド
107
+
108
+ | コマンド | 非同期 | 説明 |
109
+ | -------- | ------ | ---- |
110
+ | `start` | いいえ | センサーを構築(never-throw: コンストラクタの同期例外はキャッチし`error`へ)し読み取りを開始する。開始済みの間は冪等(再度呼んでも何もしない)。 |
111
+ | `stop` | いいえ | センサーを停止しリスナーを解除する。未開始でも安全に呼べる。 |
112
+
113
+ ## 注意・制限
114
+
115
+ - **`_gen`世代ガードは無し。** `start()`/`stop()`は同期的な購読/購読解除のトグルであり、`dispose()`とレースしうる非同期probeが存在しません(`docs/sensor-tag-design.md` §1.5)。
116
+ - **`error`は sticky(据え置き)です。** 最後に観測した失敗(`unsupported`、`SecurityError`等)を保持し、その後の`start()`成功や`reading`受信では自動クリアされません。`stop()`+`start()`でリトライが成功しても直前の`error`は残り続けます。必要なら利用側の state でクリア/再解釈してください。
117
+ - **`frequency`は`start()`時にのみ読み取られます。** `attributeChangedCallback`は無く、`start()`は既に開始済みの間は冪等(再度呼んでも何もしない、上記コマンド参照)であるため、稼働中に`frequency`(属性またはプロパティ)を変更しても反映されません。新しいサンプリングレートを適用するには`stop()`してから`start()`し直してください。
118
+ - **再親付け(別の親要素への移動)はセンサーを停止し、自動再開しません。** 接続中の`<wcs-magnetometer>`要素を別の親へ移動すると`disconnectedCallback`→`connectedCallback`が発火します。Shellは接続時に自動開始しないため(上記クイックスタート参照)、これは実質的な停止であり自動再開はされません。`x`/`y`/`z`は最後のサンプル値のまま凍結され、`error`も発生しません — `start`を再度発行するまでセンサーは inert のままです。
119
+ - **生の`new Magnetometer(...)`は唯一のガード付き構築ヘルパー以外では呼ばない。** 権限拒否・Permissions-Policyブロックは同期的に例外を投げます。
120
+ - 権限状態(`granted`/`denied`/`prompt`)は意図的にこのノードでは重複実装していません — `<wcs-permission name="magnetometer">`と合成してください。
121
+
122
+ ## ヘッドレス利用(`MagnetometerCore`)
123
+
124
+ ```typescript
125
+ import { MagnetometerCore } from "@wcstack/magnetometer";
126
+
127
+ const core = new MagnetometerCore();
128
+ core.addEventListener("wcs-magnetometer:reading", (e) => {
129
+ console.log((e as CustomEvent).detail); // { x, y, z }
130
+ });
131
+
132
+ core.start();
133
+ // 後始末:
134
+ core.dispose();
135
+ ```
136
+
137
+ ## ライセンス
138
+
139
+ MIT
package/README.md ADDED
@@ -0,0 +1,142 @@
1
+ # @wcstack/magnetometer
2
+
3
+ `@wcstack/magnetometer` is a headless Generic Sensor API (Magnetometer) component for the wcstack ecosystem.
4
+
5
+ It is not a visual UI widget.
6
+ It is an **async primitive node** that turns device magnetic field readings into reactive state.
7
+
8
+ With `@wcstack/state`, `<wcs-magnetometer>` can be bound directly through path contracts:
9
+
10
+ - **input surface**: `frequency` (sampling rate in Hz)
11
+ - **output state surface**: `x`, `y`, `z`, `error`
12
+
13
+ This means compass/magnetic-field-driven UI can be expressed declaratively in HTML, without writing `Magnetometer`/`reading`/`error`-listener glue in your UI layer.
14
+
15
+ `@wcstack/magnetometer` follows the [CSBC](https://github.com/csbc-dev/arch/blob/main/README.md) (Core / Shell / Binding Contract) architecture:
16
+
17
+ - **Core** (`MagnetometerCore`) constructs the platform `Magnetometer`, tracks its live `reading`/`error` events
18
+ - **Shell** (`<wcs-magnetometer>`) connects that state to DOM lifecycle
19
+ - **Binding Contract** (`static wcBindable`) declares observable `properties` and `start`/`stop` `commands`
20
+
21
+ ## Why this exists — a rare case where the platform API already matches never-throw
22
+
23
+ The Generic Sensor API's `Accelerometer`/`Gyroscope`/`Magnetometer`/`AmbientLightSensor` family all share one base shape: `.start()`/`.stop()`, a `'reading'` event per sample, and — notably — an `'error'` **event** for failures instead of a thrown exception. This already lines up with wcstack's never-throw convention; the one place this Core still needs a defensive `try/catch` is the synchronous `Magnetometer` **constructor** itself, which can throw (`SecurityError`) on permission denial or a Permissions-Policy block.
24
+
25
+ > **Compose with `@wcstack/permission`.** `navigator.permissions.query({name:"magnetometer"})` already exists — pair `<wcs-magnetometer>` with `<wcs-permission name="magnetometer">` for `granted`/`denied`/`prompt` status rather than duplicating that state here (see `docs/sensor-tag-design.md`).
26
+
27
+ > **Chromium/Android-centric support.** Desktop browsers commonly reject with `SecurityError` even when the `Magnetometer` class exists. Design any UI around `unsupported`/denied being the common case, not the exception.
28
+
29
+ ## Install
30
+
31
+ ```bash
32
+ npm install @wcstack/magnetometer
33
+ ```
34
+
35
+ ## Quick Start
36
+
37
+ ### 1. Read live magnetic field
38
+
39
+ `<wcs-magnetometer>` does **not** auto-start on connect — binding alone leaves
40
+ `x`/`y`/`z` at their initial `null`. You must fire the `start` command
41
+ (e.g. from a button) before readings flow:
42
+
43
+ ```html
44
+ <script type="module" src="https://esm.run/@wcstack/state/auto"></script>
45
+ <script type="module" src="https://esm.run/@wcstack/magnetometer/auto"></script>
46
+
47
+ <wcs-state>
48
+ <script type="module">
49
+ export default {
50
+ $commandTokens: ["startMagnet"],
51
+ x: null, y: null, z: null,
52
+ };
53
+ </script>
54
+ </wcs-state>
55
+
56
+ <wcs-magnetometer
57
+ data-wcs="x: x; y: y; z: z; command.start: $command.startMagnet"
58
+ ></wcs-magnetometer>
59
+
60
+ <button data-wcs="onclick: $command.startMagnet">Start</button>
61
+ <p data-wcs="textContent: x"></p>
62
+ ```
63
+
64
+ The button never touches `<wcs-magnetometer>` directly: its click emits the `startMagnet` command token (`$commandTokens: ["startMagnet"]` declares the name), and `<wcs-magnetometer>` subscribes to it via `command.start: $command.startMagnet` (the [command-token protocol](../state/) — the element with the command method is the *subscriber*, not the emitter).
65
+
66
+ ### 2. Gate on permission, then start
67
+
68
+ This example also needs `@wcstack/permission` registered (alongside the
69
+ `@wcstack/state` / `@wcstack/magnetometer` scripts from example 1), with its
70
+ own self-contained `<wcs-state>` declaring `magnetGranted`:
71
+
72
+ ```html
73
+ <script type="module" src="https://esm.run/@wcstack/permission/auto"></script>
74
+
75
+ <wcs-state>
76
+ <script type="module">
77
+ export default {
78
+ $commandTokens: ["startMagnet"],
79
+ magnetGranted: false,
80
+ };
81
+ </script>
82
+ </wcs-state>
83
+
84
+ <wcs-permission name="magnetometer" data-wcs="granted: magnetGranted"></wcs-permission>
85
+ <wcs-magnetometer data-wcs="command.start: $command.startMagnet"></wcs-magnetometer>
86
+
87
+ <button data-wcs="onclick: $command.startMagnet; disabled: magnetGranted|not">Start</button>
88
+ ```
89
+
90
+ Every bound state path must be declared up front — binding an undeclared path throws at initialization. Negation in a `data-wcs` path is done with the `|not` filter (`magnetGranted|not`), not a leading `!`.
91
+
92
+ ## Attributes / Inputs
93
+
94
+ | Attribute | Type | Default | Description |
95
+ | ----------- | ------ | ------- | ------------ |
96
+ | `frequency` | number | — | Sampling rate in Hz, forwarded to the `Magnetometer` constructor. Read only when `start()` runs — changing it while already started has no effect until `stop()` + `start()` (see Notes). |
97
+
98
+ ## Observable Properties (outputs)
99
+
100
+ | Property | Event | Description |
101
+ | -------- | ------------------------- | ------------ |
102
+ | `x` | `wcs-magnetometer:reading` | Magnetic flux density along the x-axis, or `null` before the first reading. |
103
+ | `y` | `wcs-magnetometer:reading` | Magnetic flux density along the y-axis. |
104
+ | `z` | `wcs-magnetometer:reading` | Magnetic flux density along the z-axis. |
105
+ | `error` | `wcs-magnetometer:error` | Normalized `{ error, message }`, or `null`. |
106
+
107
+ `x`/`y`/`z` all derive from the single `wcs-magnetometer:reading` event (one native `reading` event updates all three axes together).
108
+
109
+ ## Commands
110
+
111
+ | Command | Async | Description |
112
+ | ------- | ----- | ------------ |
113
+ | `start` | no | Construct the sensor (never-throw: a synchronous constructor exception is caught and surfaced via `error`) and begin reading. Idempotent while already started (a redundant call is a no-op). |
114
+ | `stop` | no | Stop the sensor and detach its listeners. Safe to call when not started. |
115
+
116
+ ## Notes & limitations
117
+
118
+ - **No `_gen` generation guard.** `start()`/`stop()` are a synchronous subscribe/unsubscribe toggle with no asynchronous probe to race against a `dispose()` — see `docs/sensor-tag-design.md` §1.5.
119
+ - **`error` is sticky.** It holds the last observed failure (e.g. `unsupported`, `SecurityError`) and is **not** auto-cleared by a later successful `start()` or by incoming `reading`s. A `stop()` + `start()` retry that succeeds still leaves the previous `error` in place — clear or reinterpret it in your own state if needed.
120
+ - **`frequency` is read only at `start()`.** There is no `attributeChangedCallback`, and `start()` is idempotent while already started (a redundant call is a no-op — see Commands above), so changing the `frequency` attribute/property on a running sensor has no effect. To apply a new sampling rate, `stop()` then `start()` again.
121
+ - **Reparenting stops the sensor and does not resume it.** Moving a connected `<wcs-magnetometer>` element to a different parent runs `disconnectedCallback` → `connectedCallback`; since the Shell does not auto-start on connect (see Quick Start above), this is effectively a stop with no automatic restart. `x`/`y`/`z` freeze at their last sample, and no `error` is raised — the sensor stays inert until `start` is invoked again.
122
+ - **Never call the raw `new Magnetometer(...)` anywhere but the one guarded construction helper** — permission denial and Permissions-Policy blocks throw synchronously.
123
+ - Permission status (`granted`/`denied`/`prompt`) is intentionally not duplicated here — compose with `<wcs-permission name="magnetometer">`.
124
+
125
+ ## Headless usage (`MagnetometerCore`)
126
+
127
+ ```typescript
128
+ import { MagnetometerCore } from "@wcstack/magnetometer";
129
+
130
+ const core = new MagnetometerCore();
131
+ core.addEventListener("wcs-magnetometer:reading", (e) => {
132
+ console.log((e as CustomEvent).detail); // { x, y, z }
133
+ });
134
+
135
+ core.start();
136
+ // later:
137
+ core.dispose();
138
+ ```
139
+
140
+ ## License
141
+
142
+ MIT
package/dist/auto.js ADDED
@@ -0,0 +1,3 @@
1
+ import { bootstrapMagnetometer } from "./index.esm.js";
2
+
3
+ bootstrapMagnetometer();
@@ -0,0 +1 @@
1
+ import{bootstrapMagnetometer}from"./index.esm.min.js";bootstrapMagnetometer();
@@ -0,0 +1,225 @@
1
+ interface IWcBindableProperty {
2
+ readonly name: string;
3
+ readonly event: string;
4
+ readonly getter?: (event: Event) => any;
5
+ }
6
+ interface IWcBindableInput {
7
+ readonly name: string;
8
+ readonly attribute?: string;
9
+ }
10
+ interface IWcBindableCommand {
11
+ readonly name: string;
12
+ readonly async?: boolean;
13
+ }
14
+ interface IWcBindable {
15
+ readonly protocol: "wc-bindable";
16
+ readonly version: 1;
17
+ readonly properties: readonly IWcBindableProperty[];
18
+ readonly inputs?: readonly IWcBindableInput[];
19
+ readonly commands?: readonly IWcBindableCommand[];
20
+ }
21
+
22
+ interface ITagNames {
23
+ readonly magnetometer: string;
24
+ }
25
+ interface IWritableTagNames {
26
+ magnetometer?: string;
27
+ }
28
+ interface IConfig {
29
+ readonly tagNames: ITagNames;
30
+ }
31
+ interface IWritableConfig {
32
+ tagNames?: IWritableTagNames;
33
+ }
34
+
35
+ /**
36
+ * A single `reading` sample from the Magnetometer sensor: magnetic flux
37
+ * density along the x/y/z axes, in microtesla (µT).
38
+ */
39
+ interface WcsMagnetometerReading {
40
+ x: number | null;
41
+ y: number | null;
42
+ z: number | null;
43
+ }
44
+ /**
45
+ * Error detail published on the `wcs-magnetometer:error` event. Mirrors the
46
+ * Generic Sensor API's `SensorErrorEvent.error` (a `DOMException`-like value)
47
+ * flattened to a plain object, plus the synthetic `"unsupported"` name used
48
+ * when the global `Magnetometer` constructor is absent.
49
+ */
50
+ interface WcsMagnetometerErrorDetail {
51
+ error: string;
52
+ message: string;
53
+ }
54
+ /**
55
+ * Value types for MagnetometerCore (headless) — the observable state
56
+ * properties. Use with `bind()` from a wc-bindable binding core for
57
+ * compile-time type checking.
58
+ *
59
+ * @example
60
+ * ```typescript
61
+ * const core = new MagnetometerCore();
62
+ * bind(core, (name: keyof WcsMagnetometerCoreValues, value) => { ... });
63
+ * ```
64
+ */
65
+ interface WcsMagnetometerCoreValues extends WcsMagnetometerReading {
66
+ error: WcsMagnetometerErrorDetail | null;
67
+ }
68
+ /**
69
+ * Value types for the Shell (`<wcs-magnetometer>`) — identical observable
70
+ * surface to the Core, plus the `frequency` attribute-backed input.
71
+ */
72
+ type WcsMagnetometerValues = WcsMagnetometerCoreValues;
73
+
74
+ declare function bootstrapMagnetometer(userConfig?: IWritableConfig): void;
75
+
76
+ declare function getConfig(): IConfig;
77
+
78
+ /**
79
+ * Headless Magnetometer primitive. A thin, framework-agnostic wrapper around
80
+ * the Generic Sensor API's `Magnetometer` class exposed through the
81
+ * wc-bindable protocol.
82
+ *
83
+ * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /
84
+ * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`
85
+ * event rather than a rejected promise, so this Core can satisfy never-throw
86
+ * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —
87
+ * see docs/sensor-tag-design.md §0. The one place a synchronous
88
+ * exception *can* still escape the platform API is the `Magnetometer`
89
+ * constructor itself (e.g. `SecurityError` on permission denial or a
90
+ * feature-policy block); `_createSensor()` wraps that single call in
91
+ * try/catch, mirroring FetchCore's `_doFetch` try/catch around
92
+ * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).
93
+ *
94
+ * `x`/`y`/`z` are three getters derived from the single `wcs-magnetometer:reading`
95
+ * event (mirroring how NetworkCore exposes effectiveType/downlink/… from one
96
+ * `wcs-network:change` event): the native `reading` event already reports all
97
+ * three axes together, so they are not split into independent events. `reading`
98
+ * is an event-like signal (a fresh sample every time, not a settled state) and
99
+ * is therefore deliberately NOT same-value guarded — every sample dispatches.
100
+ * `error` is state-like (denial / unsupported does not change from tick to
101
+ * tick) and IS same-value guarded, and is published on its own
102
+ * `wcs-magnetometer:error` event, independent of `reading`.
103
+ *
104
+ * No `_gen` generation guard: start()/stop() are a synchronous
105
+ * subscribe/unsubscribe toggle with no asynchronous probe whose stale
106
+ * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5
107
+ * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).
108
+ *
109
+ * Permissions: this Core does not query `navigator.permissions` itself.
110
+ * Compose with `<wcs-permission name="magnetometer">` instead — see
111
+ * docs/sensor-tag-design.md §"2番目の決定: Permissions APIとの合成".
112
+ */
113
+ declare class MagnetometerCore extends EventTarget {
114
+ static wcBindable: IWcBindable;
115
+ private _target;
116
+ private _reading;
117
+ private _error;
118
+ private _sensor;
119
+ constructor(target?: EventTarget);
120
+ get x(): number | null;
121
+ get y(): number | null;
122
+ get z(): number | null;
123
+ get error(): WcsMagnetometerErrorDetail | null;
124
+ /** No asynchronous probe to await: start()/stop() are synchronous
125
+ * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring
126
+ * NetworkCore). */
127
+ get ready(): Promise<void>;
128
+ private _setReading;
129
+ private _setError;
130
+ /**
131
+ * Start the sensor at the given `frequency` (Hz), or the platform default
132
+ * when omitted. Idempotent while already started: a redundant start() does
133
+ * not construct a second sensor instance (which would leak the first).
134
+ * Restart with a different frequency via stop() + start().
135
+ *
136
+ * Synchronous, mirroring the native `Sensor.start()` — never throws
137
+ * (docs/async-io-node-guidelines.md §3.6): both "unsupported" and a
138
+ * synchronous constructor exception (permission denial, feature-policy
139
+ * block) are converted to the `error` property instead of propagating.
140
+ */
141
+ start(frequency?: number): void;
142
+ /** Stop the sensor and detach its listeners. Safe to call when not started. */
143
+ stop(): void;
144
+ /** Lifecycle alias for start(), so the Shell's connectedCallback can drive
145
+ * this Core the same way as other IO nodes' observe()/dispose() pair. No
146
+ * asynchronous probe, so the returned promise always resolves immediately. */
147
+ observe(frequency?: number): Promise<void>;
148
+ /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */
149
+ dispose(): void;
150
+ private _teardownSensor;
151
+ /**
152
+ * Construct the platform `Magnetometer`, guarding both non-support and a
153
+ * synchronous constructor exception. Never calls the raw `new Magnetometer(...)`
154
+ * anywhere else in this class — see docs/sensor-tag-design.md §1.5.
155
+ *
156
+ * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):
157
+ * re-checked on every start(), never cached, so tests can install/remove
158
+ * the global freely and an unsupported environment is always reported
159
+ * correctly.
160
+ */
161
+ private _createSensor;
162
+ private _onReading;
163
+ private _onError;
164
+ }
165
+
166
+ /**
167
+ * `<wcs-magnetometer>` — declarative Generic Sensor API (`Magnetometer`)
168
+ * monitor + start/stop control.
169
+ *
170
+ * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a
171
+ * bidirectional node: `start`/`stop` commands (command-token: state → element)
172
+ * alongside the `x`/`y`/`z`/`error` observable surface (event-token: element →
173
+ * state). The `frequency` attribute is the sole configuration input, forwarded
174
+ * to the platform `Magnetometer` constructor's `{ frequency }` option
175
+ * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or
176
+ * non-positive value (NaN, 0, negative) reads back as `null` — meaning "no
177
+ * frequency specified" — so start() falls back to the platform default rather
178
+ * than forwarding a value the sensor would reject. Any positive finite value is
179
+ * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive
180
+ * rate is still left to the browser/sensor to reject via `error`).
181
+ *
182
+ * Permission handling is intentionally NOT implemented here. Compose with
183
+ * `<wcs-permission name="magnetometer">` instead (see the README's permission
184
+ * example, "Gate on permission, then start", and docs/sensor-tag-design.md).
185
+ */
186
+ declare class WcsMagnetometer extends HTMLElement {
187
+ static hasConnectedCallbackPromise: boolean;
188
+ static wcBindable: IWcBindable;
189
+ private _core;
190
+ private _connectedCallbackPromise;
191
+ constructor();
192
+ /**
193
+ * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the
194
+ * attribute does not parse to a positive finite number (NaN, `"0"`, negative)
195
+ * — in every such "no usable value" case the platform default applies.
196
+ *
197
+ * Note the deliberate set/get asymmetry: `set frequency(0)` (or any
198
+ * non-positive/non-finite value) still writes the attribute verbatim for
199
+ * transparency/inspectability, but the getter normalizes it back to `null`.
200
+ * A round-trip through a non-positive value therefore does NOT preserve it —
201
+ * that value carries no valid sampling meaning, so it is treated as "unset"
202
+ * on read. Only positive finite frequencies survive a set→get round-trip.
203
+ *
204
+ * This value is read only at `start()` time. There is no
205
+ * `attributeChangedCallback`, and `MagnetometerCore.start()` is idempotent
206
+ * while already started (a redundant call is a no-op), so setting
207
+ * `frequency` (attribute or property) on an already-running sensor has no
208
+ * effect until the caller `stop()`s and `start()`s again (see the README's
209
+ * "Notes & limitations").
210
+ */
211
+ get frequency(): number | null;
212
+ set frequency(value: number | null | undefined);
213
+ get x(): number | null;
214
+ get y(): number | null;
215
+ get z(): number | null;
216
+ get error(): WcsMagnetometerErrorDetail | null;
217
+ get connectedCallbackPromise(): Promise<void>;
218
+ start(): void;
219
+ stop(): void;
220
+ connectedCallback(): void;
221
+ disconnectedCallback(): void;
222
+ }
223
+
224
+ export { MagnetometerCore, WcsMagnetometer, bootstrapMagnetometer, getConfig };
225
+ export type { IWritableConfig, IWritableTagNames, WcsMagnetometerCoreValues, WcsMagnetometerErrorDetail, WcsMagnetometerReading, WcsMagnetometerValues };
@@ -0,0 +1,376 @@
1
+ const _config = {
2
+ tagNames: {
3
+ magnetometer: "wcs-magnetometer",
4
+ },
5
+ };
6
+ function deepFreeze(obj) {
7
+ if (obj === null || typeof obj !== "object")
8
+ return obj;
9
+ Object.freeze(obj);
10
+ for (const key of Object.keys(obj)) {
11
+ deepFreeze(obj[key]);
12
+ }
13
+ return obj;
14
+ }
15
+ function deepClone(obj) {
16
+ if (obj === null || typeof obj !== "object")
17
+ return obj;
18
+ const clone = {};
19
+ for (const key of Object.keys(obj)) {
20
+ clone[key] = deepClone(obj[key]);
21
+ }
22
+ return clone;
23
+ }
24
+ let frozenConfig = null;
25
+ const config = _config;
26
+ function getConfig() {
27
+ if (!frozenConfig) {
28
+ frozenConfig = deepFreeze(deepClone(_config));
29
+ }
30
+ return frozenConfig;
31
+ }
32
+ function setConfig(partialConfig) {
33
+ if (partialConfig.tagNames) {
34
+ Object.assign(_config.tagNames, partialConfig.tagNames);
35
+ }
36
+ frozenConfig = null;
37
+ }
38
+
39
+ const NULL_READING = Object.freeze({ x: null, y: null, z: null });
40
+ /**
41
+ * Headless Magnetometer primitive. A thin, framework-agnostic wrapper around
42
+ * the Generic Sensor API's `Magnetometer` class exposed through the
43
+ * wc-bindable protocol.
44
+ *
45
+ * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /
46
+ * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`
47
+ * event rather than a rejected promise, so this Core can satisfy never-throw
48
+ * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —
49
+ * see docs/sensor-tag-design.md §0. The one place a synchronous
50
+ * exception *can* still escape the platform API is the `Magnetometer`
51
+ * constructor itself (e.g. `SecurityError` on permission denial or a
52
+ * feature-policy block); `_createSensor()` wraps that single call in
53
+ * try/catch, mirroring FetchCore's `_doFetch` try/catch around
54
+ * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).
55
+ *
56
+ * `x`/`y`/`z` are three getters derived from the single `wcs-magnetometer:reading`
57
+ * event (mirroring how NetworkCore exposes effectiveType/downlink/… from one
58
+ * `wcs-network:change` event): the native `reading` event already reports all
59
+ * three axes together, so they are not split into independent events. `reading`
60
+ * is an event-like signal (a fresh sample every time, not a settled state) and
61
+ * is therefore deliberately NOT same-value guarded — every sample dispatches.
62
+ * `error` is state-like (denial / unsupported does not change from tick to
63
+ * tick) and IS same-value guarded, and is published on its own
64
+ * `wcs-magnetometer:error` event, independent of `reading`.
65
+ *
66
+ * No `_gen` generation guard: start()/stop() are a synchronous
67
+ * subscribe/unsubscribe toggle with no asynchronous probe whose stale
68
+ * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5
69
+ * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).
70
+ *
71
+ * Permissions: this Core does not query `navigator.permissions` itself.
72
+ * Compose with `<wcs-permission name="magnetometer">` instead — see
73
+ * docs/sensor-tag-design.md §"2番目の決定: Permissions APIとの合成".
74
+ */
75
+ class MagnetometerCore extends EventTarget {
76
+ static wcBindable = {
77
+ protocol: "wc-bindable",
78
+ version: 1,
79
+ properties: [
80
+ { name: "x", event: "wcs-magnetometer:reading", getter: (e) => e.detail.x },
81
+ { name: "y", event: "wcs-magnetometer:reading", getter: (e) => e.detail.y },
82
+ { name: "z", event: "wcs-magnetometer:reading", getter: (e) => e.detail.z },
83
+ { name: "error", event: "wcs-magnetometer:error" },
84
+ ],
85
+ commands: [{ name: "start" }, { name: "stop" }],
86
+ };
87
+ _target;
88
+ _reading = NULL_READING;
89
+ _error = null;
90
+ // The live sensor instance while started (null otherwise), kept so stop()
91
+ // can remove its listeners precisely and so start() can detect "already
92
+ // started" without a separate boolean (docs/async-io-node-guidelines.md
93
+ // §3.5 idempotency).
94
+ _sensor = null;
95
+ constructor(target) {
96
+ super();
97
+ this._target = target ?? this;
98
+ }
99
+ get x() {
100
+ return this._reading.x;
101
+ }
102
+ get y() {
103
+ return this._reading.y;
104
+ }
105
+ get z() {
106
+ return this._reading.z;
107
+ }
108
+ get error() {
109
+ return this._error;
110
+ }
111
+ /** No asynchronous probe to await: start()/stop() are synchronous
112
+ * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring
113
+ * NetworkCore). */
114
+ get ready() {
115
+ return Promise.resolve();
116
+ }
117
+ // --- State setters ---
118
+ // Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a
119
+ // settled state, so it must dispatch every time even when the values happen
120
+ // to repeat (docs/sensor-tag-design.md §1.1).
121
+ _setReading(reading) {
122
+ this._reading = reading;
123
+ this._target.dispatchEvent(new CustomEvent("wcs-magnetometer:reading", {
124
+ detail: reading,
125
+ bubbles: true,
126
+ }));
127
+ }
128
+ _setError(error) {
129
+ // Same-value guard (by error name + message): error is state-like, unlike
130
+ // reading — a repeated identical error (same name and message) must not
131
+ // redispatch. Note `error` is also STICKY: nothing calls _setError(null),
132
+ // so a successful (re)start does not clear a prior failure — the monitoring
133
+ // sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).
134
+ if (this._error?.error === error?.error && this._error?.message === error?.message)
135
+ return;
136
+ this._error = error;
137
+ this._target.dispatchEvent(new CustomEvent("wcs-magnetometer:error", {
138
+ detail: error,
139
+ bubbles: true,
140
+ }));
141
+ }
142
+ // --- Public API ---
143
+ /**
144
+ * Start the sensor at the given `frequency` (Hz), or the platform default
145
+ * when omitted. Idempotent while already started: a redundant start() does
146
+ * not construct a second sensor instance (which would leak the first).
147
+ * Restart with a different frequency via stop() + start().
148
+ *
149
+ * Synchronous, mirroring the native `Sensor.start()` — never throws
150
+ * (docs/async-io-node-guidelines.md §3.6): both "unsupported" and a
151
+ * synchronous constructor exception (permission denial, feature-policy
152
+ * block) are converted to the `error` property instead of propagating.
153
+ */
154
+ start(frequency) {
155
+ if (this._sensor)
156
+ return;
157
+ const sensor = this._createSensor(frequency);
158
+ if (!sensor)
159
+ return;
160
+ sensor.addEventListener("reading", this._onReading);
161
+ sensor.addEventListener("error", this._onError);
162
+ this._sensor = sensor;
163
+ try {
164
+ sensor.start();
165
+ }
166
+ catch (e) {
167
+ // Defensive: the platform contract says start()/stop() do not throw
168
+ // (failures surface via the 'error' event), but never-throw is a hard
169
+ // requirement here, so guard against a non-conformant implementation
170
+ // too.
171
+ this._teardownSensor();
172
+ this._setError({ error: e?.name ?? "error", message: e?.message ?? String(e) });
173
+ }
174
+ }
175
+ /** Stop the sensor and detach its listeners. Safe to call when not started. */
176
+ stop() {
177
+ if (!this._sensor)
178
+ return;
179
+ try {
180
+ this._sensor.stop();
181
+ }
182
+ catch {
183
+ // Never-throw defensive guard, symmetric with start(). Teardown below
184
+ // still runs so listeners are detached regardless.
185
+ }
186
+ this._teardownSensor();
187
+ }
188
+ /** Lifecycle alias for start(), so the Shell's connectedCallback can drive
189
+ * this Core the same way as other IO nodes' observe()/dispose() pair. No
190
+ * asynchronous probe, so the returned promise always resolves immediately. */
191
+ observe(frequency) {
192
+ this.start(frequency);
193
+ return this.ready;
194
+ }
195
+ /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */
196
+ dispose() {
197
+ this.stop();
198
+ }
199
+ // --- Internal ---
200
+ // Both call sites (start()'s catch, stop()) only ever invoke this once
201
+ // `this._sensor` is already known non-null, so there is no null-guard here
202
+ // (nothing to defend against).
203
+ _teardownSensor() {
204
+ this._sensor.removeEventListener("reading", this._onReading);
205
+ this._sensor.removeEventListener("error", this._onError);
206
+ this._sensor = null;
207
+ }
208
+ /**
209
+ * Construct the platform `Magnetometer`, guarding both non-support and a
210
+ * synchronous constructor exception. Never calls the raw `new Magnetometer(...)`
211
+ * anywhere else in this class — see docs/sensor-tag-design.md §1.5.
212
+ *
213
+ * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):
214
+ * re-checked on every start(), never cached, so tests can install/remove
215
+ * the global freely and an unsupported environment is always reported
216
+ * correctly.
217
+ */
218
+ _createSensor(frequency) {
219
+ const Ctor = globalThis.Magnetometer;
220
+ if (typeof Ctor !== "function") {
221
+ this._setError({ error: "unsupported", message: "Magnetometer is not supported" });
222
+ return null;
223
+ }
224
+ try {
225
+ return new Ctor(frequency !== undefined ? { frequency } : undefined);
226
+ }
227
+ catch (e) {
228
+ // SecurityError (permission denial, feature-policy block) or any other
229
+ // synchronous construction failure. Mirrors the FetchCore._doFetch
230
+ // try/catch structure (packages/fetch/src/core/FetchCore.ts) — a
231
+ // synchronous constructor call here instead of an awaited fetch().
232
+ this._setError({ error: e?.name ?? "error", message: e?.message ?? String(e) });
233
+ return null;
234
+ }
235
+ }
236
+ _onReading = (event) => {
237
+ const sensor = event.target;
238
+ this._setReading({ x: sensor.x, y: sensor.y, z: sensor.z });
239
+ };
240
+ _onError = (event) => {
241
+ const err = event.error;
242
+ // Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent
243
+ // without an `error` field would otherwise stringify `undefined` into the
244
+ // literal message "undefined" (aligned across the sensor family).
245
+ this._setError({ error: err?.name ?? "error", message: err?.message ?? "Sensor error" });
246
+ };
247
+ }
248
+
249
+ /**
250
+ * `<wcs-magnetometer>` — declarative Generic Sensor API (`Magnetometer`)
251
+ * monitor + start/stop control.
252
+ *
253
+ * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a
254
+ * bidirectional node: `start`/`stop` commands (command-token: state → element)
255
+ * alongside the `x`/`y`/`z`/`error` observable surface (event-token: element →
256
+ * state). The `frequency` attribute is the sole configuration input, forwarded
257
+ * to the platform `Magnetometer` constructor's `{ frequency }` option
258
+ * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or
259
+ * non-positive value (NaN, 0, negative) reads back as `null` — meaning "no
260
+ * frequency specified" — so start() falls back to the platform default rather
261
+ * than forwarding a value the sensor would reject. Any positive finite value is
262
+ * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive
263
+ * rate is still left to the browser/sensor to reject via `error`).
264
+ *
265
+ * Permission handling is intentionally NOT implemented here. Compose with
266
+ * `<wcs-permission name="magnetometer">` instead (see the README's permission
267
+ * example, "Gate on permission, then start", and docs/sensor-tag-design.md).
268
+ */
269
+ class WcsMagnetometer extends HTMLElement {
270
+ static hasConnectedCallbackPromise = true;
271
+ static wcBindable = {
272
+ ...MagnetometerCore.wcBindable,
273
+ inputs: [{ name: "frequency" }],
274
+ // Core の commands をそのまま継承(単一情報源)。
275
+ commands: MagnetometerCore.wcBindable.commands,
276
+ };
277
+ _core;
278
+ _connectedCallbackPromise = Promise.resolve();
279
+ constructor() {
280
+ super();
281
+ this._core = new MagnetometerCore(this);
282
+ }
283
+ // --- Attribute accessors ---
284
+ /**
285
+ * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the
286
+ * attribute does not parse to a positive finite number (NaN, `"0"`, negative)
287
+ * — in every such "no usable value" case the platform default applies.
288
+ *
289
+ * Note the deliberate set/get asymmetry: `set frequency(0)` (or any
290
+ * non-positive/non-finite value) still writes the attribute verbatim for
291
+ * transparency/inspectability, but the getter normalizes it back to `null`.
292
+ * A round-trip through a non-positive value therefore does NOT preserve it —
293
+ * that value carries no valid sampling meaning, so it is treated as "unset"
294
+ * on read. Only positive finite frequencies survive a set→get round-trip.
295
+ *
296
+ * This value is read only at `start()` time. There is no
297
+ * `attributeChangedCallback`, and `MagnetometerCore.start()` is idempotent
298
+ * while already started (a redundant call is a no-op), so setting
299
+ * `frequency` (attribute or property) on an already-running sensor has no
300
+ * effect until the caller `stop()`s and `start()`s again (see the README's
301
+ * "Notes & limitations").
302
+ */
303
+ get frequency() {
304
+ const attr = this.getAttribute("frequency");
305
+ if (attr === null || attr.trim() === "")
306
+ return null;
307
+ const parsed = Number(attr);
308
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : null;
309
+ }
310
+ set frequency(value) {
311
+ if (value === null || value === undefined) {
312
+ this.removeAttribute("frequency");
313
+ }
314
+ else {
315
+ this.setAttribute("frequency", String(value));
316
+ }
317
+ }
318
+ // --- Core delegated getters ---
319
+ get x() {
320
+ return this._core.x;
321
+ }
322
+ get y() {
323
+ return this._core.y;
324
+ }
325
+ get z() {
326
+ return this._core.z;
327
+ }
328
+ get error() {
329
+ return this._core.error;
330
+ }
331
+ get connectedCallbackPromise() {
332
+ return this._connectedCallbackPromise;
333
+ }
334
+ // --- Commands ---
335
+ start() {
336
+ this._core.start(this.frequency ?? undefined);
337
+ }
338
+ stop() {
339
+ this._core.stop();
340
+ }
341
+ // --- Lifecycle ---
342
+ // Deliberately does NOT auto-start the sensor on connect. Unlike
343
+ // Geolocation (whose default phase acquires a fix immediately unless
344
+ // `manual` is set), Magnetometer has no such "connect implies observing"
345
+ // precedent in the design doc (docs/sensor-tag-design.md §1.3):
346
+ // start/stop are the only commands, so connecting the element merely makes
347
+ // it inert until a command-token `start` (or the `start()` method) is
348
+ // invoked. This also keeps behavior predictable when composed with
349
+ // `<wcs-permission name="magnetometer">`: the caller decides when to start,
350
+ // typically gated on `granted`.
351
+ connectedCallback() {
352
+ this.style.display = "none";
353
+ // No asynchronous probe to await (docs/async-io-node-guidelines.md §3.8);
354
+ // kept for SSR uniformity with other IO nodes.
355
+ this._connectedCallbackPromise = this._core.ready;
356
+ }
357
+ disconnectedCallback() {
358
+ this._core.dispose();
359
+ }
360
+ }
361
+
362
+ function registerComponents() {
363
+ if (!customElements.get(config.tagNames.magnetometer)) {
364
+ customElements.define(config.tagNames.magnetometer, WcsMagnetometer);
365
+ }
366
+ }
367
+
368
+ function bootstrapMagnetometer(userConfig) {
369
+ if (userConfig) {
370
+ setConfig(userConfig);
371
+ }
372
+ registerComponents();
373
+ }
374
+
375
+ export { MagnetometerCore, WcsMagnetometer, bootstrapMagnetometer, getConfig };
376
+ //# sourceMappingURL=index.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.js","sources":["../src/config.ts","../src/core/MagnetometerCore.ts","../src/components/Magnetometer.ts","../src/registerComponents.ts","../src/bootstrapMagnetometer.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n tagNames: {\n magnetometer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n tagNames: {\n magnetometer: \"wcs-magnetometer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsMagnetometerReading, WcsMagnetometerErrorDetail } from \"../types.js\";\n\nconst NULL_READING: WcsMagnetometerReading = Object.freeze({ x: null, y: null, z: null });\n\n/**\n * Headless Magnetometer primitive. A thin, framework-agnostic wrapper around\n * the Generic Sensor API's `Magnetometer` class exposed through the\n * wc-bindable protocol.\n *\n * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /\n * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`\n * event rather than a rejected promise, so this Core can satisfy never-throw\n * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —\n * see docs/sensor-tag-design.md §0. The one place a synchronous\n * exception *can* still escape the platform API is the `Magnetometer`\n * constructor itself (e.g. `SecurityError` on permission denial or a\n * feature-policy block); `_createSensor()` wraps that single call in\n * try/catch, mirroring FetchCore's `_doFetch` try/catch around\n * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).\n *\n * `x`/`y`/`z` are three getters derived from the single `wcs-magnetometer:reading`\n * event (mirroring how NetworkCore exposes effectiveType/downlink/… from one\n * `wcs-network:change` event): the native `reading` event already reports all\n * three axes together, so they are not split into independent events. `reading`\n * is an event-like signal (a fresh sample every time, not a settled state) and\n * is therefore deliberately NOT same-value guarded — every sample dispatches.\n * `error` is state-like (denial / unsupported does not change from tick to\n * tick) and IS same-value guarded, and is published on its own\n * `wcs-magnetometer:error` event, independent of `reading`.\n *\n * No `_gen` generation guard: start()/stop() are a synchronous\n * subscribe/unsubscribe toggle with no asynchronous probe whose stale\n * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5\n * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).\n *\n * Permissions: this Core does not query `navigator.permissions` itself.\n * Compose with `<wcs-permission name=\"magnetometer\">` instead — see\n * docs/sensor-tag-design.md §\"2番目の決定: Permissions APIとの合成\".\n */\nexport class MagnetometerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"x\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.x },\n { name: \"y\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.y },\n { name: \"z\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.z },\n { name: \"error\", event: \"wcs-magnetometer:error\" },\n ],\n commands: [{ name: \"start\" }, { name: \"stop\" }],\n };\n\n private _target: EventTarget;\n private _reading: WcsMagnetometerReading = NULL_READING;\n private _error: WcsMagnetometerErrorDetail | null = null;\n\n // The live sensor instance while started (null otherwise), kept so stop()\n // can remove its listeners precisely and so start() can detect \"already\n // started\" without a separate boolean (docs/async-io-node-guidelines.md\n // §3.5 idempotency).\n private _sensor: (EventTarget & { start(): void; stop(): void }) | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get x(): number | null {\n return this._reading.x;\n }\n\n get y(): number | null {\n return this._reading.y;\n }\n\n get z(): number | null {\n return this._reading.z;\n }\n\n get error(): WcsMagnetometerErrorDetail | null {\n return this._error;\n }\n\n /** No asynchronous probe to await: start()/stop() are synchronous\n * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring\n * NetworkCore). */\n get ready(): Promise<void> {\n return Promise.resolve();\n }\n\n // --- State setters ---\n\n // Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a\n // settled state, so it must dispatch every time even when the values happen\n // to repeat (docs/sensor-tag-design.md §1.1).\n private _setReading(reading: WcsMagnetometerReading): void {\n this._reading = reading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-magnetometer:reading\", {\n detail: reading,\n bubbles: true,\n }));\n }\n\n private _setError(error: WcsMagnetometerErrorDetail | null): void {\n // Same-value guard (by error name + message): error is state-like, unlike\n // reading — a repeated identical error (same name and message) must not\n // redispatch. Note `error` is also STICKY: nothing calls _setError(null),\n // so a successful (re)start does not clear a prior failure — the monitoring\n // sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).\n if (this._error?.error === error?.error && this._error?.message === error?.message) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-magnetometer:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Start the sensor at the given `frequency` (Hz), or the platform default\n * when omitted. Idempotent while already started: a redundant start() does\n * not construct a second sensor instance (which would leak the first).\n * Restart with a different frequency via stop() + start().\n *\n * Synchronous, mirroring the native `Sensor.start()` — never throws\n * (docs/async-io-node-guidelines.md §3.6): both \"unsupported\" and a\n * synchronous constructor exception (permission denial, feature-policy\n * block) are converted to the `error` property instead of propagating.\n */\n start(frequency?: number): void {\n if (this._sensor) return;\n const sensor = this._createSensor(frequency);\n if (!sensor) return;\n sensor.addEventListener(\"reading\", this._onReading as EventListener);\n sensor.addEventListener(\"error\", this._onError as EventListener);\n this._sensor = sensor;\n try {\n sensor.start();\n } catch (e: any) {\n // Defensive: the platform contract says start()/stop() do not throw\n // (failures surface via the 'error' event), but never-throw is a hard\n // requirement here, so guard against a non-conformant implementation\n // too.\n this._teardownSensor();\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n }\n }\n\n /** Stop the sensor and detach its listeners. Safe to call when not started. */\n stop(): void {\n if (!this._sensor) return;\n try {\n this._sensor.stop();\n } catch {\n // Never-throw defensive guard, symmetric with start(). Teardown below\n // still runs so listeners are detached regardless.\n }\n this._teardownSensor();\n }\n\n /** Lifecycle alias for start(), so the Shell's connectedCallback can drive\n * this Core the same way as other IO nodes' observe()/dispose() pair. No\n * asynchronous probe, so the returned promise always resolves immediately. */\n observe(frequency?: number): Promise<void> {\n this.start(frequency);\n return this.ready;\n }\n\n /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */\n dispose(): void {\n this.stop();\n }\n\n // --- Internal ---\n\n // Both call sites (start()'s catch, stop()) only ever invoke this once\n // `this._sensor` is already known non-null, so there is no null-guard here\n // (nothing to defend against).\n private _teardownSensor(): void {\n this._sensor!.removeEventListener(\"reading\", this._onReading as EventListener);\n this._sensor!.removeEventListener(\"error\", this._onError as EventListener);\n this._sensor = null;\n }\n\n /**\n * Construct the platform `Magnetometer`, guarding both non-support and a\n * synchronous constructor exception. Never calls the raw `new Magnetometer(...)`\n * anywhere else in this class — see docs/sensor-tag-design.md §1.5.\n *\n * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):\n * re-checked on every start(), never cached, so tests can install/remove\n * the global freely and an unsupported environment is always reported\n * correctly.\n */\n private _createSensor(frequency?: number): (EventTarget & { start(): void; stop(): void }) | null {\n const Ctor = (globalThis as any).Magnetometer;\n if (typeof Ctor !== \"function\") {\n this._setError({ error: \"unsupported\", message: \"Magnetometer is not supported\" });\n return null;\n }\n try {\n return new Ctor(frequency !== undefined ? { frequency } : undefined);\n } catch (e: any) {\n // SecurityError (permission denial, feature-policy block) or any other\n // synchronous construction failure. Mirrors the FetchCore._doFetch\n // try/catch structure (packages/fetch/src/core/FetchCore.ts) — a\n // synchronous constructor call here instead of an awaited fetch().\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n return null;\n }\n }\n\n private _onReading = (event: Event): void => {\n const sensor = event.target as unknown as { x: number | null; y: number | null; z: number | null };\n this._setReading({ x: sensor.x, y: sensor.y, z: sensor.z });\n };\n\n private _onError = (event: Event): void => {\n const err = (event as any).error as { name?: string; message?: string } | undefined;\n // Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent\n // without an `error` field would otherwise stringify `undefined` into the\n // literal message \"undefined\" (aligned across the sensor family).\n this._setError({ error: err?.name ?? \"error\", message: err?.message ?? \"Sensor error\" });\n };\n}\n","import { IWcBindable, WcsMagnetometerErrorDetail } from \"../types.js\";\nimport { MagnetometerCore } from \"../core/MagnetometerCore.js\";\n\n/**\n * `<wcs-magnetometer>` — declarative Generic Sensor API (`Magnetometer`)\n * monitor + start/stop control.\n *\n * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a\n * bidirectional node: `start`/`stop` commands (command-token: state → element)\n * alongside the `x`/`y`/`z`/`error` observable surface (event-token: element →\n * state). The `frequency` attribute is the sole configuration input, forwarded\n * to the platform `Magnetometer` constructor's `{ frequency }` option\n * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or\n * non-positive value (NaN, 0, negative) reads back as `null` — meaning \"no\n * frequency specified\" — so start() falls back to the platform default rather\n * than forwarding a value the sensor would reject. Any positive finite value is\n * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive\n * rate is still left to the browser/sensor to reject via `error`).\n *\n * Permission handling is intentionally NOT implemented here. Compose with\n * `<wcs-permission name=\"magnetometer\">` instead (see the README's permission\n * example, \"Gate on permission, then start\", and docs/sensor-tag-design.md).\n */\nexport class WcsMagnetometer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n\n static wcBindable: IWcBindable = {\n ...MagnetometerCore.wcBindable,\n inputs: [{ name: \"frequency\" }],\n // Core の commands をそのまま継承(単一情報源)。\n commands: MagnetometerCore.wcBindable.commands,\n };\n\n private _core: MagnetometerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new MagnetometerCore(this);\n }\n\n // --- Attribute accessors ---\n\n /**\n * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the\n * attribute does not parse to a positive finite number (NaN, `\"0\"`, negative)\n * — in every such \"no usable value\" case the platform default applies.\n *\n * Note the deliberate set/get asymmetry: `set frequency(0)` (or any\n * non-positive/non-finite value) still writes the attribute verbatim for\n * transparency/inspectability, but the getter normalizes it back to `null`.\n * A round-trip through a non-positive value therefore does NOT preserve it —\n * that value carries no valid sampling meaning, so it is treated as \"unset\"\n * on read. Only positive finite frequencies survive a set→get round-trip.\n *\n * This value is read only at `start()` time. There is no\n * `attributeChangedCallback`, and `MagnetometerCore.start()` is idempotent\n * while already started (a redundant call is a no-op), so setting\n * `frequency` (attribute or property) on an already-running sensor has no\n * effect until the caller `stop()`s and `start()`s again (see the README's\n * \"Notes & limitations\").\n */\n get frequency(): number | null {\n const attr = this.getAttribute(\"frequency\");\n if (attr === null || attr.trim() === \"\") return null;\n const parsed = Number(attr);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n }\n\n set frequency(value: number | null | undefined) {\n if (value === null || value === undefined) {\n this.removeAttribute(\"frequency\");\n } else {\n this.setAttribute(\"frequency\", String(value));\n }\n }\n\n // --- Core delegated getters ---\n\n get x(): number | null {\n return this._core.x;\n }\n\n get y(): number | null {\n return this._core.y;\n }\n\n get z(): number | null {\n return this._core.z;\n }\n\n get error(): WcsMagnetometerErrorDetail | null {\n return this._core.error;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Commands ---\n\n start(): void {\n this._core.start(this.frequency ?? undefined);\n }\n\n stop(): void {\n this._core.stop();\n }\n\n // --- Lifecycle ---\n\n // Deliberately does NOT auto-start the sensor on connect. Unlike\n // Geolocation (whose default phase acquires a fix immediately unless\n // `manual` is set), Magnetometer has no such \"connect implies observing\"\n // precedent in the design doc (docs/sensor-tag-design.md §1.3):\n // start/stop are the only commands, so connecting the element merely makes\n // it inert until a command-token `start` (or the `start()` method) is\n // invoked. This also keeps behavior predictable when composed with\n // `<wcs-permission name=\"magnetometer\">`: the caller decides when to start,\n // typically gated on `granted`.\n connectedCallback(): void {\n this.style.display = \"none\";\n // No asynchronous probe to await (docs/async-io-node-guidelines.md §3.8);\n // kept for SSR uniformity with other IO nodes.\n this._connectedCallbackPromise = this._core.ready;\n }\n\n disconnectedCallback(): void {\n this._core.dispose();\n }\n}\n","import { WcsMagnetometer } from \"./components/Magnetometer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.magnetometer)) {\n customElements.define(config.tagNames.magnetometer, WcsMagnetometer);\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapMagnetometer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n"],"names":[],"mappings":"AAQA,MAAM,OAAO,GAAoB;AAC/B,IAAA,QAAQ,EAAE;AACR,QAAA,YAAY,EAAE,kBAAkB;AACjC,KAAA;CACF;AAED,SAAS,UAAU,CAAI,GAAM,EAAA;AAC3B,IAAA,IAAI,GAAG,KAAK,IAAI,IAAI,OAAO,GAAG,KAAK,QAAQ;AAAE,QAAA,OAAO,GAAG;AACvD,IAAA,MAAM,CAAC,MAAM,CAAC,GAAG,CAAC;IAClB,KAAK,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE;AAClC,QAAA,UAAU,CAAE,GAA+B,CAAC,GAAG,CAAC,CAAC;IACnD;AACA,IAAA,OAAO,GAAG;AACZ;AAEA,SAAS,SAAS,CAAI,GAAM,EAAA;AAC1B,IAAA,IAAI,GAAG,KAAK,IAAI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CAAC,YAAY,EAAE,eAAe,CAAC;IACtE;AACF;;ACHM,SAAU,qBAAqB,CAAC,UAA4B,EAAA;IAChE,IAAI,UAAU,EAAE;QACd,SAAS,CAAC,UAAU,CAAC;IACvB;AACA,IAAA,kBAAkB,EAAE;AACtB;;;;"}
@@ -0,0 +1,2 @@
1
+ const e={tagNames:{magnetometer:"wcs-magnetometer"}};function t(e){if(null===e||"object"!=typeof e)return e;Object.freeze(e);for(const r of Object.keys(e))t(e[r]);return e}function r(e){if(null===e||"object"!=typeof e)return e;const t={};for(const s of Object.keys(e))t[s]=r(e[s]);return t}let s=null;const n=e;function o(){return s||(s=t(r(e))),s}const i=Object.freeze({x:null,y:null,z:null});class a extends EventTarget{static wcBindable={protocol:"wc-bindable",version:1,properties:[{name:"x",event:"wcs-magnetometer:reading",getter:e=>e.detail.x},{name:"y",event:"wcs-magnetometer:reading",getter:e=>e.detail.y},{name:"z",event:"wcs-magnetometer:reading",getter:e=>e.detail.z},{name:"error",event:"wcs-magnetometer:error"}],commands:[{name:"start"},{name:"stop"}]};_target;_reading=i;_error=null;_sensor=null;constructor(e){super(),this._target=e??this}get x(){return this._reading.x}get y(){return this._reading.y}get z(){return this._reading.z}get error(){return this._error}get ready(){return Promise.resolve()}_setReading(e){this._reading=e,this._target.dispatchEvent(new CustomEvent("wcs-magnetometer:reading",{detail:e,bubbles:!0}))}_setError(e){this._error?.error===e?.error&&this._error?.message===e?.message||(this._error=e,this._target.dispatchEvent(new CustomEvent("wcs-magnetometer:error",{detail:e,bubbles:!0})))}start(e){if(this._sensor)return;const t=this._createSensor(e);if(t){t.addEventListener("reading",this._onReading),t.addEventListener("error",this._onError),this._sensor=t;try{t.start()}catch(e){this._teardownSensor(),this._setError({error:e?.name??"error",message:e?.message??String(e)})}}}stop(){if(this._sensor){try{this._sensor.stop()}catch{}this._teardownSensor()}}observe(e){return this.start(e),this.ready}dispose(){this.stop()}_teardownSensor(){this._sensor.removeEventListener("reading",this._onReading),this._sensor.removeEventListener("error",this._onError),this._sensor=null}_createSensor(e){const t=globalThis.Magnetometer;if("function"!=typeof t)return this._setError({error:"unsupported",message:"Magnetometer is not supported"}),null;try{return new t(void 0!==e?{frequency:e}:void 0)}catch(e){return this._setError({error:e?.name??"error",message:e?.message??String(e)}),null}}_onReading=e=>{const t=e.target;this._setReading({x:t.x,y:t.y,z:t.z})};_onError=e=>{const t=e.error;this._setError({error:t?.name??"error",message:t?.message??"Sensor error"})}}class c extends HTMLElement{static hasConnectedCallbackPromise=!0;static wcBindable={...a.wcBindable,inputs:[{name:"frequency"}],commands:a.wcBindable.commands};_core;_connectedCallbackPromise=Promise.resolve();constructor(){super(),this._core=new a(this)}get frequency(){const e=this.getAttribute("frequency");if(null===e||""===e.trim())return null;const t=Number(e);return Number.isFinite(t)&&t>0?t:null}set frequency(e){null==e?this.removeAttribute("frequency"):this.setAttribute("frequency",String(e))}get x(){return this._core.x}get y(){return this._core.y}get z(){return this._core.z}get error(){return this._core.error}get connectedCallbackPromise(){return this._connectedCallbackPromise}start(){this._core.start(this.frequency??void 0)}stop(){this._core.stop()}connectedCallback(){this.style.display="none",this._connectedCallbackPromise=this._core.ready}disconnectedCallback(){this._core.dispose()}}function m(t){var r;t&&((r=t).tagNames&&Object.assign(e.tagNames,r.tagNames),s=null),customElements.get(n.tagNames.magnetometer)||customElements.define(n.tagNames.magnetometer,c)}export{a as MagnetometerCore,c as WcsMagnetometer,m as bootstrapMagnetometer,o as getConfig};
2
+ //# sourceMappingURL=index.esm.min.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.esm.min.js","sources":["../src/config.ts","../src/core/MagnetometerCore.ts","../src/components/Magnetometer.ts","../src/bootstrapMagnetometer.ts","../src/registerComponents.ts"],"sourcesContent":["import { IConfig, IWritableConfig } from \"./types.js\";\n\ninterface IInternalConfig extends IConfig {\n tagNames: {\n magnetometer: string;\n };\n}\n\nconst _config: IInternalConfig = {\n tagNames: {\n magnetometer: \"wcs-magnetometer\",\n },\n};\n\nfunction deepFreeze<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n Object.freeze(obj);\n for (const key of Object.keys(obj)) {\n deepFreeze((obj as Record<string, unknown>)[key]);\n }\n return obj;\n}\n\nfunction deepClone<T>(obj: T): T {\n if (obj === null || typeof obj !== \"object\") return obj;\n const clone: Record<string, unknown> = {};\n for (const key of Object.keys(obj)) {\n clone[key] = deepClone((obj as Record<string, unknown>)[key]);\n }\n return clone as T;\n}\n\nlet frozenConfig: IConfig | null = null;\n\nexport const config: IConfig = _config as IConfig;\n\nexport function getConfig(): IConfig {\n if (!frozenConfig) {\n frozenConfig = deepFreeze(deepClone(_config));\n }\n return frozenConfig;\n}\n\nexport function setConfig(partialConfig: IWritableConfig): void {\n if (partialConfig.tagNames) {\n Object.assign(_config.tagNames, partialConfig.tagNames);\n }\n frozenConfig = null;\n}\n","import { IWcBindable, WcsMagnetometerReading, WcsMagnetometerErrorDetail } from \"../types.js\";\n\nconst NULL_READING: WcsMagnetometerReading = Object.freeze({ x: null, y: null, z: null });\n\n/**\n * Headless Magnetometer primitive. A thin, framework-agnostic wrapper around\n * the Generic Sensor API's `Magnetometer` class exposed through the\n * wc-bindable protocol.\n *\n * The platform `Sensor` base class (shared by `Accelerometer` / `Gyroscope` /\n * `Magnetometer` / `AmbientLightSensor`) reports failure through an `'error'`\n * event rather than a rejected promise, so this Core can satisfy never-throw\n * (docs/async-io-node-guidelines.md §3.6) by simply forwarding that event —\n * see docs/sensor-tag-design.md §0. The one place a synchronous\n * exception *can* still escape the platform API is the `Magnetometer`\n * constructor itself (e.g. `SecurityError` on permission denial or a\n * feature-policy block); `_createSensor()` wraps that single call in\n * try/catch, mirroring FetchCore's `_doFetch` try/catch around\n * `globalThis.fetch` (packages/fetch/src/core/FetchCore.ts).\n *\n * `x`/`y`/`z` are three getters derived from the single `wcs-magnetometer:reading`\n * event (mirroring how NetworkCore exposes effectiveType/downlink/… from one\n * `wcs-network:change` event): the native `reading` event already reports all\n * three axes together, so they are not split into independent events. `reading`\n * is an event-like signal (a fresh sample every time, not a settled state) and\n * is therefore deliberately NOT same-value guarded — every sample dispatches.\n * `error` is state-like (denial / unsupported does not change from tick to\n * tick) and IS same-value guarded, and is published on its own\n * `wcs-magnetometer:error` event, independent of `reading`.\n *\n * No `_gen` generation guard: start()/stop() are a synchronous\n * subscribe/unsubscribe toggle with no asynchronous probe whose stale\n * resolution could race a dispose() — see docs/sensor-tag-design.md §1.5\n * (the same reasoning as NetworkCore, docs/network-tag-design.md §5).\n *\n * Permissions: this Core does not query `navigator.permissions` itself.\n * Compose with `<wcs-permission name=\"magnetometer\">` instead — see\n * docs/sensor-tag-design.md §\"2番目の決定: Permissions APIとの合成\".\n */\nexport class MagnetometerCore extends EventTarget {\n static wcBindable: IWcBindable = {\n protocol: \"wc-bindable\",\n version: 1,\n properties: [\n { name: \"x\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.x },\n { name: \"y\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.y },\n { name: \"z\", event: \"wcs-magnetometer:reading\", getter: (e: Event) => (e as CustomEvent).detail.z },\n { name: \"error\", event: \"wcs-magnetometer:error\" },\n ],\n commands: [{ name: \"start\" }, { name: \"stop\" }],\n };\n\n private _target: EventTarget;\n private _reading: WcsMagnetometerReading = NULL_READING;\n private _error: WcsMagnetometerErrorDetail | null = null;\n\n // The live sensor instance while started (null otherwise), kept so stop()\n // can remove its listeners precisely and so start() can detect \"already\n // started\" without a separate boolean (docs/async-io-node-guidelines.md\n // §3.5 idempotency).\n private _sensor: (EventTarget & { start(): void; stop(): void }) | null = null;\n\n constructor(target?: EventTarget) {\n super();\n this._target = target ?? this;\n }\n\n get x(): number | null {\n return this._reading.x;\n }\n\n get y(): number | null {\n return this._reading.y;\n }\n\n get z(): number | null {\n return this._reading.z;\n }\n\n get error(): WcsMagnetometerErrorDetail | null {\n return this._error;\n }\n\n /** No asynchronous probe to await: start()/stop() are synchronous\n * (docs/async-io-node-guidelines.md §3.8 is satisfied trivially, mirroring\n * NetworkCore). */\n get ready(): Promise<void> {\n return Promise.resolve();\n }\n\n // --- State setters ---\n\n // Deliberately NOT same-value guarded: a `reading` is a fresh sample, not a\n // settled state, so it must dispatch every time even when the values happen\n // to repeat (docs/sensor-tag-design.md §1.1).\n private _setReading(reading: WcsMagnetometerReading): void {\n this._reading = reading;\n this._target.dispatchEvent(new CustomEvent(\"wcs-magnetometer:reading\", {\n detail: reading,\n bubbles: true,\n }));\n }\n\n private _setError(error: WcsMagnetometerErrorDetail | null): void {\n // Same-value guard (by error name + message): error is state-like, unlike\n // reading — a repeated identical error (same name and message) must not\n // redispatch. Note `error` is also STICKY: nothing calls _setError(null),\n // so a successful (re)start does not clear a prior failure — the monitoring\n // sensor family deliberately keeps the last observed error (docs/sensor-tag-design.md §1.5).\n if (this._error?.error === error?.error && this._error?.message === error?.message) return;\n this._error = error;\n this._target.dispatchEvent(new CustomEvent(\"wcs-magnetometer:error\", {\n detail: error,\n bubbles: true,\n }));\n }\n\n // --- Public API ---\n\n /**\n * Start the sensor at the given `frequency` (Hz), or the platform default\n * when omitted. Idempotent while already started: a redundant start() does\n * not construct a second sensor instance (which would leak the first).\n * Restart with a different frequency via stop() + start().\n *\n * Synchronous, mirroring the native `Sensor.start()` — never throws\n * (docs/async-io-node-guidelines.md §3.6): both \"unsupported\" and a\n * synchronous constructor exception (permission denial, feature-policy\n * block) are converted to the `error` property instead of propagating.\n */\n start(frequency?: number): void {\n if (this._sensor) return;\n const sensor = this._createSensor(frequency);\n if (!sensor) return;\n sensor.addEventListener(\"reading\", this._onReading as EventListener);\n sensor.addEventListener(\"error\", this._onError as EventListener);\n this._sensor = sensor;\n try {\n sensor.start();\n } catch (e: any) {\n // Defensive: the platform contract says start()/stop() do not throw\n // (failures surface via the 'error' event), but never-throw is a hard\n // requirement here, so guard against a non-conformant implementation\n // too.\n this._teardownSensor();\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n }\n }\n\n /** Stop the sensor and detach its listeners. Safe to call when not started. */\n stop(): void {\n if (!this._sensor) return;\n try {\n this._sensor.stop();\n } catch {\n // Never-throw defensive guard, symmetric with start(). Teardown below\n // still runs so listeners are detached regardless.\n }\n this._teardownSensor();\n }\n\n /** Lifecycle alias for start(), so the Shell's connectedCallback can drive\n * this Core the same way as other IO nodes' observe()/dispose() pair. No\n * asynchronous probe, so the returned promise always resolves immediately. */\n observe(frequency?: number): Promise<void> {\n this.start(frequency);\n return this.ready;\n }\n\n /** Lifecycle alias for stop(), invoked from the Shell's disconnectedCallback. */\n dispose(): void {\n this.stop();\n }\n\n // --- Internal ---\n\n // Both call sites (start()'s catch, stop()) only ever invoke this once\n // `this._sensor` is already known non-null, so there is no null-guard here\n // (nothing to defend against).\n private _teardownSensor(): void {\n this._sensor!.removeEventListener(\"reading\", this._onReading as EventListener);\n this._sensor!.removeEventListener(\"error\", this._onError as EventListener);\n this._sensor = null;\n }\n\n /**\n * Construct the platform `Magnetometer`, guarding both non-support and a\n * synchronous constructor exception. Never calls the raw `new Magnetometer(...)`\n * anywhere else in this class — see docs/sensor-tag-design.md §1.5.\n *\n * API resolution is call-time (docs/async-io-node-guidelines.md §3.7):\n * re-checked on every start(), never cached, so tests can install/remove\n * the global freely and an unsupported environment is always reported\n * correctly.\n */\n private _createSensor(frequency?: number): (EventTarget & { start(): void; stop(): void }) | null {\n const Ctor = (globalThis as any).Magnetometer;\n if (typeof Ctor !== \"function\") {\n this._setError({ error: \"unsupported\", message: \"Magnetometer is not supported\" });\n return null;\n }\n try {\n return new Ctor(frequency !== undefined ? { frequency } : undefined);\n } catch (e: any) {\n // SecurityError (permission denial, feature-policy block) or any other\n // synchronous construction failure. Mirrors the FetchCore._doFetch\n // try/catch structure (packages/fetch/src/core/FetchCore.ts) — a\n // synchronous constructor call here instead of an awaited fetch().\n this._setError({ error: e?.name ?? \"error\", message: e?.message ?? String(e) });\n return null;\n }\n }\n\n private _onReading = (event: Event): void => {\n const sensor = event.target as unknown as { x: number | null; y: number | null; z: number | null };\n this._setReading({ x: sensor.x, y: sensor.y, z: sensor.z });\n };\n\n private _onError = (event: Event): void => {\n const err = (event as any).error as { name?: string; message?: string } | undefined;\n // Fallback is a meaningful constant, NOT String(err): a SensorErrorEvent\n // without an `error` field would otherwise stringify `undefined` into the\n // literal message \"undefined\" (aligned across the sensor family).\n this._setError({ error: err?.name ?? \"error\", message: err?.message ?? \"Sensor error\" });\n };\n}\n","import { IWcBindable, WcsMagnetometerErrorDetail } from \"../types.js\";\nimport { MagnetometerCore } from \"../core/MagnetometerCore.js\";\n\n/**\n * `<wcs-magnetometer>` — declarative Generic Sensor API (`Magnetometer`)\n * monitor + start/stop control.\n *\n * Unlike `<wcs-network>` / `<wcs-permission>` (pure monitors), this Shell is a\n * bidirectional node: `start`/`stop` commands (command-token: state → element)\n * alongside the `x`/`y`/`z`/`error` observable surface (event-token: element →\n * state). The `frequency` attribute is the sole configuration input, forwarded\n * to the platform `Magnetometer` constructor's `{ frequency }` option\n * (docs/sensor-tag-design.md §1.2). The getter normalizes it: a non-finite or\n * non-positive value (NaN, 0, negative) reads back as `null` — meaning \"no\n * frequency specified\" — so start() falls back to the platform default rather\n * than forwarding a value the sensor would reject. Any positive finite value is\n * passed through verbatim (no upper-bound clamping — an out-of-range-but-positive\n * rate is still left to the browser/sensor to reject via `error`).\n *\n * Permission handling is intentionally NOT implemented here. Compose with\n * `<wcs-permission name=\"magnetometer\">` instead (see the README's permission\n * example, \"Gate on permission, then start\", and docs/sensor-tag-design.md).\n */\nexport class WcsMagnetometer extends HTMLElement {\n static hasConnectedCallbackPromise = true;\n\n static wcBindable: IWcBindable = {\n ...MagnetometerCore.wcBindable,\n inputs: [{ name: \"frequency\" }],\n // Core の commands をそのまま継承(単一情報源)。\n commands: MagnetometerCore.wcBindable.commands,\n };\n\n private _core: MagnetometerCore;\n private _connectedCallbackPromise: Promise<void> = Promise.resolve();\n\n constructor() {\n super();\n this._core = new MagnetometerCore(this);\n }\n\n // --- Attribute accessors ---\n\n /**\n * Sampling frequency in Hz. Reads back `null` when unset, blank, or when the\n * attribute does not parse to a positive finite number (NaN, `\"0\"`, negative)\n * — in every such \"no usable value\" case the platform default applies.\n *\n * Note the deliberate set/get asymmetry: `set frequency(0)` (or any\n * non-positive/non-finite value) still writes the attribute verbatim for\n * transparency/inspectability, but the getter normalizes it back to `null`.\n * A round-trip through a non-positive value therefore does NOT preserve it —\n * that value carries no valid sampling meaning, so it is treated as \"unset\"\n * on read. Only positive finite frequencies survive a set→get round-trip.\n *\n * This value is read only at `start()` time. There is no\n * `attributeChangedCallback`, and `MagnetometerCore.start()` is idempotent\n * while already started (a redundant call is a no-op), so setting\n * `frequency` (attribute or property) on an already-running sensor has no\n * effect until the caller `stop()`s and `start()`s again (see the README's\n * \"Notes & limitations\").\n */\n get frequency(): number | null {\n const attr = this.getAttribute(\"frequency\");\n if (attr === null || attr.trim() === \"\") return null;\n const parsed = Number(attr);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : null;\n }\n\n set frequency(value: number | null | undefined) {\n if (value === null || value === undefined) {\n this.removeAttribute(\"frequency\");\n } else {\n this.setAttribute(\"frequency\", String(value));\n }\n }\n\n // --- Core delegated getters ---\n\n get x(): number | null {\n return this._core.x;\n }\n\n get y(): number | null {\n return this._core.y;\n }\n\n get z(): number | null {\n return this._core.z;\n }\n\n get error(): WcsMagnetometerErrorDetail | null {\n return this._core.error;\n }\n\n get connectedCallbackPromise(): Promise<void> {\n return this._connectedCallbackPromise;\n }\n\n // --- Commands ---\n\n start(): void {\n this._core.start(this.frequency ?? undefined);\n }\n\n stop(): void {\n this._core.stop();\n }\n\n // --- Lifecycle ---\n\n // Deliberately does NOT auto-start the sensor on connect. Unlike\n // Geolocation (whose default phase acquires a fix immediately unless\n // `manual` is set), Magnetometer has no such \"connect implies observing\"\n // precedent in the design doc (docs/sensor-tag-design.md §1.3):\n // start/stop are the only commands, so connecting the element merely makes\n // it inert until a command-token `start` (or the `start()` method) is\n // invoked. This also keeps behavior predictable when composed with\n // `<wcs-permission name=\"magnetometer\">`: the caller decides when to start,\n // typically gated on `granted`.\n connectedCallback(): void {\n this.style.display = \"none\";\n // No asynchronous probe to await (docs/async-io-node-guidelines.md §3.8);\n // kept for SSR uniformity with other IO nodes.\n this._connectedCallbackPromise = this._core.ready;\n }\n\n disconnectedCallback(): void {\n this._core.dispose();\n }\n}\n","import { setConfig } from \"./config.js\";\nimport { registerComponents } from \"./registerComponents.js\";\nimport { IWritableConfig } from \"./types.js\";\n\nexport function bootstrapMagnetometer(userConfig?: IWritableConfig): void {\n if (userConfig) {\n setConfig(userConfig);\n }\n registerComponents();\n}\n","import { WcsMagnetometer } from \"./components/Magnetometer.js\";\nimport { config } from \"./config.js\";\n\nexport function registerComponents(): void {\n if (!customElements.get(config.tagNames.magnetometer)) {\n customElements.define(config.tagNames.magnetometer, WcsMagnetometer);\n }\n}\n"],"names":["_config","tagNames","magnetometer","deepFreeze","obj","Object","freeze","key","keys","deepClone","clone","frozenConfig","config","getConfig","NULL_READING","x","y","z","MagnetometerCore","EventTarget","static","protocol","version","properties","name","event","getter","e","detail","commands","_target","_reading","_error","_sensor","constructor","target","super","this","error","ready","Promise","resolve","_setReading","reading","dispatchEvent","CustomEvent","bubbles","_setError","message","start","frequency","sensor","_createSensor","addEventListener","_onReading","_onError","_teardownSensor","String","stop","observe","dispose","removeEventListener","Ctor","globalThis","Magnetometer","undefined","err","WcsMagnetometer","HTMLElement","wcBindable","inputs","_core","_connectedCallbackPromise","attr","getAttribute","trim","parsed","Number","isFinite","value","removeAttribute","setAttribute","connectedCallbackPromise","connectedCallback","style","display","disconnectedCallback","bootstrapMagnetometer","userConfig","partialConfig","assign","customElements","get","define"],"mappings":"AAQA,MAAMA,EAA2B,CAC/BC,SAAU,CACRC,aAAc,qBAIlB,SAASC,EAAcC,GACrB,GAAY,OAARA,GAA+B,iBAARA,EAAkB,OAAOA,EACpDC,OAAOC,OAAOF,GACd,IAAK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,KAAK+C,MAAMC,QAAU,OAGrBhD,KAAKmC,0BAA4BnC,KAAKkC,MAAMhC,KAC9C,CAEA,oBAAA+C,GACEjD,KAAKkC,MAAMX,SACb,EC7HI,SAAU2B,EAAsBC,GHuChC,IAAoBC,EGtCpBD,KHsCoBC,EGrCZD,GHsCMvF,UAChBI,OAAOqF,OAAO1F,EAAQC,SAAUwF,EAAcxF,UAEhDU,EAAe,MI3CVgF,eAAeC,IAAIhF,EAAOX,SAASC,eACtCyF,eAAeE,OAAOjF,EAAOX,SAASC,aAAciE,EDIxD"}
package/package.json ADDED
@@ -0,0 +1,71 @@
1
+ {
2
+ "name": "@wcstack/magnetometer",
3
+ "version": "1.16.0",
4
+ "description": "Declarative Magnetometer component for Web Components. Framework-agnostic Generic Sensor API (Magnetometer) monitor via wc-bindable-protocol.",
5
+ "type": "module",
6
+ "main": "./dist/index.esm.js",
7
+ "module": "./dist/index.esm.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.esm.js"
13
+ },
14
+ "./auto": "./dist/auto.min.js"
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "clean": "rimraf dist .tsc-out",
21
+ "build": "rimraf dist .tsc-out && tsc && rollup -c",
22
+ "test": "vitest run",
23
+ "test:watch": "vitest",
24
+ "test:coverage": "vitest run --coverage",
25
+ "lint": "eslint src",
26
+ "version:patch": "npm version patch",
27
+ "version:minor": "npm version minor",
28
+ "version:major": "npm version major",
29
+ "prepublishOnly": "npm run build && npm run test:coverage"
30
+ },
31
+ "keywords": [
32
+ "web-components",
33
+ "magnetometer",
34
+ "generic-sensor",
35
+ "motion",
36
+ "custom-elements",
37
+ "wc-bindable",
38
+ "declarative",
39
+ "zero-dependencies",
40
+ "framework-agnostic"
41
+ ],
42
+ "author": "mogera551",
43
+ "homepage": "https://wcstack.github.io",
44
+ "repository": {
45
+ "type": "git",
46
+ "url": "https://github.com/wcstack/wcstack.git",
47
+ "directory": "packages/magnetometer"
48
+ },
49
+ "bugs": {
50
+ "url": "https://github.com/wcstack/wcstack/issues"
51
+ },
52
+ "license": "MIT",
53
+ "devDependencies": {
54
+ "@eslint/js": "^9.39.1",
55
+ "@rollup/plugin-terser": "^0.4.4",
56
+ "@rollup/plugin-typescript": "^11.1.6",
57
+ "@vitest/coverage-v8": "^4.0.15",
58
+ "@vitest/ui": "^4.0.15",
59
+ "eslint": "^9.39.1",
60
+ "globals": "^16.5.0",
61
+ "happy-dom": "^20.0.11",
62
+ "rimraf": "^6.0.1",
63
+ "rollup": "^4.22.4",
64
+ "rollup-plugin-dts": "^6.1.1",
65
+ "rollup-plugin-copy": "^3.5.0",
66
+ "tslib": "^2.8.1",
67
+ "typescript": "^5.9.3",
68
+ "typescript-eslint": "^8.49.0",
69
+ "vitest": "^4.0.15"
70
+ }
71
+ }