@pylonsync/functions 0.3.57 → 0.3.58

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pylonsync/functions",
3
- "version": "0.3.57",
3
+ "version": "0.3.58",
4
4
  "description": "TypeScript function runtime for pylon — defines server-side queries, mutations, and actions.",
5
5
  "type": "module",
6
6
  "main": "src/index.ts",
package/src/index.ts CHANGED
@@ -21,6 +21,7 @@
21
21
  export { query, mutation, action } from "./define";
22
22
  export { v } from "./validators";
23
23
  export { resetDb, installTestIsolation } from "./testing";
24
+ export { slugifyName, availableSlug } from "./slugify";
24
25
  export type {
25
26
  QueryCtx,
26
27
  MutationCtx,
package/src/slugify.ts ADDED
@@ -0,0 +1,107 @@
1
+ // ---------------------------------------------------------------------------
2
+ // Slug helpers
3
+ //
4
+ // Multi-tenant Pylon apps almost always have a "named entity with a
5
+ // URL slug" pattern — Workspace, Organization, Team, Tenant, Project,
6
+ // Channel. The slugification rules are nearly identical across them:
7
+ // lowercase, hyphenate, drop punctuation, fall back to a numeric
8
+ // suffix on collision. Promoting to the framework so app authors
9
+ // don't keep writing it.
10
+ // ---------------------------------------------------------------------------
11
+
12
+ import type { DbReader, DbWriter } from "./types";
13
+
14
+ /**
15
+ * Pure: turn a human name into a URL-safe base slug. Doesn't check
16
+ * uniqueness — combine with `availableSlug` for that.
17
+ *
18
+ * Rules:
19
+ * - lowercase
20
+ * - non-alphanumeric runs become single dashes
21
+ * - trim leading/trailing dashes
22
+ * - max 40 chars (so a numeric suffix can land within typical
23
+ * 50-char schema constraints)
24
+ * - empty result (e.g. emoji-only name) → `fallback`
25
+ *
26
+ * @param name The user-typed display name to slugify.
27
+ * @param fallback Replacement when the slug strips to empty. Default: "x".
28
+ */
29
+ export function slugifyName(name: string, fallback = "x"): string {
30
+ const base = name
31
+ .toLowerCase()
32
+ .normalize("NFKD")
33
+ .replace(/[\u0300-\u036f]/g, "")
34
+ .replace(/[^a-z0-9]+/g, "-")
35
+ .replace(/^-+|-+$/g, "")
36
+ .slice(0, 40);
37
+ if (base.length >= 2) return base;
38
+ if (base.length === 1) return `${base}1`;
39
+ return fallback;
40
+ }
41
+
42
+ /**
43
+ * Find the first slug that's available in the named entity's `field`
44
+ * column. Tries `base`, then `base-2`, `base-3`, …, then a 6-char
45
+ * random suffix as a final fallback.
46
+ *
47
+ * Reserved slugs (operational subdomain names, brand-protected words)
48
+ * can be passed via `reserved`; matches are skipped.
49
+ *
50
+ * Caller still wraps the eventual insert in try/catch — TOCTOU is
51
+ * always possible with this kind of "check then write" probe, and
52
+ * the framework's UNIQUE index is the actual source of truth. The
53
+ * helper just minimises the number of avoidable retries.
54
+ *
55
+ * @example
56
+ * ```ts
57
+ * const slug = await availableSlug(ctx.db, {
58
+ * entity: "Workspace",
59
+ * field: "slug",
60
+ * name: args.name,
61
+ * reserved: RESERVED_SUBDOMAINS,
62
+ * });
63
+ * await ctx.db.insert("Workspace", { slug, ... });
64
+ * ```
65
+ */
66
+ export async function availableSlug(
67
+ db: DbReader | DbWriter,
68
+ options: {
69
+ entity: string;
70
+ field?: string;
71
+ name: string;
72
+ reserved?: ReadonlySet<string> | readonly string[];
73
+ /** Max numeric suffix to try before falling back to random. Default: 50. */
74
+ maxNumericTries?: number;
75
+ },
76
+ ): Promise<string> {
77
+ const field = options.field ?? "slug";
78
+ const reserved = toSet(options.reserved);
79
+ const base = slugifyName(options.name);
80
+ const max = options.maxNumericTries ?? 50;
81
+
82
+ const candidates: string[] = [base];
83
+ for (let i = 2; i <= max; i++) candidates.push(`${base}-${i}`);
84
+
85
+ for (const candidate of candidates) {
86
+ if (reserved.has(candidate)) continue;
87
+ const dup = await db.query(options.entity, { [field]: candidate, $limit: 1 });
88
+ if (dup.length === 0) return candidate;
89
+ }
90
+
91
+ // Random suffix fallback. Uses an unambiguous-looking alphabet (no
92
+ // 0/O/1/l) so the slug is readable in URLs.
93
+ const alphabet = "abcdefghjkmnpqrstuvwxyz23456789";
94
+ let rand = "";
95
+ for (let i = 0; i < 6; i++) {
96
+ rand += alphabet[Math.floor(Math.random() * alphabet.length)];
97
+ }
98
+ return `${base}-${rand}`;
99
+ }
100
+
101
+ function toSet(
102
+ input: ReadonlySet<string> | readonly string[] | undefined,
103
+ ): ReadonlySet<string> {
104
+ if (!input) return new Set<string>();
105
+ if (input instanceof Set) return input;
106
+ return new Set(input);
107
+ }