@unisim/sdk 0.169.0 → 0.170.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.
@@ -0,0 +1,171 @@
1
+ // ─────────────────────────────────────────────────────────────────────────────
2
+ // A second signed-in account, parked beside the live one.
3
+ //
4
+ // James, 2026-09-30: "can we add a feature to switch accounts just for me to go
5
+ // between personal and admin without signout/in?" He has two Universal IDs — a
6
+ // personal one and the platform admin (accounts@unisim.co.uk) — and god-mode is
7
+ // keyed on the admin's EMAIL, so the only way between them was sign out, sign in.
8
+ //
9
+ // The other account's session is kept under its own key in the SAME store as
10
+ // the live one (`chooseSessionStorage`): the .unisim.co.uk cookie on the web,
11
+ // the shared suite store in the native apps. So a switch made in one suite app
12
+ // is the switch in all of them, exactly as a sign-in is.
13
+ //
14
+ // ⚠️ A SESSION MAY LIVE IN ONE PLACE ONLY. GoTrue rotates the refresh token on
15
+ // every refresh and treats a used one coming back as theft — see the header of
16
+ // the `session-handoff` edge function: two stores sharing one refresh token
17
+ // sign the person out of both. So the parked session is never a COPY of the
18
+ // live one. Switching moves the live session into the stash and the stashed
19
+ // one out of it; `reconcileAccountStash` below throws the stash away whenever
20
+ // it turns out to hold the account that is live (a cancelled "Add another
21
+ // account", or someone signing in to the parked account the ordinary way).
22
+ //
23
+ // Only for the platform admin: the rows show when one of the two accounts is
24
+ // accounts@unisim.co.uk (see `useAccountSwitch`). Nobody else ever writes the
25
+ // stash, so for everyone else this file is a no-op on every auth event.
26
+ // ─────────────────────────────────────────────────────────────────────────────
27
+ /** Beside `universal-suite-auth`; the cookie adapter's chunk names (`<key>.N`) cannot collide with it. */
28
+ export const ACCOUNT_STASH_KEY = 'universal-suite-auth-other';
29
+ // Kept in sync with PLATFORM_ADMIN_EMAIL in auth.ts and admin.ts.
30
+ const PLATFORM_ADMIN_EMAIL = 'accounts@unisim.co.uk';
31
+ export function isPlatformAdminEmail(email) {
32
+ return !!email && email.toLowerCase() === PLATFORM_ADMIN_EMAIL;
33
+ }
34
+ /** The same store the live session uses. `undefined` there means supabase-js's own localStorage. */
35
+ export function accountStashStorage(chosen) {
36
+ if (chosen.storage)
37
+ return chosen.storage;
38
+ return {
39
+ getItem: (key) => {
40
+ try {
41
+ return window.localStorage.getItem(key);
42
+ }
43
+ catch {
44
+ return null;
45
+ }
46
+ },
47
+ setItem: (key, value) => {
48
+ try {
49
+ window.localStorage.setItem(key, value);
50
+ }
51
+ catch { /* private mode */ }
52
+ },
53
+ removeItem: (key) => {
54
+ try {
55
+ window.localStorage.removeItem(key);
56
+ }
57
+ catch { /* private mode */ }
58
+ },
59
+ };
60
+ }
61
+ export async function readStash(store) {
62
+ try {
63
+ const raw = await store.getItem(ACCOUNT_STASH_KEY);
64
+ if (!raw)
65
+ return null;
66
+ const parsed = JSON.parse(raw);
67
+ if (typeof parsed.access_token !== 'string' ||
68
+ typeof parsed.refresh_token !== 'string' ||
69
+ typeof parsed.user?.id !== 'string')
70
+ return null;
71
+ return {
72
+ access_token: parsed.access_token,
73
+ refresh_token: parsed.refresh_token,
74
+ user: { id: parsed.user.id, email: parsed.user.email ?? null },
75
+ };
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ export async function writeStash(store, session) {
82
+ const value = {
83
+ access_token: session.access_token,
84
+ refresh_token: session.refresh_token,
85
+ user: { id: session.user.id, email: session.user.email ?? null },
86
+ };
87
+ await store.setItem(ACCOUNT_STASH_KEY, JSON.stringify(value));
88
+ }
89
+ export async function clearStash(store) {
90
+ await store.removeItem(ACCOUNT_STASH_KEY);
91
+ }
92
+ /**
93
+ * True while "Add another account" has the sign-in dialog open. The live
94
+ * session was parked when it opened and is STILL live until the new sign-in
95
+ * lands, so for that stretch it is the one case where the stash may hold the
96
+ * live account — and a token refresh must update it rather than throw it away.
97
+ */
98
+ let addingAccount = false;
99
+ export function setAddingAccount(on) {
100
+ addingAccount = on;
101
+ }
102
+ /**
103
+ * Keep the stash honest on every auth event. Called from the provider's
104
+ * `onAuthStateChange` listener, so it must not call back into supabase-js
105
+ * (a listener that awaits the client deadlocks it) — it only touches storage.
106
+ *
107
+ * - Signed out, or a page that loads with nobody signed in: the stash goes
108
+ * too. A parked session left in a browser after its owner signed out is a
109
+ * session the next person at that browser could be handed.
110
+ * - The stash holds the live account: stale by definition (see the header),
111
+ * so it goes — unless an add is under way, when it is refreshed instead.
112
+ */
113
+ export function reconcileAccountStash(store, event, session) {
114
+ void (async () => {
115
+ try {
116
+ if (event === 'SIGNED_OUT' || (event === 'INITIAL_SESSION' && !session)) {
117
+ await clearStash(store);
118
+ return;
119
+ }
120
+ if (!session)
121
+ return;
122
+ const stash = await readStash(store);
123
+ if (!stash || stash.user.id !== session.user.id)
124
+ return;
125
+ if (addingAccount)
126
+ await writeStash(store, session);
127
+ else
128
+ await clearStash(store);
129
+ }
130
+ catch {
131
+ // Bookkeeping only: never let it disturb the sign-in it is watching.
132
+ }
133
+ })();
134
+ }
135
+ /**
136
+ * Trade a parked refresh token for a fresh session, straight from GoTrue.
137
+ *
138
+ * Done here rather than through `supabase.auth.setSession`, because when the
139
+ * parked token turns out to be dead setSession REMOVES THE LIVE SESSION on its
140
+ * way out — the person would be signed out of the account they were trying to
141
+ * leave. Asking GoTrue first means a dead stash costs nothing.
142
+ *
143
+ * `dead` = GoTrue refused the token (revoked, reused, account deleted): the
144
+ * stash is worthless. `unreachable` = the network or GoTrue failed: try again.
145
+ */
146
+ export async function refreshStashed(supabaseUrl, anonKey, refreshToken) {
147
+ let res;
148
+ try {
149
+ res = await fetch(`${supabaseUrl.replace(/\/$/, '')}/auth/v1/token?grant_type=refresh_token`, {
150
+ method: 'POST',
151
+ headers: { apikey: anonKey, 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({ refresh_token: refreshToken }),
153
+ });
154
+ }
155
+ catch {
156
+ return { ok: false, reason: 'unreachable' };
157
+ }
158
+ if (res.status >= 400 && res.status < 500)
159
+ return { ok: false, reason: 'dead' };
160
+ if (!res.ok)
161
+ return { ok: false, reason: 'unreachable' };
162
+ try {
163
+ const body = (await res.json());
164
+ if (body.access_token && body.refresh_token) {
165
+ return { ok: true, access_token: body.access_token, refresh_token: body.refresh_token };
166
+ }
167
+ }
168
+ catch { /* fall through */ }
169
+ return { ok: false, reason: 'unreachable' };
170
+ }
171
+ //# sourceMappingURL=accountStash.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountStash.js","sourceRoot":"","sources":["../src/accountStash.ts"],"names":[],"mappings":"AAAA,gFAAgF;AAChF,0DAA0D;AAC1D,EAAE;AACF,gFAAgF;AAChF,+EAA+E;AAC/E,gFAAgF;AAChF,kFAAkF;AAClF,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,+EAA+E;AAC/E,yDAAyD;AACzD,EAAE;AACF,+EAA+E;AAC/E,+EAA+E;AAC/E,4EAA4E;AAC5E,4EAA4E;AAC5E,4EAA4E;AAC5E,8EAA8E;AAC9E,0EAA0E;AAC1E,2EAA2E;AAC3E,EAAE;AACF,6EAA6E;AAC7E,8EAA8E;AAC9E,wEAAwE;AACxE,gFAAgF;AAKhF,0GAA0G;AAC1G,MAAM,CAAC,MAAM,iBAAiB,GAAG,4BAA4B,CAAA;AAE7D,kEAAkE;AAClE,MAAM,oBAAoB,GAAG,uBAAuB,CAAA;AAEpD,MAAM,UAAU,oBAAoB,CAAC,KAAgC;IACnE,OAAO,CAAC,CAAC,KAAK,IAAI,KAAK,CAAC,WAAW,EAAE,KAAK,oBAAoB,CAAA;AAChE,CAAC;AAaD,oGAAoG;AACpG,MAAM,UAAU,mBAAmB,CAAC,MAA4B;IAC9D,IAAI,MAAM,CAAC,OAAO;QAAE,OAAO,MAAM,CAAC,OAAO,CAAA;IACzC,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,EAAE,EAAE;YACf,IAAI,CAAC;gBAAC,OAAO,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;YAAC,CAAC;YAAC,MAAM,CAAC;gBA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H,CAAC;IAAC,MAAM,CAAC,CAAC,kBAAkB,CAAC,CAAC;IAC9B,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,MAAM,EAAE,aAAa,EAAE,CAAA;AAC7C,CAAC"}
@@ -0,0 +1,18 @@
1
+ export interface UseAccountSwitchResult {
2
+ /** The parked account's email when "Switch to …" should show, else null. */
3
+ otherEmail: string | null;
4
+ /** Whether "Add another account" should show. */
5
+ canAdd: boolean;
6
+ /**
7
+ * Swap the live and parked accounts. Resolves `switched` (the caller
8
+ * reloads), `expired` (the parked account needs signing in again — the stash
9
+ * is gone, start an add), or `failed` (offline; nothing changed).
10
+ */
11
+ switchAccount: () => Promise<'switched' | 'expired' | 'failed'>;
12
+ /** Park the live account; the caller then opens the sign-in dialog. */
13
+ beginAdd: () => Promise<void>;
14
+ /** The sign-in dialog closed. True when someone else is now signed in (reload). */
15
+ endAdd: () => Promise<boolean>;
16
+ }
17
+ export declare function useAccountSwitch(): UseAccountSwitchResult;
18
+ //# sourceMappingURL=accountSwitch.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountSwitch.d.ts","sourceRoot":"","sources":["../src/accountSwitch.ts"],"names":[],"mappings":"AAqBA,MAAM,WAAW,sBAAsB;IACrC,4EAA4E;IAC5E,UAAU,EAAE,MAAM,GAAG,IAAI,CAAA;IACzB,iDAAiD;IACjD,MAAM,EAAE,OAAO,CAAA;IACf;;;;OAIG;IACH,aAAa,EAAE,MAAM,OAAO,CAAC,UAAU,GAAG,SAAS,GAAG,QAAQ,CAAC,CAAA;IAC/D,uEAAuE;IACvE,QAAQ,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAA;IAC7B,mFAAmF;IACnF,MAAM,EAAE,MAAM,OAAO,CAAC,OAAO,CAAC,CAAA;CAC/B;AAED,wBAAgB,gBAAgB,IAAI,sBAAsB,CAoGzD"}
@@ -0,0 +1,102 @@
1
+ 'use client';
2
+ // The profile menu's end of accountStash.ts: which row to offer, and what it
3
+ // does. See that file's header for the why and the one rule (a session lives
4
+ // in one place only).
5
+ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
6
+ import { useUniversal } from './provider.js';
7
+ import { releaseHeldSeat } from './seatSession.js';
8
+ import { chooseSessionStorage } from './sessionStorage.js';
9
+ import { accountStashStorage, clearStash, isPlatformAdminEmail, readStash, refreshStashed, setAddingAccount, writeStash, } from './accountStash.js';
10
+ export function useAccountSwitch() {
11
+ const { supabase, session, config } = useUniversal();
12
+ const store = useMemo(() => accountStashStorage(chooseSessionStorage(config.cookieDomain)), [config.cookieDomain]);
13
+ const userId = session?.user?.id ?? null;
14
+ const email = session?.user?.email ?? null;
15
+ const anonymous = session?.user?.is_anonymous === true;
16
+ const mock = !!config.mockAuth && !config.cookieDomain;
17
+ const real = !!userId && !anonymous && !mock;
18
+ const [stash, setStash] = useState(null);
19
+ useEffect(() => {
20
+ if (!real) {
21
+ setStash(null);
22
+ return;
23
+ }
24
+ let cancelled = false;
25
+ void readStash(store).then((s) => {
26
+ if (!cancelled)
27
+ setStash(s && s.user.id !== userId ? s : null);
28
+ });
29
+ return () => {
30
+ cancelled = true;
31
+ };
32
+ }, [store, real, userId]);
33
+ const startedAs = useRef(null);
34
+ const switchAccount = useCallback(async () => {
35
+ const target = await readStash(store);
36
+ const { data } = await supabase.auth.getSession();
37
+ const current = data.session;
38
+ if (!target || !current || target.user.id === current.user.id)
39
+ return 'failed';
40
+ const fresh = await refreshStashed(config.supabaseUrl, config.supabaseAnonKey, target.refresh_token);
41
+ if (!fresh.ok) {
42
+ if (fresh.reason === 'dead') {
43
+ await clearStash(store);
44
+ setStash(null);
45
+ return 'expired';
46
+ }
47
+ return 'failed';
48
+ }
49
+ // The same courtesy sign-out pays: a concurrent seat held by the account
50
+ // being left is handed back rather than waiting out its idle timeout.
51
+ try {
52
+ await releaseHeldSeat();
53
+ }
54
+ catch { /* the seat expires on its own */ }
55
+ // Park the live session BEFORE replacing it, so there is never a moment
56
+ // when it exists nowhere.
57
+ await writeStash(store, current);
58
+ const { error } = await supabase.auth.setSession({
59
+ access_token: fresh.access_token,
60
+ refresh_token: fresh.refresh_token,
61
+ });
62
+ if (error) {
63
+ // Put back the account we were on; the parked copy of it would now be
64
+ // a second holder of a live token, so it goes.
65
+ await supabase.auth.setSession({
66
+ access_token: current.access_token,
67
+ refresh_token: current.refresh_token,
68
+ });
69
+ await clearStash(store);
70
+ setStash(null);
71
+ return 'failed';
72
+ }
73
+ return 'switched';
74
+ }, [supabase, store, config.supabaseUrl, config.supabaseAnonKey]);
75
+ const beginAdd = useCallback(async () => {
76
+ const { data } = await supabase.auth.getSession();
77
+ if (!data.session)
78
+ return;
79
+ startedAs.current = data.session.user.id;
80
+ setAddingAccount(true);
81
+ await writeStash(store, data.session);
82
+ }, [supabase, store]);
83
+ const endAdd = useCallback(async () => {
84
+ setAddingAccount(false);
85
+ const { data } = await supabase.auth.getSession();
86
+ const live = data.session;
87
+ const parked = await readStash(store);
88
+ // Closed without signing in to a different account: the parked copy is
89
+ // the live session, and must not outlive the dialog.
90
+ if (parked && live && parked.user.id === live.user.id) {
91
+ await clearStash(store);
92
+ setStash(null);
93
+ }
94
+ return !!live && !!startedAs.current && live.user.id !== startedAs.current;
95
+ }, [supabase, store]);
96
+ const otherEmail = real && stash && (isPlatformAdminEmail(email) || isPlatformAdminEmail(stash.user.email))
97
+ ? stash.user.email ?? ''
98
+ : null;
99
+ const canAdd = real && !stash && isPlatformAdminEmail(email);
100
+ return { otherEmail, canAdd, switchAccount, beginAdd, endAdd };
101
+ }
102
+ //# sourceMappingURL=accountSwitch.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"accountSwitch.js","sourceRoot":"","sources":["../src/accountSwitch.ts"],"names":[],"mappings":"AAAA,YAAY,CAAA;AAEZ,6EAA6E;AAC7E,6EAA6E;AAC7E,sBAAsB;AAEtB,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAA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ErB,MAAM,MAAM,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACpC,gBAAgB,CAAC,KAAK,CAAC,CAAA;QACvB,MAAM,EAAE,IAAI,EAAE,GAAG,MAAM,QAAQ,CAAC,IAAI,CAAC,UAAU,EAAE,CAAA;QACjD,MAAM,IAAI,GAAG,IAAI,CAAC,OAAO,CAAA;QACzB,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,KAAK,CAAC,CAAA;QACrC,uEAAuE;QACvE,qDAAqD;QACrD,IAAI,MAAM,IAAI,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,EAAE,KAAK,IAAI,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC;YACtD,MAAM,UAAU,CAAC,KAAK,CAAC,CAAA;YACvB,QAAQ,CAAC,IAAI,CAAC,CAAA;QAChB,CAAC;QACD,OAAO,CAAC,CAAC,IAAI,IAAI,CAAC,CAAC,SAAS,CAAC,OAAO,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,KAAK,SAAS,CAAC,OAAO,CAAA;IAC5E,CAAC,EAAE,CAAC,QAAQ,EAAE,KAAK,CAAC,CAAC,CAAA;IAErB,MAAM,UAAU,GACd,IAAI,IAAI,KAAK,IAAI,CAAC,oBAAoB,CAAC,KAAK,CAAC,IAAI,oBAAoB,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACtF,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;QACxB,CAAC,CAAC,IAAI,CAAA;IACV,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,KAAK,IAAI,oBAAoB,CAAC,KAAK,CAAC,CAAA;IAE5D,OAAO,EAAE,UAAU,EAAE,MAAM,EAAE,aAAa,EAAE,QAAQ,EAAE,MAAM,EAAE,CAAA;AAChE,CAAC"}
@@ -0,0 +1,105 @@
1
+ import { type CSSProperties } from 'react';
2
+ import { type MenuTheme } from './menuTheme.js';
3
+ /** Two taps on one button closer together than this are a double tap. */
4
+ export declare const DEFAULT_VIEW_DOUBLE_TAP_MS = 350;
5
+ /**
6
+ * The stored default for one view row, or `null`. For a store that needs it
7
+ * outside React — a zustand store's initial state, say. Inside a component use
8
+ * {@link useDefaultView}.
9
+ */
10
+ export declare function readDefaultView(product: string, id: string): string | null;
11
+ /** Store (or, with `null`, forget) one view row's default. */
12
+ export declare function writeDefaultView(product: string, id: string, view: string | null): void;
13
+ /**
14
+ * Forget every default view `product` has. Reset to defaults calls this, so an
15
+ * app gets it without wiring anything.
16
+ */
17
+ export declare function clearDefaultViews(product: string): void;
18
+ export interface UseDefaultViewOptions<T extends string> {
19
+ /**
20
+ * Every view this row can show. A stored value not in the list (a view that
21
+ * has since been removed) is ignored and `fallback` used instead.
22
+ */
23
+ views?: readonly T[];
24
+ }
25
+ export interface DefaultViewButtonProps {
26
+ title: string;
27
+ 'data-default-view'?: 'true';
28
+ style: CSSProperties;
29
+ }
30
+ export interface UseDefaultView<T extends string> {
31
+ /** The view to open on: the stored one, else `fallback`. */
32
+ defaultView: T;
33
+ /** Whether the person has chosen one (false = still the app's own default). */
34
+ isSet: boolean;
35
+ setDefaultView: (view: T | null) => void;
36
+ /**
37
+ * Call from the button's own onClick, BEFORE or after switching view — it
38
+ * does not switch anything. Returns true when this tap was the second of a
39
+ * double tap and made `view` the default.
40
+ */
41
+ tap: (view: T) => boolean;
42
+ /**
43
+ * `title`, `data-default-view` and a `style` (the pop, and
44
+ * `touch-action: manipulation` so a phone does not zoom on the double tap)
45
+ * for one button. Spread it, then merge your own style over it if you have one.
46
+ */
47
+ buttonProps: (view: T, label: string) => DefaultViewButtonProps;
48
+ }
49
+ /**
50
+ * The default for one row of view buttons, and the double tap that sets it.
51
+ *
52
+ * ```tsx
53
+ * const views = ['grid', 'list'] as const
54
+ * const dv = useDefaultView('files-layout', 'grid', { views })
55
+ * const [layout, setLayout] = useState(dv.defaultView)
56
+ * …
57
+ * <button
58
+ * {...dv.buttonProps('list', 'List')}
59
+ * onClick={() => { dv.tap('list'); setLayout('list') }}
60
+ * className="… data-[default-view=true]:ring-orange-400 …"
61
+ * >List</button>
62
+ * ```
63
+ *
64
+ * `id` names the row within the app (it is stored under the app's product, so
65
+ * two apps may both use `'layout'`). Must render inside <UniversalProvider>.
66
+ */
67
+ export declare function useDefaultView<T extends string>(id: string, fallback: T, options?: UseDefaultViewOptions<T>): UseDefaultView<T>;
68
+ /**
69
+ * The colourway of the Tune this app dialog, so a row the app passes into it
70
+ * can match. <PreferencesDialog> provides it; outside it, light.
71
+ */
72
+ export declare const PreferencesThemeContext: import("react").Context<MenuTheme>;
73
+ export interface DefaultViewSelectProps<T extends string> {
74
+ /** The same `id` the view row's {@link useDefaultView} uses. */
75
+ id: string;
76
+ /** The row's label, e.g. "Library opens on". */
77
+ label: string;
78
+ /** The app's own default. Choosing it forgets the stored one. */
79
+ fallback: T;
80
+ /** Every view, with the label its button shows. */
81
+ views: readonly {
82
+ value: T;
83
+ label: string;
84
+ }[];
85
+ }
86
+ /**
87
+ * The Tune this app row for one view row's default — the double tap's twin,
88
+ * for anybody who cannot double-tap. Pass it in the navbar's `appPreferences`.
89
+ * Inline-styled to match the dialog's own Language row, in either colourway.
90
+ */
91
+ export declare function DefaultViewSelect<T extends string>({ id, label, fallback, views }: DefaultViewSelectProps<T>): import("react/jsx-runtime").JSX.Element;
92
+ /**
93
+ * Everything **Reset to defaults** does, for an app that draws its own
94
+ * settings surface instead of the SDK's Tune this app (Universal Jukebox):
95
+ * clears this app's default views, its language override and — given the
96
+ * app's `themeStore` — its colour scheme override, then runs `onResetDefaults`
97
+ * for the app's own settings. The SDK's dialog uses the same function.
98
+ */
99
+ export declare function useResetAppDefaults(onResetDefaults?: () => void, themeStore?: {
100
+ getState: () => {
101
+ override: unknown;
102
+ setOverride: (v: null) => void;
103
+ };
104
+ }): () => void;
105
+ //# sourceMappingURL=defaultView.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"defaultView.d.ts","sourceRoot":"","sources":["../src/default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