@ai-matrx/kit 0.6.0 → 0.7.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/CHANGELOG.md +5 -0
- package/dist/short-link-react.cjs +57 -20
- package/dist/short-link-react.cjs.map +1 -1
- package/dist/short-link-react.d.cts +41 -8
- package/dist/short-link-react.d.ts +41 -8
- package/dist/short-link-react.js +57 -20
- package/dist/short-link-react.js.map +1 -1
- package/dist/short-link.cjs +7 -0
- package/dist/short-link.cjs.map +1 -1
- package/dist/short-link.d.cts +7 -1
- package/dist/short-link.d.ts +7 -1
- package/dist/short-link.js +7 -0
- package/dist/short-link.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.7.0 — 2026-08-29
|
|
4
|
+
|
|
5
|
+
- `./short-link`: `currentAppPath()` — the current page (pathname + query + hash) as a shortenable path, so a sorted/filtered/configured view shortens to exactly that view.
|
|
6
|
+
- `./short-link-react`: headless `useCopyShortLink` (mint-per-path cache + clipboard + self-resetting phase — the whole flow for any custom chrome such as menu rows and context-menu items); `CopyShortLinkButton` rebuilt on it and `path` is now optional (omitted = current page at click time); new `CopyPageShortLinkButton` alias for the zero-prop "share this exact view" affordance.
|
|
7
|
+
|
|
3
8
|
## 0.6.0 — 2026-08-29
|
|
4
9
|
|
|
5
10
|
- `./short-link` grows the WHOLE client half: `mintShortLink(supabaseClient, { path, organizationId })` (calls the org-gated `public.shorten_app_url` door and returns the finished short URL) and `resolveShortLinkPath(supabaseClient, token)` (the anon resolver). Pass the Supabase client itself — no app writes shortener logic.
|
|
@@ -21,7 +21,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
// src/short-link-react.tsx
|
|
22
22
|
var short_link_react_exports = {};
|
|
23
23
|
__export(short_link_react_exports, {
|
|
24
|
+
CopyPageShortLinkButton: () => CopyPageShortLinkButton,
|
|
24
25
|
CopyShortLinkButton: () => CopyShortLinkButton,
|
|
26
|
+
useCopyShortLink: () => useCopyShortLink,
|
|
25
27
|
useShortLink: () => useShortLink
|
|
26
28
|
});
|
|
27
29
|
module.exports = __toCommonJS(short_link_react_exports);
|
|
@@ -76,6 +78,12 @@ async function mintShortLink(client, options) {
|
|
|
76
78
|
}
|
|
77
79
|
return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };
|
|
78
80
|
}
|
|
81
|
+
function currentAppPath() {
|
|
82
|
+
if (typeof window === "undefined" || !window.location) return null;
|
|
83
|
+
const { pathname, search, hash } = window.location;
|
|
84
|
+
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
|
|
85
|
+
return `${pathname}${search}${hash}`;
|
|
86
|
+
}
|
|
79
87
|
|
|
80
88
|
// src/short-link-react.tsx
|
|
81
89
|
var import_jsx_runtime = require("react/jsx-runtime");
|
|
@@ -111,49 +119,78 @@ function useShortLink(client, options) {
|
|
|
111
119
|
}, [client, options.path, options.organizationId, options.expiresAt, options.origin]);
|
|
112
120
|
return { mint, url, minting, error };
|
|
113
121
|
}
|
|
114
|
-
function
|
|
115
|
-
client,
|
|
116
|
-
label = "Copy short link",
|
|
117
|
-
className,
|
|
118
|
-
onCopied,
|
|
119
|
-
onError,
|
|
120
|
-
...options
|
|
121
|
-
}) {
|
|
122
|
-
const { mint, minting } = useShortLink(client, options);
|
|
122
|
+
function useCopyShortLink(client, options) {
|
|
123
123
|
const [phase, setPhase] = (0, import_react.useState)("idle");
|
|
124
|
+
const [lastUrl, setLastUrl] = (0, import_react.useState)(null);
|
|
125
|
+
const cache = (0, import_react.useRef)(/* @__PURE__ */ new Map());
|
|
124
126
|
const resetTimer = (0, import_react.useRef)(null);
|
|
127
|
+
const { path, onCopied, onError, ...mintOptions } = options;
|
|
125
128
|
const flash = (0, import_react.useCallback)((next) => {
|
|
126
129
|
setPhase(next);
|
|
127
130
|
if (resetTimer.current) clearTimeout(resetTimer.current);
|
|
128
131
|
resetTimer.current = setTimeout(() => setPhase("idle"), 2e3);
|
|
129
132
|
}, []);
|
|
130
|
-
const
|
|
131
|
-
const
|
|
133
|
+
const copy = (0, import_react.useCallback)(async () => {
|
|
134
|
+
const targetPath = path ?? currentAppPath();
|
|
135
|
+
if (!targetPath) {
|
|
136
|
+
flash("error");
|
|
137
|
+
onError?.("No path to shorten");
|
|
138
|
+
return { ok: false, error: "No path to shorten" };
|
|
139
|
+
}
|
|
140
|
+
let result = cache.current.get(targetPath);
|
|
141
|
+
if (!result?.ok) {
|
|
142
|
+
setPhase("minting");
|
|
143
|
+
result = await mintShortLink(client, { ...mintOptions, path: targetPath });
|
|
144
|
+
cache.current.set(targetPath, result);
|
|
145
|
+
}
|
|
132
146
|
if (!result.ok) {
|
|
133
147
|
flash("error");
|
|
134
148
|
onError?.(result.error);
|
|
135
|
-
return;
|
|
149
|
+
return { ok: false, error: result.error };
|
|
136
150
|
}
|
|
137
151
|
const copied = await writeClipboard(result.url);
|
|
138
|
-
if (copied) {
|
|
139
|
-
flash("copied");
|
|
140
|
-
onCopied?.(result.url);
|
|
141
|
-
} else {
|
|
152
|
+
if (!copied) {
|
|
142
153
|
flash("error");
|
|
143
154
|
onError?.("Could not write to the clipboard");
|
|
155
|
+
return { ok: false, error: "Could not write to the clipboard" };
|
|
144
156
|
}
|
|
145
|
-
|
|
146
|
-
|
|
157
|
+
setLastUrl(result.url);
|
|
158
|
+
flash("copied");
|
|
159
|
+
onCopied?.(result.url);
|
|
160
|
+
return { ok: true, url: result.url };
|
|
161
|
+
}, [
|
|
162
|
+
client,
|
|
163
|
+
path,
|
|
164
|
+
mintOptions.organizationId,
|
|
165
|
+
mintOptions.expiresAt,
|
|
166
|
+
mintOptions.origin,
|
|
167
|
+
flash,
|
|
168
|
+
onCopied,
|
|
169
|
+
onError
|
|
170
|
+
]);
|
|
171
|
+
return { copy, phase, lastUrl };
|
|
172
|
+
}
|
|
173
|
+
function CopyShortLinkButton({
|
|
174
|
+
client,
|
|
175
|
+
label = "Copy short link",
|
|
176
|
+
className,
|
|
177
|
+
...options
|
|
178
|
+
}) {
|
|
179
|
+
const { copy, phase } = useCopyShortLink(client, options);
|
|
180
|
+
const text = phase === "copied" ? "Copied" : phase === "error" ? "Copy failed" : phase === "minting" ? "Creating\u2026" : label;
|
|
147
181
|
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(
|
|
148
182
|
"button",
|
|
149
183
|
{
|
|
150
184
|
type: "button",
|
|
151
|
-
onClick,
|
|
152
|
-
disabled: minting,
|
|
185
|
+
onClick: copy,
|
|
186
|
+
disabled: phase === "minting",
|
|
153
187
|
"aria-live": "polite",
|
|
154
188
|
className: "inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 " + (phase === "error" ? "text-destructive " : "") + (className ?? ""),
|
|
155
189
|
children: text
|
|
156
190
|
}
|
|
157
191
|
);
|
|
158
192
|
}
|
|
193
|
+
function CopyPageShortLinkButton(props) {
|
|
194
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(CopyShortLinkButton, { ...props });
|
|
195
|
+
}
|
|
159
196
|
//# sourceMappingURL=short-link-react.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/short-link-react.tsx","../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link-react — the drop-in short-link UI.\n *\n * The five-minute story: import the button, hand it your Supabase client and a\n * path, done. The mint call (the org-gated `shorten_app_url` door), the URL\n * shape, the clipboard write, and the state feedback all live HERE — a\n * consuming app writes zero shortener logic.\n *\n * <CopyShortLinkButton client={supabase} path={`/notes/${id}`} organizationId={orgId} />\n *\n * Runtime deps of this subpath: none beyond React.\n * Styling is the Matrx Tailwind semantic-token vocabulary;\n * override via `className` (last-wins merge is the host's concern — the class\n * string is appended).\n */\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport {\n mintShortLink,\n type MintShortLinkOptions,\n type MintShortLinkResult,\n type ShortLinkClient,\n} from \"./short-link\";\n\nasync function writeClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface UseShortLinkResult {\n /** Mint (once) and return the short URL; re-calls return the cached mint. */\n mint: () => Promise<MintShortLinkResult>;\n /** The minted URL, once `mint` has succeeded. */\n url: string | null;\n minting: boolean;\n error: string | null;\n}\n\n/** Mint-on-demand with caching — the logic under `CopyShortLinkButton`. */\nexport function useShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): UseShortLinkResult {\n const [url, setUrl] = useState<string | null>(null);\n const [minting, setMinting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const cached = useRef<MintShortLinkResult | null>(null);\n\n const mint = useCallback(async (): Promise<MintShortLinkResult> => {\n if (cached.current?.ok) return cached.current;\n setMinting(true);\n setError(null);\n try {\n const result = await mintShortLink(client, options);\n cached.current = result;\n if (result.ok) {\n setUrl(result.url);\n } else {\n setError(result.error);\n }\n return result;\n } finally {\n setMinting(false);\n }\n }, [client, options.path, options.organizationId, options.expiresAt, options.origin]);\n\n return { mint, url, minting, error };\n}\n\nexport interface CopyShortLinkButtonProps extends MintShortLinkOptions {\n /** Your Supabase client (anything with a compatible `.rpc`). */\n client: ShortLinkClient;\n /** Button label; default \"Copy short link\". */\n label?: string;\n className?: string;\n /** Called with the short URL after it lands on the clipboard. */\n onCopied?: (url: string) => void;\n onError?: (error: string) => void;\n}\n\n/**\n * One click: mint (first time only), copy the short URL, confirm inline.\n * The mint is lazy — no short-link row exists until someone actually asks\n * for the link.\n */\nexport function CopyShortLinkButton({\n client,\n label = \"Copy short link\",\n className,\n onCopied,\n onError,\n ...options\n}: CopyShortLinkButtonProps) {\n const { mint, minting } = useShortLink(client, options);\n const [phase, setPhase] = useState<\"idle\" | \"copied\" | \"error\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const flash = useCallback((next: \"copied\" | \"error\") => {\n setPhase(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setPhase(\"idle\"), 2000);\n }, []);\n\n const onClick = useCallback(async () => {\n const result = await mint();\n if (!result.ok) {\n flash(\"error\");\n onError?.(result.error);\n return;\n }\n const copied = await writeClipboard(result.url);\n if (copied) {\n flash(\"copied\");\n onCopied?.(result.url);\n } else {\n flash(\"error\");\n onError?.(\"Could not write to the clipboard\");\n }\n }, [mint, flash, onCopied, onError]);\n\n const text =\n phase === \"copied\" ? \"Copied\" : phase === \"error\" ? \"Copy failed\" : minting ? \"Creating…\" : label;\n\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={minting}\n aria-live=\"polite\"\n className={\n \"inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 \" +\n \"text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 \" +\n (phase === \"error\" ? \"text-destructive \" : \"\") +\n (className ?? \"\")\n }\n >\n {text}\n </button>\n );\n}\n","/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAgBA,mBAA8C;;;ACevC,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAAuB,IAAI;AAOnF,SAAS,wBAAwB,WAAqD;AAC3F,QAAM,SAAS,aAAa,IAAI,KAAK,EAAE,YAAY;AACnD,SAAO,SAAS,KAAK,KAAK,IAAI,QAAQ;AACxC;AAQO,SAAS,cAAc,OAAuB;AACnD,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI;AAAA,MACR,kBAAkB,KAAK,U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CAAC,CAAC;AAEL,QAAM,cAAU,0BAAY,YAAY;AACtC,UAAM,SAAS,MAAM,KAAK;AAC1B,QAAI,CAAC,OAAO,IAAI;AACd,YAAM,OAAO;AACb,gBAAU,OAAO,KAAK;AACtB;AAAA,IACF;AACA,UAAM,SAAS,MAAM,eAAe,OAAO,GAAG;AAC9C,QAAI,QAAQ;AACV,YAAM,QAAQ;AACd,iBAAW,OAAO,GAAG;AAAA,IACvB,OAAO;AACL,YAAM,OAAO;AACb,gBAAU,kCAAkC;AAAA,IAC9C;AAAA,EACF,GAAG,CAAC,MAAM,OAAO,UAAU,OAAO,CAAC;AAEnC,QAAM,OACJ,UAAU,WAAW,WAAW,UAAU,UAAU,gBAAgB,UAAU,mBAAc;AAE9F,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL;AAAA,MACA,UAAU;AAAA,MACV,aAAU;AAAA,MACV,WACE,oKAEC,UAAU,UAAU,sBAAsB,OAC1C,aAAa;AAAA,MAGf;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/short-link-react.tsx","../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link-react — the drop-in short-link UI, headless included.\n *\n * The five-minute story: import the button, hand it your Supabase client, done.\n * The mint call (the org-gated `shorten_app_url` door), the URL shape, the\n * clipboard write, and the state feedback all live HERE — a consuming app\n * writes zero shortener logic.\n *\n * <CopyShortLinkButton client={supabase} path={`/notes/${id}`} organizationId={orgId} />\n * <CopyPageShortLinkButton client={supabase} organizationId={orgId} /> // THIS page, query string and all\n *\n * Custom chrome (a menu row, a context-menu item, an icon button)? Use the\n * headless hook and keep only the markup:\n *\n * const { copy, phase } = useCopyShortLink(supabase, { organizationId });\n * <button onClick={copy}>{phase === \"copied\" ? \"Copied\" : \"Copy short link\"}</button>\n *\n * Omitting `path` means \"the current page at the moment of the click\" —\n * pathname + query + hash, so a sorted/filtered/column-configured view\n * shortens to exactly that view.\n *\n * Runtime deps of this subpath: none beyond React.\n * Styling is the Matrx Tailwind semantic-token vocabulary; override via\n * `className` (the class string is appended).\n */\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport {\n currentAppPath,\n mintShortLink,\n type MintShortLinkOptions,\n type MintShortLinkResult,\n type ShortLinkClient,\n} from \"./short-link\";\n\nasync function writeClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface UseShortLinkResult {\n /** Mint (once) and return the short URL; re-calls return the cached mint. */\n mint: () => Promise<MintShortLinkResult>;\n /** The minted URL, once `mint` has succeeded. */\n url: string | null;\n minting: boolean;\n error: string | null;\n}\n\n/** Mint-on-demand with caching — a fixed path known at render time. */\nexport function useShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): UseShortLinkResult {\n const [url, setUrl] = useState<string | null>(null);\n const [minting, setMinting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const cached = useRef<MintShortLinkResult | null>(null);\n\n const mint = useCallback(async (): Promise<MintShortLinkResult> => {\n if (cached.current?.ok) return cached.current;\n setMinting(true);\n setError(null);\n try {\n const result = await mintShortLink(client, options);\n cached.current = result;\n if (result.ok) {\n setUrl(result.url);\n } else {\n setError(result.error);\n }\n return result;\n } finally {\n setMinting(false);\n }\n }, [client, options.path, options.organizationId, options.expiresAt, options.origin]);\n\n return { mint, url, minting, error };\n}\n\nexport type CopyShortLinkPhase = \"idle\" | \"minting\" | \"copied\" | \"error\";\n\nexport interface UseCopyShortLinkOptions\n extends Omit<MintShortLinkOptions, \"path\"> {\n /**\n * Path to shorten. Omit for \"the current page at click time\" (pathname +\n * query + hash — the exact configured view).\n */\n path?: string;\n /** Called with the short URL after it lands on the clipboard. */\n onCopied?: (url: string) => void;\n onError?: (error: string) => void;\n}\n\nexport interface UseCopyShortLinkResult {\n /** Mint (cached per path) + copy to the clipboard. The whole flow. */\n copy: () => Promise<{ ok: boolean; url?: string; error?: string }>;\n phase: CopyShortLinkPhase;\n /** The last successfully copied URL. */\n lastUrl: string | null;\n}\n\n/**\n * The headless whole-flow hook: mint (cached per path), clipboard write, and a\n * self-resetting phase for feedback. Every piece of chrome — the buttons below,\n * a menu row, a context-menu item — sits on this.\n */\nexport function useCopyShortLink(\n client: ShortLinkClient,\n options: UseCopyShortLinkOptions,\n): UseCopyShortLinkResult {\n const [phase, setPhase] = useState<CopyShortLinkPhase>(\"idle\");\n const [lastUrl, setLastUrl] = useState<string | null>(null);\n const cache = useRef<Map<string, MintShortLinkResult>>(new Map());\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const { path, onCopied, onError, ...mintOptions } = options;\n\n const flash = useCallback((next: \"copied\" | \"error\") => {\n setPhase(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setPhase(\"idle\"), 2000);\n }, []);\n\n const copy = useCallback(async () => {\n const targetPath = path ?? currentAppPath();\n if (!targetPath) {\n flash(\"error\");\n onError?.(\"No path to shorten\");\n return { ok: false, error: \"No path to shorten\" };\n }\n let result = cache.current.get(targetPath);\n if (!result?.ok) {\n setPhase(\"minting\");\n result = await mintShortLink(client, { ...mintOptions, path: targetPath });\n cache.current.set(targetPath, result);\n }\n if (!result.ok) {\n flash(\"error\");\n onError?.(result.error);\n return { ok: false, error: result.error };\n }\n const copied = await writeClipboard(result.url);\n if (!copied) {\n flash(\"error\");\n onError?.(\"Could not write to the clipboard\");\n return { ok: false, error: \"Could not write to the clipboard\" };\n }\n setLastUrl(result.url);\n flash(\"copied\");\n onCopied?.(result.url);\n return { ok: true, url: result.url };\n }, [\n client,\n path,\n mintOptions.organizationId,\n mintOptions.expiresAt,\n mintOptions.origin,\n flash,\n onCopied,\n onError,\n ]);\n\n return { copy, phase, lastUrl };\n}\n\nexport interface CopyShortLinkButtonProps extends UseCopyShortLinkOptions {\n /** Your Supabase client (anything with a compatible `.rpc`). */\n client: ShortLinkClient;\n /** Button label; default \"Copy short link\". */\n label?: string;\n className?: string;\n}\n\n/**\n * One click: mint (first time only), copy the short URL, confirm inline.\n * The mint is lazy — no short-link row exists until someone actually asks\n * for the link. With no `path`, shortens the current page at click time.\n */\nexport function CopyShortLinkButton({\n client,\n label = \"Copy short link\",\n className,\n ...options\n}: CopyShortLinkButtonProps) {\n const { copy, phase } = useCopyShortLink(client, options);\n\n const text =\n phase === \"copied\"\n ? \"Copied\"\n : phase === \"error\"\n ? \"Copy failed\"\n : phase === \"minting\"\n ? \"Creating…\"\n : label;\n\n return (\n <button\n type=\"button\"\n onClick={copy}\n disabled={phase === \"minting\"}\n aria-live=\"polite\"\n className={\n \"inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 \" +\n \"text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 \" +\n (phase === \"error\" ? \"text-destructive \" : \"\") +\n (className ?? \"\")\n }\n >\n {text}\n </button>\n );\n}\n\nexport type CopyPageShortLinkButtonProps = Omit<CopyShortLinkButtonProps, \"path\">;\n\n/**\n * \"Copy a short link to THIS page\" — the zero-thought affordance. The path is\n * read at click time (pathname + query + hash), so whatever the person has\n * configured — sorts, filters, hidden columns, a hash target — is exactly what\n * the recipient opens.\n */\nexport function CopyPageShortLinkButton(props: CopyPageShortLinkButtonProps) {\n return <CopyShortLinkButton {...props} />;\n}\n","/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n\n/**\n * The current page as a shortenable same-app path — pathname + query + hash,\n * exactly the \"this view, as I have it configured\" URL (sorts, filters, hidden\n * columns riding in the query string all survive). `null` outside a browser.\n */\nexport function currentAppPath(): string | null {\n if (typeof window === \"undefined\" || !window.location) return null;\n const { pathname, search, hash } = window.location;\n if (!pathname.startsWith(\"/\") || pathname.startsWith(\"//\")) return null;\n return `${pathname}${search}${hash}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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MAAM,eAAe,OAAO,GAAG;AAC9C,QAAI,CAAC,QAAQ;AACX,YAAM,OAAO;AACb,gBAAU,kCAAkC;AAC5C,aAAO,EAAE,IAAI,OAAO,OAAO,mCAAmC;AAAA,IAChE;AACA,eAAW,OAAO,GAAG;AACrB,UAAM,QAAQ;AACd,eAAW,OAAO,GAAG;AACrB,WAAO,EAAE,IAAI,MAAM,KAAK,OAAO,IAAI;AAAA,EACrC,GAAG;AAAA,IACD;AAAA,IACA;AAAA,IACA,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ,YAAY;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,EACF,CAAC;AAED,SAAO,EAAE,MAAM,OAAO,QAAQ;AAChC;AAeO,SAAS,oBAAoB;AAAA,EAClC;AAAA,EACA,QAAQ;AAAA,EACR;AAAA,EACA,GAAG;AACL,GAA6B;AAC3B,QAAM,EAAE,MAAM,MAAM,IAAI,iBAAiB,QAAQ,OAAO;AAExD,QAAM,OACJ,UAAU,WACN,WACA,UAAU,UACR,gBACA,UAAU,YACR,mBACA;AAEV,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL,SAAS;AAAA,MACT,UAAU,UAAU;AAAA,MACpB,aAAU;AAAA,MACV,WACE,oKAEC,UAAU,UAAU,sBAAsB,OAC1C,aAAa;AAAA,MAGf;AAAA;AAAA,EACH;AAEJ;AAUO,SAAS,wBAAwB,OAAqC;AAC3E,SAAO,4CAAC,uBAAqB,GAAG,OAAO;AACzC;","names":[]}
|
|
@@ -37,23 +37,56 @@ interface UseShortLinkResult {
|
|
|
37
37
|
minting: boolean;
|
|
38
38
|
error: string | null;
|
|
39
39
|
}
|
|
40
|
-
/** Mint-on-demand with caching —
|
|
40
|
+
/** Mint-on-demand with caching — a fixed path known at render time. */
|
|
41
41
|
declare function useShortLink(client: ShortLinkClient, options: MintShortLinkOptions): UseShortLinkResult;
|
|
42
|
-
|
|
42
|
+
type CopyShortLinkPhase = "idle" | "minting" | "copied" | "error";
|
|
43
|
+
interface UseCopyShortLinkOptions extends Omit<MintShortLinkOptions, "path"> {
|
|
44
|
+
/**
|
|
45
|
+
* Path to shorten. Omit for "the current page at click time" (pathname +
|
|
46
|
+
* query + hash — the exact configured view).
|
|
47
|
+
*/
|
|
48
|
+
path?: string;
|
|
49
|
+
/** Called with the short URL after it lands on the clipboard. */
|
|
50
|
+
onCopied?: (url: string) => void;
|
|
51
|
+
onError?: (error: string) => void;
|
|
52
|
+
}
|
|
53
|
+
interface UseCopyShortLinkResult {
|
|
54
|
+
/** Mint (cached per path) + copy to the clipboard. The whole flow. */
|
|
55
|
+
copy: () => Promise<{
|
|
56
|
+
ok: boolean;
|
|
57
|
+
url?: string;
|
|
58
|
+
error?: string;
|
|
59
|
+
}>;
|
|
60
|
+
phase: CopyShortLinkPhase;
|
|
61
|
+
/** The last successfully copied URL. */
|
|
62
|
+
lastUrl: string | null;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The headless whole-flow hook: mint (cached per path), clipboard write, and a
|
|
66
|
+
* self-resetting phase for feedback. Every piece of chrome — the buttons below,
|
|
67
|
+
* a menu row, a context-menu item — sits on this.
|
|
68
|
+
*/
|
|
69
|
+
declare function useCopyShortLink(client: ShortLinkClient, options: UseCopyShortLinkOptions): UseCopyShortLinkResult;
|
|
70
|
+
interface CopyShortLinkButtonProps extends UseCopyShortLinkOptions {
|
|
43
71
|
/** Your Supabase client (anything with a compatible `.rpc`). */
|
|
44
72
|
client: ShortLinkClient;
|
|
45
73
|
/** Button label; default "Copy short link". */
|
|
46
74
|
label?: string;
|
|
47
75
|
className?: string;
|
|
48
|
-
/** Called with the short URL after it lands on the clipboard. */
|
|
49
|
-
onCopied?: (url: string) => void;
|
|
50
|
-
onError?: (error: string) => void;
|
|
51
76
|
}
|
|
52
77
|
/**
|
|
53
78
|
* One click: mint (first time only), copy the short URL, confirm inline.
|
|
54
79
|
* The mint is lazy — no short-link row exists until someone actually asks
|
|
55
|
-
* for the link.
|
|
80
|
+
* for the link. With no `path`, shortens the current page at click time.
|
|
81
|
+
*/
|
|
82
|
+
declare function CopyShortLinkButton({ client, label, className, ...options }: CopyShortLinkButtonProps): React.JSX.Element;
|
|
83
|
+
type CopyPageShortLinkButtonProps = Omit<CopyShortLinkButtonProps, "path">;
|
|
84
|
+
/**
|
|
85
|
+
* "Copy a short link to THIS page" — the zero-thought affordance. The path is
|
|
86
|
+
* read at click time (pathname + query + hash), so whatever the person has
|
|
87
|
+
* configured — sorts, filters, hidden columns, a hash target — is exactly what
|
|
88
|
+
* the recipient opens.
|
|
56
89
|
*/
|
|
57
|
-
declare function
|
|
90
|
+
declare function CopyPageShortLinkButton(props: CopyPageShortLinkButtonProps): React.JSX.Element;
|
|
58
91
|
|
|
59
|
-
export { CopyShortLinkButton, type CopyShortLinkButtonProps, type UseShortLinkResult, useShortLink };
|
|
92
|
+
export { CopyPageShortLinkButton, type CopyPageShortLinkButtonProps, CopyShortLinkButton, type CopyShortLinkButtonProps, type CopyShortLinkPhase, type UseCopyShortLinkOptions, type UseCopyShortLinkResult, type UseShortLinkResult, useCopyShortLink, useShortLink };
|
|
@@ -37,23 +37,56 @@ interface UseShortLinkResult {
|
|
|
37
37
|
minting: boolean;
|
|
38
38
|
error: string | null;
|
|
39
39
|
}
|
|
40
|
-
/** Mint-on-demand with caching —
|
|
40
|
+
/** Mint-on-demand with caching — a fixed path known at render time. */
|
|
41
41
|
declare function useShortLink(client: ShortLinkClient, options: MintShortLinkOptions): UseShortLinkResult;
|
|
42
|
-
|
|
42
|
+
type CopyShortLinkPhase = "idle" | "minting" | "copied" | "error";
|
|
43
|
+
interface UseCopyShortLinkOptions extends Omit<MintShortLinkOptions, "path"> {
|
|
44
|
+
/**
|
|
45
|
+
* Path to shorten. Omit for "the current page at click time" (pathname +
|
|
46
|
+
* query + hash — the exact configured view).
|
|
47
|
+
*/
|
|
48
|
+
path?: string;
|
|
49
|
+
/** Called with the short URL after it lands on the clipboard. */
|
|
50
|
+
onCopied?: (url: string) => void;
|
|
51
|
+
onError?: (error: string) => void;
|
|
52
|
+
}
|
|
53
|
+
interface UseCopyShortLinkResult {
|
|
54
|
+
/** Mint (cached per path) + copy to the clipboard. The whole flow. */
|
|
55
|
+
copy: () => Promise<{
|
|
56
|
+
ok: boolean;
|
|
57
|
+
url?: string;
|
|
58
|
+
error?: string;
|
|
59
|
+
}>;
|
|
60
|
+
phase: CopyShortLinkPhase;
|
|
61
|
+
/** The last successfully copied URL. */
|
|
62
|
+
lastUrl: string | null;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* The headless whole-flow hook: mint (cached per path), clipboard write, and a
|
|
66
|
+
* self-resetting phase for feedback. Every piece of chrome — the buttons below,
|
|
67
|
+
* a menu row, a context-menu item — sits on this.
|
|
68
|
+
*/
|
|
69
|
+
declare function useCopyShortLink(client: ShortLinkClient, options: UseCopyShortLinkOptions): UseCopyShortLinkResult;
|
|
70
|
+
interface CopyShortLinkButtonProps extends UseCopyShortLinkOptions {
|
|
43
71
|
/** Your Supabase client (anything with a compatible `.rpc`). */
|
|
44
72
|
client: ShortLinkClient;
|
|
45
73
|
/** Button label; default "Copy short link". */
|
|
46
74
|
label?: string;
|
|
47
75
|
className?: string;
|
|
48
|
-
/** Called with the short URL after it lands on the clipboard. */
|
|
49
|
-
onCopied?: (url: string) => void;
|
|
50
|
-
onError?: (error: string) => void;
|
|
51
76
|
}
|
|
52
77
|
/**
|
|
53
78
|
* One click: mint (first time only), copy the short URL, confirm inline.
|
|
54
79
|
* The mint is lazy — no short-link row exists until someone actually asks
|
|
55
|
-
* for the link.
|
|
80
|
+
* for the link. With no `path`, shortens the current page at click time.
|
|
81
|
+
*/
|
|
82
|
+
declare function CopyShortLinkButton({ client, label, className, ...options }: CopyShortLinkButtonProps): React.JSX.Element;
|
|
83
|
+
type CopyPageShortLinkButtonProps = Omit<CopyShortLinkButtonProps, "path">;
|
|
84
|
+
/**
|
|
85
|
+
* "Copy a short link to THIS page" — the zero-thought affordance. The path is
|
|
86
|
+
* read at click time (pathname + query + hash), so whatever the person has
|
|
87
|
+
* configured — sorts, filters, hidden columns, a hash target — is exactly what
|
|
88
|
+
* the recipient opens.
|
|
56
89
|
*/
|
|
57
|
-
declare function
|
|
90
|
+
declare function CopyPageShortLinkButton(props: CopyPageShortLinkButtonProps): React.JSX.Element;
|
|
58
91
|
|
|
59
|
-
export { CopyShortLinkButton, type CopyShortLinkButtonProps, type UseShortLinkResult, useShortLink };
|
|
92
|
+
export { CopyPageShortLinkButton, type CopyPageShortLinkButtonProps, CopyShortLinkButton, type CopyShortLinkButtonProps, type CopyShortLinkPhase, type UseCopyShortLinkOptions, type UseCopyShortLinkResult, type UseShortLinkResult, useCopyShortLink, useShortLink };
|
package/dist/short-link-react.js
CHANGED
|
@@ -52,6 +52,12 @@ async function mintShortLink(client, options) {
|
|
|
52
52
|
}
|
|
53
53
|
return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };
|
|
54
54
|
}
|
|
55
|
+
function currentAppPath() {
|
|
56
|
+
if (typeof window === "undefined" || !window.location) return null;
|
|
57
|
+
const { pathname, search, hash } = window.location;
|
|
58
|
+
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
|
|
59
|
+
return `${pathname}${search}${hash}`;
|
|
60
|
+
}
|
|
55
61
|
|
|
56
62
|
// src/short-link-react.tsx
|
|
57
63
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -87,53 +93,84 @@ function useShortLink(client, options) {
|
|
|
87
93
|
}, [client, options.path, options.organizationId, options.expiresAt, options.origin]);
|
|
88
94
|
return { mint, url, minting, error };
|
|
89
95
|
}
|
|
90
|
-
function
|
|
91
|
-
client,
|
|
92
|
-
label = "Copy short link",
|
|
93
|
-
className,
|
|
94
|
-
onCopied,
|
|
95
|
-
onError,
|
|
96
|
-
...options
|
|
97
|
-
}) {
|
|
98
|
-
const { mint, minting } = useShortLink(client, options);
|
|
96
|
+
function useCopyShortLink(client, options) {
|
|
99
97
|
const [phase, setPhase] = useState("idle");
|
|
98
|
+
const [lastUrl, setLastUrl] = useState(null);
|
|
99
|
+
const cache = useRef(/* @__PURE__ */ new Map());
|
|
100
100
|
const resetTimer = useRef(null);
|
|
101
|
+
const { path, onCopied, onError, ...mintOptions } = options;
|
|
101
102
|
const flash = useCallback((next) => {
|
|
102
103
|
setPhase(next);
|
|
103
104
|
if (resetTimer.current) clearTimeout(resetTimer.current);
|
|
104
105
|
resetTimer.current = setTimeout(() => setPhase("idle"), 2e3);
|
|
105
106
|
}, []);
|
|
106
|
-
const
|
|
107
|
-
const
|
|
107
|
+
const copy = useCallback(async () => {
|
|
108
|
+
const targetPath = path ?? currentAppPath();
|
|
109
|
+
if (!targetPath) {
|
|
110
|
+
flash("error");
|
|
111
|
+
onError?.("No path to shorten");
|
|
112
|
+
return { ok: false, error: "No path to shorten" };
|
|
113
|
+
}
|
|
114
|
+
let result = cache.current.get(targetPath);
|
|
115
|
+
if (!result?.ok) {
|
|
116
|
+
setPhase("minting");
|
|
117
|
+
result = await mintShortLink(client, { ...mintOptions, path: targetPath });
|
|
118
|
+
cache.current.set(targetPath, result);
|
|
119
|
+
}
|
|
108
120
|
if (!result.ok) {
|
|
109
121
|
flash("error");
|
|
110
122
|
onError?.(result.error);
|
|
111
|
-
return;
|
|
123
|
+
return { ok: false, error: result.error };
|
|
112
124
|
}
|
|
113
125
|
const copied = await writeClipboard(result.url);
|
|
114
|
-
if (copied) {
|
|
115
|
-
flash("copied");
|
|
116
|
-
onCopied?.(result.url);
|
|
117
|
-
} else {
|
|
126
|
+
if (!copied) {
|
|
118
127
|
flash("error");
|
|
119
128
|
onError?.("Could not write to the clipboard");
|
|
129
|
+
return { ok: false, error: "Could not write to the clipboard" };
|
|
120
130
|
}
|
|
121
|
-
|
|
122
|
-
|
|
131
|
+
setLastUrl(result.url);
|
|
132
|
+
flash("copied");
|
|
133
|
+
onCopied?.(result.url);
|
|
134
|
+
return { ok: true, url: result.url };
|
|
135
|
+
}, [
|
|
136
|
+
client,
|
|
137
|
+
path,
|
|
138
|
+
mintOptions.organizationId,
|
|
139
|
+
mintOptions.expiresAt,
|
|
140
|
+
mintOptions.origin,
|
|
141
|
+
flash,
|
|
142
|
+
onCopied,
|
|
143
|
+
onError
|
|
144
|
+
]);
|
|
145
|
+
return { copy, phase, lastUrl };
|
|
146
|
+
}
|
|
147
|
+
function CopyShortLinkButton({
|
|
148
|
+
client,
|
|
149
|
+
label = "Copy short link",
|
|
150
|
+
className,
|
|
151
|
+
...options
|
|
152
|
+
}) {
|
|
153
|
+
const { copy, phase } = useCopyShortLink(client, options);
|
|
154
|
+
const text = phase === "copied" ? "Copied" : phase === "error" ? "Copy failed" : phase === "minting" ? "Creating\u2026" : label;
|
|
123
155
|
return /* @__PURE__ */ jsx(
|
|
124
156
|
"button",
|
|
125
157
|
{
|
|
126
158
|
type: "button",
|
|
127
|
-
onClick,
|
|
128
|
-
disabled: minting,
|
|
159
|
+
onClick: copy,
|
|
160
|
+
disabled: phase === "minting",
|
|
129
161
|
"aria-live": "polite",
|
|
130
162
|
className: "inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 " + (phase === "error" ? "text-destructive " : "") + (className ?? ""),
|
|
131
163
|
children: text
|
|
132
164
|
}
|
|
133
165
|
);
|
|
134
166
|
}
|
|
167
|
+
function CopyPageShortLinkButton(props) {
|
|
168
|
+
return /* @__PURE__ */ jsx(CopyShortLinkButton, { ...props });
|
|
169
|
+
}
|
|
135
170
|
export {
|
|
171
|
+
CopyPageShortLinkButton,
|
|
136
172
|
CopyShortLinkButton,
|
|
173
|
+
useCopyShortLink,
|
|
137
174
|
useShortLink
|
|
138
175
|
};
|
|
139
176
|
//# sourceMappingURL=short-link-react.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/short-link-react.tsx","../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link-react — the drop-in short-link UI.\n *\n * The five-minute story: import the button, hand it your Supabase client and a\n * path, done. The mint call (the org-gated `shorten_app_url` door), the URL\n * shape, the clipboard write, and the state feedback all live HERE — a\n * consuming app writes zero shortener logic.\n *\n * <CopyShortLinkButton client={supabase} path={`/notes/${id}`} organizationId={orgId} />\n *\n * Runtime deps of this subpath: none beyond React.\n * Styling is the Matrx Tailwind semantic-token vocabulary;\n * override via `className` (last-wins merge is the host's concern — the class\n * string is appended).\n */\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport {\n mintShortLink,\n type MintShortLinkOptions,\n type MintShortLinkResult,\n type ShortLinkClient,\n} from \"./short-link\";\n\nasync function writeClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface UseShortLinkResult {\n /** Mint (once) and return the short URL; re-calls return the cached mint. */\n mint: () => Promise<MintShortLinkResult>;\n /** The minted URL, once `mint` has succeeded. */\n url: string | null;\n minting: boolean;\n error: string | null;\n}\n\n/** Mint-on-demand with caching — the logic under `CopyShortLinkButton`. */\nexport function useShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): UseShortLinkResult {\n const [url, setUrl] = useState<string | null>(null);\n const [minting, setMinting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const cached = useRef<MintShortLinkResult | null>(null);\n\n const mint = useCallback(async (): Promise<MintShortLinkResult> => {\n if (cached.current?.ok) return cached.current;\n setMinting(true);\n setError(null);\n try {\n const result = await mintShortLink(client, options);\n cached.current = result;\n if (result.ok) {\n setUrl(result.url);\n } else {\n setError(result.error);\n }\n return result;\n } finally {\n setMinting(false);\n }\n }, [client, options.path, options.organizationId, options.expiresAt, options.origin]);\n\n return { mint, url, minting, error };\n}\n\nexport interface CopyShortLinkButtonProps extends MintShortLinkOptions {\n /** Your Supabase client (anything with a compatible `.rpc`). */\n client: ShortLinkClient;\n /** Button label; default \"Copy short link\". */\n label?: string;\n className?: string;\n /** Called with the short URL after it lands on the clipboard. */\n onCopied?: (url: string) => void;\n onError?: (error: string) => void;\n}\n\n/**\n * One click: mint (first time only), copy the short URL, confirm inline.\n * The mint is lazy — no short-link row exists until someone actually asks\n * for the link.\n */\nexport function CopyShortLinkButton({\n client,\n label = \"Copy short link\",\n className,\n onCopied,\n onError,\n ...options\n}: CopyShortLinkButtonProps) {\n const { mint, minting } = useShortLink(client, options);\n const [phase, setPhase] = useState<\"idle\" | \"copied\" | \"error\">(\"idle\");\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const flash = useCallback((next: \"copied\" | \"error\") => {\n setPhase(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setPhase(\"idle\"), 2000);\n }, []);\n\n const onClick = useCallback(async () => {\n const result = await mint();\n if (!result.ok) {\n flash(\"error\");\n onError?.(result.error);\n return;\n }\n const copied = await writeClipboard(result.url);\n if (copied) {\n flash(\"copied\");\n onCopied?.(result.url);\n } else {\n flash(\"error\");\n onError?.(\"Could not write to the clipboard\");\n }\n }, [mint, flash, onCopied, onError]);\n\n const text =\n phase === \"copied\" ? \"Copied\" : phase === \"error\" ? \"Copy failed\" : minting ? \"Creating…\" : label;\n\n return (\n <button\n type=\"button\"\n onClick={onClick}\n disabled={minting}\n aria-live=\"polite\"\n className={\n \"inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 \" +\n \"text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 \" +\n (phase === \"error\" ? \"text-destructive \" : \"\") +\n (className ?? \"\")\n }\n >\n {text}\n </button>\n );\n}\n","/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n"],"mappings":";;;AAgBA,SAAS,aAAa,QAAQ,gBAAgB;;;ACevC,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,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Aa,QAAQ,OAAO;AACtD,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAsC,MAAM;AACtE,QAAM,aAAa,OAA6C,IAAI;AAEpE,QAAM,QAAQ,YAAY,CAAC,SAA6B;AACtD,aAAS,IAAI;AACb,QAAI,WAAW,QAAS,cAAa,WAAW,OAAO;AACvD,eAAW,UAAU,WAAW,MAAM,SAAS,MAAM,GAAG,GAAI;AAAA,EAC9D,GAAG,CAAC,CAAC;AAEL,QAAM,UAAU,YAAY,YAAY;AACtC,UAAM,SAAS,MAAM,KAAK;AAC1B,QAAI,CAAC,OAAO,IAAI;AACd,YAAM,OAAO;AACb,gBAAU,OAAO,KAAK;AACtB;AAAA,IACF;AACA,UAAM,SAAS,MAAM,eAAe,OAAO,GAAG;AAC9C,QAAI,QAAQ;AACV,YAAM,QAAQ;AACd,iBAAW,OAAO,GAAG;AAAA,IACvB,OAAO;AACL,YAAM,OAAO;AACb,gBAAU,kCAAkC;AAAA,IAC9C;AAAA,EACF,GAAG,CAAC,MAAM,OAAO,UAAU,OAAO,CAAC;AAEnC,QAAM,OACJ,UAAU,WAAW,WAAW,UAAU,UAAU,gBAAgB,UAAU,mBAAc;AAE9F,SACE;AAAA,IAAC;AAAA;AAAA,MACC,MAAK;AAAA,MACL;AAAA,MACA,UAAU;AAAA,MACV,aAAU;AAAA,MACV,WACE,oKAEC,UAAU,UAAU,sBAAsB,OAC1C,aAAa;AAAA,MAGf;AAAA;AAAA,EACH;AAEJ;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/short-link-react.tsx","../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link-react — the drop-in short-link UI, headless included.\n *\n * The five-minute story: import the button, hand it your Supabase client, done.\n * The mint call (the org-gated `shorten_app_url` door), the URL shape, the\n * clipboard write, and the state feedback all live HERE — a consuming app\n * writes zero shortener logic.\n *\n * <CopyShortLinkButton client={supabase} path={`/notes/${id}`} organizationId={orgId} />\n * <CopyPageShortLinkButton client={supabase} organizationId={orgId} /> // THIS page, query string and all\n *\n * Custom chrome (a menu row, a context-menu item, an icon button)? Use the\n * headless hook and keep only the markup:\n *\n * const { copy, phase } = useCopyShortLink(supabase, { organizationId });\n * <button onClick={copy}>{phase === \"copied\" ? \"Copied\" : \"Copy short link\"}</button>\n *\n * Omitting `path` means \"the current page at the moment of the click\" —\n * pathname + query + hash, so a sorted/filtered/column-configured view\n * shortens to exactly that view.\n *\n * Runtime deps of this subpath: none beyond React.\n * Styling is the Matrx Tailwind semantic-token vocabulary; override via\n * `className` (the class string is appended).\n */\n\nimport { useCallback, useRef, useState } from \"react\";\n\nimport {\n currentAppPath,\n mintShortLink,\n type MintShortLinkOptions,\n type MintShortLinkResult,\n type ShortLinkClient,\n} from \"./short-link\";\n\nasync function writeClipboard(text: string): Promise<boolean> {\n try {\n await navigator.clipboard.writeText(text);\n return true;\n } catch {\n return false;\n }\n}\n\nexport interface UseShortLinkResult {\n /** Mint (once) and return the short URL; re-calls return the cached mint. */\n mint: () => Promise<MintShortLinkResult>;\n /** The minted URL, once `mint` has succeeded. */\n url: string | null;\n minting: boolean;\n error: string | null;\n}\n\n/** Mint-on-demand with caching — a fixed path known at render time. */\nexport function useShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): UseShortLinkResult {\n const [url, setUrl] = useState<string | null>(null);\n const [minting, setMinting] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const cached = useRef<MintShortLinkResult | null>(null);\n\n const mint = useCallback(async (): Promise<MintShortLinkResult> => {\n if (cached.current?.ok) return cached.current;\n setMinting(true);\n setError(null);\n try {\n const result = await mintShortLink(client, options);\n cached.current = result;\n if (result.ok) {\n setUrl(result.url);\n } else {\n setError(result.error);\n }\n return result;\n } finally {\n setMinting(false);\n }\n }, [client, options.path, options.organizationId, options.expiresAt, options.origin]);\n\n return { mint, url, minting, error };\n}\n\nexport type CopyShortLinkPhase = \"idle\" | \"minting\" | \"copied\" | \"error\";\n\nexport interface UseCopyShortLinkOptions\n extends Omit<MintShortLinkOptions, \"path\"> {\n /**\n * Path to shorten. Omit for \"the current page at click time\" (pathname +\n * query + hash — the exact configured view).\n */\n path?: string;\n /** Called with the short URL after it lands on the clipboard. */\n onCopied?: (url: string) => void;\n onError?: (error: string) => void;\n}\n\nexport interface UseCopyShortLinkResult {\n /** Mint (cached per path) + copy to the clipboard. The whole flow. */\n copy: () => Promise<{ ok: boolean; url?: string; error?: string }>;\n phase: CopyShortLinkPhase;\n /** The last successfully copied URL. */\n lastUrl: string | null;\n}\n\n/**\n * The headless whole-flow hook: mint (cached per path), clipboard write, and a\n * self-resetting phase for feedback. Every piece of chrome — the buttons below,\n * a menu row, a context-menu item — sits on this.\n */\nexport function useCopyShortLink(\n client: ShortLinkClient,\n options: UseCopyShortLinkOptions,\n): UseCopyShortLinkResult {\n const [phase, setPhase] = useState<CopyShortLinkPhase>(\"idle\");\n const [lastUrl, setLastUrl] = useState<string | null>(null);\n const cache = useRef<Map<string, MintShortLinkResult>>(new Map());\n const resetTimer = useRef<ReturnType<typeof setTimeout> | null>(null);\n const { path, onCopied, onError, ...mintOptions } = options;\n\n const flash = useCallback((next: \"copied\" | \"error\") => {\n setPhase(next);\n if (resetTimer.current) clearTimeout(resetTimer.current);\n resetTimer.current = setTimeout(() => setPhase(\"idle\"), 2000);\n }, []);\n\n const copy = useCallback(async () => {\n const targetPath = path ?? currentAppPath();\n if (!targetPath) {\n flash(\"error\");\n onError?.(\"No path to shorten\");\n return { ok: false, error: \"No path to shorten\" };\n }\n let result = cache.current.get(targetPath);\n if (!result?.ok) {\n setPhase(\"minting\");\n result = await mintShortLink(client, { ...mintOptions, path: targetPath });\n cache.current.set(targetPath, result);\n }\n if (!result.ok) {\n flash(\"error\");\n onError?.(result.error);\n return { ok: false, error: result.error };\n }\n const copied = await writeClipboard(result.url);\n if (!copied) {\n flash(\"error\");\n onError?.(\"Could not write to the clipboard\");\n return { ok: false, error: \"Could not write to the clipboard\" };\n }\n setLastUrl(result.url);\n flash(\"copied\");\n onCopied?.(result.url);\n return { ok: true, url: result.url };\n }, [\n client,\n path,\n mintOptions.organizationId,\n mintOptions.expiresAt,\n mintOptions.origin,\n flash,\n onCopied,\n onError,\n ]);\n\n return { copy, phase, lastUrl };\n}\n\nexport interface CopyShortLinkButtonProps extends UseCopyShortLinkOptions {\n /** Your Supabase client (anything with a compatible `.rpc`). */\n client: ShortLinkClient;\n /** Button label; default \"Copy short link\". */\n label?: string;\n className?: string;\n}\n\n/**\n * One click: mint (first time only), copy the short URL, confirm inline.\n * The mint is lazy — no short-link row exists until someone actually asks\n * for the link. With no `path`, shortens the current page at click time.\n */\nexport function CopyShortLinkButton({\n client,\n label = \"Copy short link\",\n className,\n ...options\n}: CopyShortLinkButtonProps) {\n const { copy, phase } = useCopyShortLink(client, options);\n\n const text =\n phase === \"copied\"\n ? \"Copied\"\n : phase === \"error\"\n ? \"Copy failed\"\n : phase === \"minting\"\n ? \"Creating…\"\n : label;\n\n return (\n <button\n type=\"button\"\n onClick={copy}\n disabled={phase === \"minting\"}\n aria-live=\"polite\"\n className={\n \"inline-flex items-center gap-1.5 rounded-md border border-border bg-card px-2.5 py-1.5 \" +\n \"text-sm font-medium text-foreground hover:bg-muted disabled:opacity-60 \" +\n (phase === \"error\" ? \"text-destructive \" : \"\") +\n (className ?? \"\")\n }\n >\n {text}\n </button>\n );\n}\n\nexport type CopyPageShortLinkButtonProps = Omit<CopyShortLinkButtonProps, \"path\">;\n\n/**\n * \"Copy a short link to THIS page\" — the zero-thought affordance. The path is\n * read at click time (pathname + query + hash), so whatever the person has\n * configured — sorts, filters, hidden columns, a hash target — is exactly what\n * the recipient opens.\n */\nexport function CopyPageShortLinkButton(props: CopyPageShortLinkButtonProps) {\n return <CopyShortLinkButton {...props} />;\n}\n","/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n\n/**\n * The current page as a shortenable same-app path — pathname + query + hash,\n * exactly the \"this view, as I have it configured\" URL (sorts, filters, hidden\n * columns riding in the query string all survive). `null` outside a browser.\n */\nexport function currentAppPath(): string | null {\n if (typeof window === \"undefined\" || !window.location) return null;\n const { pathname, search, hash } = window.location;\n if (!pathname.startsWith(\"/\") || pathname.startsWith(\"//\")) return null;\n return `${pathname}${search}${hash}`;\n}\n"],"mappings":";;;AA0BA,SAAS,aAAa,QAAQ,gBAAgB;;;ACKvC,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAAuB,IAAI;AAOnF,SAAS,wBAAwB,WAAqD;AAC3F,QAAM,SAAS,aAAa,IAAI,KAAK,EAAE,YAAY;AACnD,SAAO,SAAS,KAAK,KAAK,IAAI,QAAQ;AACxC;AAQO,SAAS,cAAc,OAAuB;AACnD,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,YAAY;AACf,UAAM,IAAI;AAAA,MACR,kBAAkB,KAAK,UAAU,KAAK,CAAC,+BACjC,uBAAuB,cAAc,yBAAyB;AAAA,IACtE;AAAA,EACF;AACA,SAAO,GAAG,sBAAsB,GAAG,UAAU;AAC/C;AAMO,SAAS,aAAa,QAAgB,OAAuB;AAClE,SAAO,GAAG,OAAO,QAAQ,QAAQ,EAAE,CAAC,GAAG,cAAc,KAAK,CAAC;AAC7D;AAqCA,SAAS,cAAc,QAAgC;AACrD,MAAI,OAAQ,QAAO;AACnB,MAAI,OAAO,WAAW,eAAe,OAAO,UAAU,QAAQ;AAC5D,WAAO,OAAO,SAAS;AAAA,EACzB;AACA,SAAO;AACT;AAGA,eAAsB,cACpB,QACA,SAC8B;AAC9B,MAAI,CAAC,QAAQ,KAAK,WAAW,GAAG,KAAK,QAAQ,KAAK,WAAW,IAAI,GAAG;AAClE,WAAO,EAAE,IAAI,OAAO,OAAO,qEAAqE;AAAA,EAClG;AACA,QAAM,SAAS,cAAc,QAAQ,MAAM;AAC3C,MAAI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ATH_PREFIX: () => SHORT_LINK_PATH_PREFIX,
|
|
24
24
|
SHORT_LINK_TOKEN_ALPHABET: () => SHORT_LINK_TOKEN_ALPHABET,
|
|
25
25
|
SHORT_LINK_TOKEN_LENGTH: () => SHORT_LINK_TOKEN_LENGTH,
|
|
26
|
+
currentAppPath: () => currentAppPath,
|
|
26
27
|
isShortLinkToken: () => isShortLinkToken,
|
|
27
28
|
mintShortLink: () => mintShortLink,
|
|
28
29
|
normalizeShortLinkToken: () => normalizeShortLinkToken,
|
|
@@ -94,4 +95,10 @@ async function resolveShortLinkPath(client, token) {
|
|
|
94
95
|
}
|
|
95
96
|
return { ok: true, targetPath };
|
|
96
97
|
}
|
|
98
|
+
function currentAppPath() {
|
|
99
|
+
if (typeof window === "undefined" || !window.location) return null;
|
|
100
|
+
const { pathname, search, hash } = window.location;
|
|
101
|
+
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
|
|
102
|
+
return `${pathname}${search}${hash}`;
|
|
103
|
+
}
|
|
97
104
|
//# sourceMappingURL=short-link.cjs.map
|
package/dist/short-link.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BO,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAAuB,IAAI;AAOnF,SAAS,wBAAwB,WAAqD;AAC3F,QAAM,SAAS,aAAa,IAAI,KAAK,EAAE,YAAY;AACnD,SAAO,SAAS,KAAK,KAAK,IAAI,QAAQ;AACxC;AAGO,SAAS,iBAAiB,WAA+C;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O,QAAQ,SAAS,kCAAkC;AAAA,EAChF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,MAAM,cAAc,KAAK,GAAG,KAAK,aAAa,QAAQ,KAAK,EAAE;AACzF;AAWA,eAAsB,qBACpB,QACA,OACiC;AACjC,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,WAAY,QAAO,EAAE,IAAI,MAAM;AACpC,QAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,IAAI,sBAAsB,EAAE,SAAS,WAAW,CAAC;AACtF,MAAI,MAAO,QAAO,EAAE,IAAI,MAAM;AAC9B,QAAM,SAAS;AACf,QAAM,aAAa,QAAQ,KAAK,OAAO,cAAc;AACrD,MAAI,CAAC,cAAc,CAAC,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,GAAG;AAC7E,WAAO,EAAE,IAAI,MAAM;AAAA,EACrB;AACA,SAAO,EAAE,IAAI,MAAM,WAAW;AAChC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n\n/**\n * The current page as a shortenable same-app path — pathname + query + hash,\n * exactly the \"this view, as I have it configured\" URL (sorts, filters, hidden\n * columns riding in the query string all survive). `null` outside a browser.\n */\nexport function currentAppPath(): string | null {\n if (typeof window === \"undefined\" || !window.location) return null;\n const { pathname, search, hash } = window.location;\n if (!pathname.startsWith(\"/\") || pathname.startsWith(\"//\")) return null;\n return `${pathname}${search}${hash}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA+BO,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAA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,IAAI,OAAO,OAAO,MAAM,QAAQ;AACpD,QAAM,SAAS;AACf,QAAM,QAAQ,QAAQ,KAAK,wBAAwB,OAAO,KAAK,IAAI;AACnE,MAAI,CAAC,OAAO;AACV,WAAO,EAAE,IAAI,OAAO,OAAO,QAAQ,SAAS,kCAAkC;AAAA,EAChF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,MAAM,cAAc,KAAK,GAAG,KAAK,aAAa,QAAQ,KAAK,EAAE;AACzF;AAWA,eAAsB,qBACpB,QACA,OACiC;AACjC,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,WAAY,QAAO,EAAE,IAAI,MAAM;AACpC,QAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,IAAI,sBAAsB,EAAE,SAAS,WAAW,CAAC;AACtF,MAAI,MAAO,QAAO,EAAE,IAAI,MAAM;AAC9B,QAAM,SAAS;AACf,QAAM,aAAa,QAAQ,KAAK,OAAO,cAAc;AACrD,MAAI,CAAC,cAAc,CAAC,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,GAAG;AAC7E,WAAO,EAAE,IAAI,MAAM;AAAA,EACrB;AACA,SAAO,EAAE,IAAI,MAAM,WAAW;AAChC;AAOO,SAAS,iBAAgC;AAC9C,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,SAAU,QAAO;AAC9D,QAAM,EAAE,UAAU,QAAQ,KAAK,IAAI,OAAO;AAC1C,MAAI,CAAC,SAAS,WAAW,GAAG,KAAK,SAAS,WAAW,IAAI,EAAG,QAAO;AACnE,SAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,IAAI;AACpC;","names":[]}
|
package/dist/short-link.d.cts
CHANGED
|
@@ -90,5 +90,11 @@ type ResolveShortLinkResult = {
|
|
|
90
90
|
* deliberately does not distinguish them.
|
|
91
91
|
*/
|
|
92
92
|
declare function resolveShortLinkPath(client: ShortLinkClient, token: string): Promise<ResolveShortLinkResult>;
|
|
93
|
+
/**
|
|
94
|
+
* The current page as a shortenable same-app path — pathname + query + hash,
|
|
95
|
+
* exactly the "this view, as I have it configured" URL (sorts, filters, hidden
|
|
96
|
+
* columns riding in the query string all survive). `null` outside a browser.
|
|
97
|
+
*/
|
|
98
|
+
declare function currentAppPath(): string | null;
|
|
93
99
|
|
|
94
|
-
export { type MintShortLinkOptions, type MintShortLinkResult, type ResolveShortLinkResult, SHORT_LINK_PATH_PREFIX, SHORT_LINK_TOKEN_ALPHABET, SHORT_LINK_TOKEN_LENGTH, type ShortLinkClient, isShortLinkToken, mintShortLink, normalizeShortLinkToken, resolveShortLinkPath, shortLinkPath, shortLinkUrl };
|
|
100
|
+
export { type MintShortLinkOptions, type MintShortLinkResult, type ResolveShortLinkResult, SHORT_LINK_PATH_PREFIX, SHORT_LINK_TOKEN_ALPHABET, SHORT_LINK_TOKEN_LENGTH, type ShortLinkClient, currentAppPath, isShortLinkToken, mintShortLink, normalizeShortLinkToken, resolveShortLinkPath, shortLinkPath, shortLinkUrl };
|
package/dist/short-link.d.ts
CHANGED
|
@@ -90,5 +90,11 @@ type ResolveShortLinkResult = {
|
|
|
90
90
|
* deliberately does not distinguish them.
|
|
91
91
|
*/
|
|
92
92
|
declare function resolveShortLinkPath(client: ShortLinkClient, token: string): Promise<ResolveShortLinkResult>;
|
|
93
|
+
/**
|
|
94
|
+
* The current page as a shortenable same-app path — pathname + query + hash,
|
|
95
|
+
* exactly the "this view, as I have it configured" URL (sorts, filters, hidden
|
|
96
|
+
* columns riding in the query string all survive). `null` outside a browser.
|
|
97
|
+
*/
|
|
98
|
+
declare function currentAppPath(): string | null;
|
|
93
99
|
|
|
94
|
-
export { type MintShortLinkOptions, type MintShortLinkResult, type ResolveShortLinkResult, SHORT_LINK_PATH_PREFIX, SHORT_LINK_TOKEN_ALPHABET, SHORT_LINK_TOKEN_LENGTH, type ShortLinkClient, isShortLinkToken, mintShortLink, normalizeShortLinkToken, resolveShortLinkPath, shortLinkPath, shortLinkUrl };
|
|
100
|
+
export { type MintShortLinkOptions, type MintShortLinkResult, type ResolveShortLinkResult, SHORT_LINK_PATH_PREFIX, SHORT_LINK_TOKEN_ALPHABET, SHORT_LINK_TOKEN_LENGTH, type ShortLinkClient, currentAppPath, isShortLinkToken, mintShortLink, normalizeShortLinkToken, resolveShortLinkPath, shortLinkPath, shortLinkUrl };
|
package/dist/short-link.js
CHANGED
|
@@ -62,10 +62,17 @@ async function resolveShortLinkPath(client, token) {
|
|
|
62
62
|
}
|
|
63
63
|
return { ok: true, targetPath };
|
|
64
64
|
}
|
|
65
|
+
function currentAppPath() {
|
|
66
|
+
if (typeof window === "undefined" || !window.location) return null;
|
|
67
|
+
const { pathname, search, hash } = window.location;
|
|
68
|
+
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
|
|
69
|
+
return `${pathname}${search}${hash}`;
|
|
70
|
+
}
|
|
65
71
|
export {
|
|
66
72
|
SHORT_LINK_PATH_PREFIX,
|
|
67
73
|
SHORT_LINK_TOKEN_ALPHABET,
|
|
68
74
|
SHORT_LINK_TOKEN_LENGTH,
|
|
75
|
+
currentAppPath,
|
|
69
76
|
isShortLinkToken,
|
|
70
77
|
mintShortLink,
|
|
71
78
|
normalizeShortLinkToken,
|
package/dist/short-link.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n"],"mappings":";AA+BO,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAAuB,IAAI;AAOnF,SAAS,wBAAwB,WAAqD;AAC3F,QAAM,SAAS,aAAa,IAAI,KAAK,EAAE,YAAY;AACnD,SAAO,SAAS,KAAK,KAAK,IAAI,QAAQ;AACxC;AAGO,SAAS,iBAAiB,WAA+C;AAC9E,SAAO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AS,kCAAkC;AAAA,EAChF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,MAAM,cAAc,KAAK,GAAG,KAAK,aAAa,QAAQ,KAAK,EAAE;AACzF;AAWA,eAAsB,qBACpB,QACA,OACiC;AACjC,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,WAAY,QAAO,EAAE,IAAI,MAAM;AACpC,QAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,IAAI,sBAAsB,EAAE,SAAS,WAAW,CAAC;AACtF,MAAI,MAAO,QAAO,EAAE,IAAI,MAAM;AAC9B,QAAM,SAAS;AACf,QAAM,aAAa,QAAQ,KAAK,OAAO,cAAc;AACrD,MAAI,CAAC,cAAc,CAAC,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,GAAG;AAC7E,WAAO,EAAE,IAAI,MAAM;AAAA,EACrB;AACA,SAAO,EAAE,IAAI,MAAM,WAAW;AAChC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/short-link.ts"],"sourcesContent":["/**\n * @ai-matrx/kit/short-link — the platform short-link CONTRACT, in one place.\n *\n * The primitive itself lives in the database (migration `0557_platform_short_links`):\n * `platform.short_links` holds `token → same-app path`, org-scoped and expiring;\n * `platform.create_short_link` mints (server-side only); `public.resolve_short_link`\n * resolves (anon-callable; answers with a PATH, never content — the target route's\n * own auth gates everything). The frontend redirect route is `/r/[token]`\n * (matrx-frontend `app/(public)/r/[token]`), and the notification spine mints per\n * SMS leg (aidream `services/notifications/short_links.py`).\n *\n * This module is the shared vocabulary every client needs to speak about those\n * tokens — alphabet, length, validation, and the URL shape — so no consumer ever\n * re-declares it. 🚨 `SHORT_LINK_TOKEN_ALPHABET` and `SHORT_LINK_TOKEN_LENGTH`\n * mirror `platform.create_short_link` EXACTLY; change one and you change both.\n *\n * 🚨 A short link is a URL, not a permission. The primitive that grants\n * anonymous access to content is `platform.share_links` (`/s/[token]`, 64-hex\n * tokens) — a different system, deliberately. Never shorten by minting a share\n * link, and never share by minting a short link.\n *\n * Pure logic — no DOM, no React, no network; safe in Server Components, route\n * handlers, workers, and Node scripts.\n */\n\n/**\n * 32 characters: digits 2–9 plus a–z minus `l` and `o`. 256 % 32 = 0, so the\n * mint maps random bytes without modulo bias; lowercase-only survives channels\n * that case-mangle (the resolver lowercases before lookup); the ambiguous\n * glyphs (`0/o`, `1/l`) never appear.\n */\nexport const SHORT_LINK_TOKEN_ALPHABET = \"23456789abcdefghijkmnpqrstuvwxyz\";\n\n/** 10 characters × 5 bits = 50 bits — unguessable at any realistic probe rate. */\nexport const SHORT_LINK_TOKEN_LENGTH = 10;\n\n/** The resolve route on the app origin (matrx-frontend `app/(public)/r/[token]`). */\nexport const SHORT_LINK_PATH_PREFIX = \"/r/\";\n\nconst TOKEN_RE = new RegExp(`^[${SHORT_LINK_TOKEN_ALPHABET}]{${SHORT_LINK_TOKEN_LENGTH}}$`);\n\n/**\n * Trim, lowercase, and shape-check a candidate token. Returns the normalized\n * token, or `null` for anything outside the contract — the resolver would\n * refuse it anyway, so callers can skip the round trip.\n */\nexport function normalizeShortLinkToken(candidate: string | null | undefined): string | null {\n const token = (candidate ?? \"\").trim().toLowerCase();\n return TOKEN_RE.test(token) ? token : null;\n}\n\n/** Whether a string is a well-formed short-link token (after normalization). */\nexport function isShortLinkToken(candidate: string | null | undefined): boolean {\n return normalizeShortLinkToken(candidate) !== null;\n}\n\n/** The app-relative path a token resolves at: `/r/<token>`. */\nexport function shortLinkPath(token: string): string {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) {\n throw new Error(\n `shortLinkPath: ${JSON.stringify(token)} is not a short-link token ` +\n `(${SHORT_LINK_TOKEN_LENGTH} chars of \"${SHORT_LINK_TOKEN_ALPHABET}\")`,\n );\n }\n return `${SHORT_LINK_PATH_PREFIX}${normalized}`;\n}\n\n/**\n * The absolute short URL for a token on a given origin, e.g.\n * `shortLinkUrl(\"https://app.aimatrx.com\", token)` → `https://app.aimatrx.com/r/<token>`.\n */\nexport function shortLinkUrl(origin: string, token: string): string {\n return `${origin.replace(/\\/+$/, \"\")}${shortLinkPath(token)}`;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// The client half — the WHOLE mint/resolve logic, so a consumer adds nothing.\n//\n// Pass your Supabase client (or anything with a compatible `.rpc`) and you are\n// done: `mintShortLink(supabase, { path, organizationId })` calls the platform's\n// authenticated mint door (`public.shorten_app_url`, org-membership-gated) and\n// hands back the finished short URL; `resolveShortLinkPath(supabase, token)`\n// calls the anon resolver (`public.resolve_short_link`). No app writes its own\n// shortener logic, ever — the only thing outside this module is the shared\n// database that stores the tokens, which is exactly where shared state lives.\n// ─────────────────────────────────────────────────────────────────────────────\n\n/** Anything with a Supabase-shaped `.rpc` — pass the Supabase client itself. */\nexport interface ShortLinkClient {\n rpc(\n fn: string,\n args?: Record<string, unknown>,\n ): PromiseLike<{ data: unknown; error: { message: string } | null }>;\n}\n\nexport interface MintShortLinkOptions {\n /** Same-app path to shorten (must start with a single `/`). */\n path: string;\n /** The organization the link belongs to — the caller must be a member. */\n organizationId: string;\n /** ISO timestamp; the platform default (365 days) applies when omitted. */\n expiresAt?: string;\n /** Origin for the returned URL; defaults to `window.location.origin`. */\n origin?: string;\n}\n\nexport type MintShortLinkResult =\n | { ok: true; token: string; path: string; url: string }\n | { ok: false; error: string };\n\nfunction resolveOrigin(origin?: string): string | null {\n if (origin) return origin;\n if (typeof window !== \"undefined\" && window.location?.origin) {\n return window.location.origin;\n }\n return null;\n}\n\n/** Mint a short link through the platform's authenticated mint door. */\nexport async function mintShortLink(\n client: ShortLinkClient,\n options: MintShortLinkOptions,\n): Promise<MintShortLinkResult> {\n if (!options.path.startsWith(\"/\") || options.path.startsWith(\"//\")) {\n return { ok: false, error: \"Only a same-app path (starting with a single '/') can be shortened\" };\n }\n const origin = resolveOrigin(options.origin);\n if (!origin) {\n return { ok: false, error: \"No origin: pass options.origin outside a browser\" };\n }\n const { data, error } = await client.rpc(\"shorten_app_url\", {\n p_path: options.path,\n p_organization_id: options.organizationId,\n ...(options.expiresAt ? { p_expires_at: options.expiresAt } : {}),\n });\n if (error) return { ok: false, error: error.message };\n const result = data as { ok?: boolean; token?: string; error?: string } | null;\n const token = result?.ok ? normalizeShortLinkToken(result.token) : null;\n if (!token) {\n return { ok: false, error: result?.error ?? \"The mint door returned no token\" };\n }\n return { ok: true, token, path: shortLinkPath(token), url: shortLinkUrl(origin, token) };\n}\n\nexport type ResolveShortLinkResult =\n | { ok: true; targetPath: string }\n | { ok: false };\n\n/**\n * Resolve a short token to its target path through the anon resolver.\n * `{ok:false}` covers invalid, unknown, and expired identically — the platform\n * deliberately does not distinguish them.\n */\nexport async function resolveShortLinkPath(\n client: ShortLinkClient,\n token: string,\n): Promise<ResolveShortLinkResult> {\n const normalized = normalizeShortLinkToken(token);\n if (!normalized) return { ok: false };\n const { data, error } = await client.rpc(\"resolve_short_link\", { p_token: normalized });\n if (error) return { ok: false };\n const result = data as { ok?: boolean; target_path?: string } | null;\n const targetPath = result?.ok ? result.target_path : undefined;\n if (!targetPath || !targetPath.startsWith(\"/\") || targetPath.startsWith(\"//\")) {\n return { ok: false };\n }\n return { ok: true, targetPath };\n}\n\n/**\n * The current page as a shortenable same-app path — pathname + query + hash,\n * exactly the \"this view, as I have it configured\" URL (sorts, filters, hidden\n * columns riding in the query string all survive). `null` outside a browser.\n */\nexport function currentAppPath(): string | null {\n if (typeof window === \"undefined\" || !window.location) return null;\n const { pathname, search, hash } = window.location;\n if (!pathname.startsWith(\"/\") || pathname.startsWith(\"//\")) return null;\n return `${pathname}${search}${hash}`;\n}\n"],"mappings":";AA+BO,IAAM,4BAA4B;AAGlC,IAAM,0BAA0B;AAGhC,IAAM,yBAAyB;AAEtC,IAAM,WAAW,IAAI,OAAO,KAAK,yBAAyB,KAAK,uBAAuB,IAAI;AAOnF,SAAS,wBAAwB,WAAqD;AAC3F,QAAM,SAAS,aAAa,IAAI,KAAK,EAAE,YAAY;AACnD,SAAO,SAAS,KAAK,KAAK,I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,CAAC,OAAO;AACV,WAAO,EAAE,IAAI,OAAO,OAAO,QAAQ,SAAS,kCAAkC;AAAA,EAChF;AACA,SAAO,EAAE,IAAI,MAAM,OAAO,MAAM,cAAc,KAAK,GAAG,KAAK,aAAa,QAAQ,KAAK,EAAE;AACzF;AAWA,eAAsB,qBACpB,QACA,OACiC;AACjC,QAAM,aAAa,wBAAwB,KAAK;AAChD,MAAI,CAAC,WAAY,QAAO,EAAE,IAAI,MAAM;AACpC,QAAM,EAAE,MAAM,MAAM,IAAI,MAAM,OAAO,IAAI,sBAAsB,EAAE,SAAS,WAAW,CAAC;AACtF,MAAI,MAAO,QAAO,EAAE,IAAI,MAAM;AAC9B,QAAM,SAAS;AACf,QAAM,aAAa,QAAQ,KAAK,OAAO,cAAc;AACrD,MAAI,CAAC,cAAc,CAAC,WAAW,WAAW,GAAG,KAAK,WAAW,WAAW,IAAI,GAAG;AAC7E,WAAO,EAAE,IAAI,MAAM;AAAA,EACrB;AACA,SAAO,EAAE,IAAI,MAAM,WAAW;AAChC;AAOO,SAAS,iBAAgC;AAC9C,MAAI,OAAO,WAAW,eAAe,CAAC,OAAO,SAAU,QAAO;AAC9D,QAAM,EAAE,UAAU,QAAQ,KAAK,IAAI,OAAO;AAC1C,MAAI,CAAC,SAAS,WAAW,GAAG,KAAK,SAAS,WAAW,IAAI,EAAG,QAAO;AACnE,SAAO,GAAG,QAAQ,GAAG,MAAM,GAAG,IAAI;AACpC;","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-matrx/kit",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"description": "The always-include AI Matrx kit: the little primitives every Matrx app speaks — autosave that never loses a keystroke, stale-response guards, clipboard with graceful fallbacks — one per subpath, tree-shaken to what you use.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.cjs",
|