@asteroidcms/core-utils 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,13 +5,13 @@
5
5
  <span>/core-utils</span>
6
6
  </div>
7
7
  </h1>
8
- <p>Seamless integration utilities for <a href="https://cms.theasteroid.tech">Asteroid CMS</a> a single React provider, Apollo client, content hooks, media helpers, and a rich-text renderer.</p>
8
+ <p>Seamless integration utilities for <a href="https://cms.theasteroid.tech">Asteroid CMS</a> - a single React provider, Apollo client, content hooks, media helpers, and a rich-text renderer.</p>
9
9
  </div>
10
10
 
11
- - **Provider-driven** configure `cmsUrl`, `apiKey`, and Apollo behavior in one place
12
- - **API-key auth only** sends `x-api-key` on every request, nothing else
13
- - **Typed hooks** `useCmsContent` / `useCmsMutate` build GraphQL on the fly from a declarative selection
14
- - **Tree-shakeable** ESM + CJS + types, `@apollo/client`/`react` as peer deps
11
+ - **Provider-driven** - configure `cmsUrl`, `apiKey`, and Apollo behavior in one place
12
+ - **API-key auth only** - sends `x-api-key` on every request, nothing else
13
+ - **Typed hooks** - `useCmsContent` / `useCmsMutate` build GraphQL on the fly from a declarative selection
14
+ - **Tree-shakeable** - ESM + CJS + types, `@apollo/client`/`react` as peer deps
15
15
 
16
16
  ---
17
17
 
@@ -82,15 +82,15 @@ function NewsList() {
82
82
 
83
83
  | Prop | Type | Required | Default | Description |
84
84
  | --------------- | ------------------------------ | -------- | ------------------ | ------------------------------------------------------------ |
85
- | `cmsUrl` | `string` | ✓ | | Base URL of the Asteroid CMS API. |
86
- | `apiKey` | `string` | ✓ | | Sent on every request as the `x-api-key` header. |
85
+ | `cmsUrl` | `string` | ✓ | - | Base URL of the Asteroid CMS API. |
86
+ | `apiKey` | `string` | ✓ | - | Sent on every request as the `x-api-key` header. |
87
87
  | `graphqlPath` | `string` | | `/graphql` | Path appended to `cmsUrl` for the GraphQL endpoint. |
88
88
  | `mediaPath` | `string` | | `/media/canonical` | Path used by `cmsImage` / `useCmsImage`. |
89
89
  | `headers` | `Record<string, string>` | | `{}` | Extra headers merged onto every GraphQL request. |
90
- | `onError` | `(error: unknown) => void` | | | Called for each GraphQL / network / protocol error. |
91
- | `cacheConfig` | `InMemoryCacheConfig` | | | Forwarded to `new InMemoryCache(...)` e.g. `typePolicies`. |
92
- | `apolloOptions` | `Partial<ApolloClientOptions>` | | | Escape hatch overrides any field on the Apollo client. |
93
- | `client` | `ApolloClient` | | | Bring your own pre-built client; skips the internal factory. |
90
+ | `onError` | `(error: unknown) => void` | | - | Called for each GraphQL / network / protocol error. |
91
+ | `cacheConfig` | `InMemoryCacheConfig` | | - | Forwarded to `new InMemoryCache(...)` - e.g. `typePolicies`. |
92
+ | `apolloOptions` | `Partial<ApolloClientOptions>` | | - | Escape hatch - overrides any field on the Apollo client. |
93
+ | `client` | `ApolloClient` | | - | Bring your own pre-built client; skips the internal factory. |
94
94
 
95
95
  Example with everything wired:
96
96
 
@@ -195,6 +195,77 @@ const { data: topStories } = useCmsContent({
195
195
 
196
196
  ---
197
197
 
198
+ ## `fetchCmsContent` (Next.js / RSC)
199
+
200
+ Server-side counterpart to `useCmsContent`. Use it in Next.js Server Components, route handlers, or any other server context. Accepts a server-side Apollo client plus the same options object as `useCmsContent`, and returns the resolved data directly.
201
+
202
+ Pass a `getClient` function that returns a server-side Apollo client. The shape matches what `registerApolloClient` from `@apollo/client-integration-nextjs` already returns, so you can hand it through directly.
203
+
204
+ ```ts
205
+ // app/lib/cms-server.ts
206
+ import "server-only";
207
+ import { ApolloClient, HttpLink, InMemoryCache } from "@apollo/client";
208
+ import { registerApolloClient } from "@apollo/client-integration-nextjs";
209
+
210
+ export const { getClient, query, PreloadQuery } = registerApolloClient(() => {
211
+ return new ApolloClient({
212
+ cache: new InMemoryCache(),
213
+ link: new HttpLink({
214
+ uri: `${process.env.CMS_API_BASE_URL}/graphql`,
215
+ headers: { "X-API-Key": process.env.CMS_X_API_KEY ?? "" },
216
+ fetchOptions: { next: { revalidate: 60, tags: ["cms:landing_page"] } },
217
+ }),
218
+ });
219
+ });
220
+ ```
221
+
222
+ ```ts
223
+ // app/news/[slug]/page.tsx
224
+ import { fetchCmsContent } from "@asteroidcms/core-utils";
225
+ import { getClient } from "@/app/lib/cms-server";
226
+
227
+ // Single entry
228
+ const article = await fetchCmsContent<Article>(getClient, {
229
+ schema_slug: "news",
230
+ entrySlug: params.slug,
231
+ fullData: true,
232
+ });
233
+
234
+ // List
235
+ const articles = await fetchCmsContent<Article[]>(getClient, {
236
+ schema_slug: "news",
237
+ limit: 10,
238
+ status: "PUBLISHED",
239
+ select: ["title", "slug", "publish_date"],
240
+ });
241
+ ```
242
+
243
+ Outside Next.js you can pass any `() => ApolloClient` - e.g. `() => createApolloClient({ cmsUrl, apiKey })`.
244
+
245
+ Add `import "server-only"` in the file that calls it if you want Next.js to fail the build when it leaks into a client component.
246
+
247
+ ---
248
+
249
+ ## `buildCmsQuery`
250
+
251
+ Lower-level helper that turns a declarative selection into a GraphQL `DocumentNode` plus variables. Used internally by `useCmsContent` and `fetchCmsContent`; exported so you can drive your own Apollo calls (cache reads, prefetching, batching, etc.).
252
+
253
+ ```ts
254
+ import { buildCmsQuery } from "@asteroidcms/core-utils";
255
+
256
+ const { query, variables, isSingle } = buildCmsQuery({
257
+ schema_slug: "news",
258
+ limit: 10,
259
+ status: "PUBLISHED",
260
+ select: ["title", "slug"],
261
+ });
262
+
263
+ const { data } = await apolloClient.query({ query, variables });
264
+ const entries = isSingle ? data.entry : data.entries;
265
+ ```
266
+
267
+ ---
268
+
198
269
  ## `useCmsMutate`
199
270
 
200
271
  `create` / `update` / `delete` against a schema, with the same selection syntax.
@@ -244,7 +315,7 @@ removeComment();
244
315
  Build a canonical media URL for an asset id.
245
316
 
246
317
  ```tsx
247
- // Inside React preferred
318
+ // Inside React - preferred
248
319
  const cmsImage = useCmsImage();
249
320
  <img src={cmsImage(article.cover_image)} alt="" />;
250
321
 
@@ -255,6 +326,34 @@ cmsImage(id, { cmsUrl: "https://cms-api.example.com" });
255
326
 
256
327
  ---
257
328
 
329
+ ## `getContentReadTime`
330
+
331
+ Estimate reading time for a string of content (plain text or HTML). Strips tags, decodes common entities, counts words, and formats the result.
332
+
333
+ ```ts
334
+ import { getContentReadTime } from "@asteroidcms/core-utils";
335
+
336
+ getContentReadTime(article.body);
337
+ // "3 min read"
338
+
339
+ getContentReadTime(article.body, {
340
+ wordsPerMinute: 220,
341
+ format: "long",
342
+ round: "round",
343
+ minMinutes: 1,
344
+ });
345
+ // "3 minutes read"
346
+ ```
347
+
348
+ | Option | Type | Default | Description |
349
+ | ---------------- | ------------------------------- | --------- | ------------------------------------------------- |
350
+ | `wordsPerMinute` | `number` | `200` | Average reading speed. |
351
+ | `format` | `"short" \| "long"` | `"short"` | `"3 min read"` vs `"3 minutes read"`. |
352
+ | `round` | `"ceil" \| "round" \| "floor"` | `"ceil"` | How fractional minutes are rounded. |
353
+ | `minMinutes` | `number` | `1` | Floor for the returned value. |
354
+
355
+ ---
356
+
258
357
  ## `<RichTextContent>`
259
358
 
260
359
  Render Asteroid CMS rich-text JSON/HTML with syntax-highlighted code blocks (via `highlight.js`).
@@ -282,7 +381,7 @@ const html = parseRichText(article.body, {
282
381
 
283
382
  ---
284
383
 
285
- ## Advanced bring your own Apollo client
384
+ ## Advanced - bring your own Apollo client
286
385
 
287
386
  ```tsx
288
387
  import { ApolloClient, InMemoryCache } from "@apollo/client";
@@ -320,8 +419,8 @@ npm run build # writes dist/index.js, dist/index.cjs, dist/index.d.ts
320
419
 
321
420
  ## License
322
421
 
323
- Proprietary Copyright © Asteroid. All rights reserved.
422
+ Proprietary - Copyright © Asteroid. All rights reserved.
324
423
 
325
424
  This package is licensed for use only; copying, modifying, or
326
- redistributing the source in whole or in part is not permitted.
425
+ redistributing the source - in whole or in part - is not permitted.
327
426
  See [LICENSE](./LICENSE) for the full terms.
package/dist/index.cjs CHANGED
@@ -119,7 +119,7 @@ function useCmsContent({
119
119
  variables = {}
120
120
  }) {
121
121
  const isSingle = !!entrySlug;
122
- const buildSelection = (items = []) => {
122
+ const buildSelection2 = (items = []) => {
123
123
  const lines = [];
124
124
  items.forEach((item) => {
125
125
  if (typeof item === "string") {
@@ -132,7 +132,7 @@ function useCmsContent({
132
132
  }
133
133
  const alias = item.as || item.field;
134
134
  const resolver = item.single ? "expandedReferenceObject" : "expandedReference";
135
- const subSelection = item.select?.length ? buildSelection(item.select) : "data { ... }";
135
+ const subSelection = item.select?.length ? buildSelection2(item.select) : "data { ... }";
136
136
  lines.push(`
137
137
  ${alias}: ${resolver}(slug: "${item.field}") {
138
138
  ${subSelection}
@@ -145,7 +145,7 @@ function useCmsContent({
145
145
  const selectionParts = [];
146
146
  if (fullData) selectionParts.push("data");
147
147
  if (select.length > 0) {
148
- const userSelection = buildSelection(select);
148
+ const userSelection = buildSelection2(select);
149
149
  if (userSelection) selectionParts.push(userSelection);
150
150
  }
151
151
  const selection = selectionParts.join("\n ").trim() || "id";
@@ -229,7 +229,7 @@ function useCmsMutate({
229
229
  entryId,
230
230
  variables: inputVariables = {}
231
231
  }) {
232
- const buildSelection = (items = []) => {
232
+ const buildSelection2 = (items = []) => {
233
233
  const lines = [];
234
234
  for (const item of items) {
235
235
  if (typeof item === "string") {
@@ -243,7 +243,7 @@ function useCmsMutate({
243
243
  continue;
244
244
  }
245
245
  const resolver = single ? "expandedReferenceObject" : "expandedReference";
246
- const sub = buildSelection(subSelect) || "id slug";
246
+ const sub = buildSelection2(subSelect) || "id slug";
247
247
  lines.push(`
248
248
  ${alias}: ${resolver}(slug: "${field}") {
249
249
  id
@@ -254,7 +254,7 @@ function useCmsMutate({
254
254
  }
255
255
  return lines.join("\n ").trim();
256
256
  };
257
- const userSelection = buildSelection(select);
257
+ const userSelection = buildSelection2(select);
258
258
  let selection = fullData ? "data" : "";
259
259
  if (userSelection) {
260
260
  selection = selection ? `${selection}
@@ -311,6 +311,129 @@ function useCmsMutate({
311
311
  data: resultData
312
312
  };
313
313
  }
314
+ function buildSelection(items = []) {
315
+ const lines = [];
316
+ items.forEach((item) => {
317
+ if (typeof item === "string") {
318
+ lines.push(`${item}: dataField(slug: "${item}")`);
319
+ return;
320
+ }
321
+ if ("field" in item && typeof item.field === "string") {
322
+ if (!("select" in item)) {
323
+ const alias2 = item.as || item.field;
324
+ lines.push(`${alias2}: dataField(slug: "${item.field}")`);
325
+ return;
326
+ }
327
+ const alias = item.as || item.field;
328
+ const resolver = item.single ? "expandedReferenceObject" : "expandedReference";
329
+ const subSelection = item.select?.length ? buildSelection(item.select) : "data { ... }";
330
+ lines.push(`
331
+ ${alias}: ${resolver}(slug: "${item.field}") {
332
+ ${subSelection}
333
+ }
334
+ `);
335
+ }
336
+ });
337
+ return lines.join("\n ").trim();
338
+ }
339
+ function buildCmsQuery({
340
+ schema_slug,
341
+ entrySlug,
342
+ select = [],
343
+ fullData = false,
344
+ limit,
345
+ offset,
346
+ status = "PUBLISHED",
347
+ filter,
348
+ search,
349
+ variables = {}
350
+ }) {
351
+ const isSingle = Boolean(entrySlug);
352
+ const selectionParts = [];
353
+ if (fullData) {
354
+ selectionParts.push("data");
355
+ }
356
+ if (select.length > 0) {
357
+ const userSelection = buildSelection(select);
358
+ if (userSelection) {
359
+ selectionParts.push(userSelection);
360
+ }
361
+ }
362
+ const selection = selectionParts.join("\n ").trim() || "id";
363
+ const queryVariables = {
364
+ schema_slug,
365
+ ...entrySlug && { slug: entrySlug },
366
+ ...variables
367
+ };
368
+ const fieldArgParts = ["schema_slug: $schema_slug"];
369
+ if (!isSingle) {
370
+ if (typeof limit === "number" && limit >= 0) {
371
+ fieldArgParts.push("limit: $limit");
372
+ queryVariables.limit = limit;
373
+ }
374
+ if (typeof offset === "number" && offset >= 0) {
375
+ fieldArgParts.push("offset: $offset");
376
+ queryVariables.offset = offset;
377
+ }
378
+ if (status) {
379
+ const statuses = status;
380
+ if (statuses.length > 0) {
381
+ fieldArgParts.push("status: $status");
382
+ queryVariables.status = statuses;
383
+ }
384
+ }
385
+ const hasSearch = Array.isArray(search) && search.length > 0;
386
+ const hasFilter = filter && typeof filter === "object" && Object.keys(filter).length > 0;
387
+ if (hasSearch || hasFilter) {
388
+ const mergedFilter = hasFilter ? { ...filter } : {};
389
+ if (hasSearch) {
390
+ for (const condition of search) {
391
+ mergedFilter[condition.field] = {
392
+ regex: true,
393
+ value: condition.value,
394
+ mode: condition.mode ?? "i"
395
+ };
396
+ }
397
+ }
398
+ fieldArgParts.push("data: $filter");
399
+ queryVariables.filter = mergedFilter;
400
+ }
401
+ }
402
+ const varDecls = ["$schema_slug: String!"];
403
+ if ("limit" in queryVariables) varDecls.push("$limit: Float");
404
+ if ("offset" in queryVariables) varDecls.push("$offset: Float");
405
+ if ("status" in queryVariables) varDecls.push("$status: ContentStatus");
406
+ if ("filter" in queryVariables) varDecls.push("$filter: JSONObject");
407
+ const varBlock = varDecls.length > 0 ? `(
408
+ ${varDecls.join("\n ")}
409
+ )` : "";
410
+ const contentFieldArgs = fieldArgParts.join(", ");
411
+ const queryStr = isSingle ? `
412
+ query Get${schema_slug}Entry($schema_slug: String!, $slug: String!) {
413
+ entry: contentEntry(schema_slug: $schema_slug, slug: $slug) {
414
+ ${selection}
415
+ }
416
+ }
417
+ ` : `
418
+ query Get${schema_slug}Entries${varBlock} {
419
+ entries: contentEntries(${contentFieldArgs}) {
420
+ ${selection}
421
+ }
422
+ }
423
+ `;
424
+ return {
425
+ query: client.gql(queryStr),
426
+ variables: queryVariables,
427
+ isSingle
428
+ };
429
+ }
430
+
431
+ // src/fetchCmsContent.ts
432
+ async function fetchCmsContent(getClient, opts) {
433
+ const { query, variables, isSingle } = buildCmsQuery(opts);
434
+ const { data } = await getClient().query({ query, variables });
435
+ return isSingle ? data.entry : data.entries;
436
+ }
314
437
 
315
438
  // src/utils/cmsImage.ts
316
439
  function cmsImage(id, options) {
@@ -324,6 +447,35 @@ function useCmsImage() {
324
447
  return (id) => cmsImage(id, { cmsUrl, mediaPath });
325
448
  }
326
449
 
450
+ // src/utils/getContentReadTime.ts
451
+ function getContentReadTime(content, options = {}) {
452
+ const {
453
+ wordsPerMinute = 200,
454
+ format = "short",
455
+ round = "ceil",
456
+ minMinutes = 1
457
+ } = options;
458
+ if (!content || typeof content !== "string") {
459
+ return format === "short" ? `${minMinutes} min read` : `${minMinutes} minute read`;
460
+ }
461
+ let text = content.replace(/<script[\s\S]*?<\/script>/gi, " ").replace(/<style[\s\S]*?<\/style>/gi, " ");
462
+ text = text.replace(/<\/(p|div|h[1-6]|li|blockquote|pre|code|br|tr)>/gi, " ").replace(/<[^>]+>/g, " ");
463
+ text = text.replace(/&nbsp;/gi, " ").replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&#39;/gi, "'").replace(/&quot;/gi, '"');
464
+ text = text.replace(/\s+/g, " ").trim();
465
+ const words = text.split(" ").filter(Boolean).length;
466
+ const rawMinutes = words / wordsPerMinute;
467
+ const roundMap = {
468
+ ceil: Math.ceil,
469
+ round: Math.round,
470
+ floor: Math.floor
471
+ };
472
+ const minutes = Math.max(minMinutes, roundMap[round](rawMinutes));
473
+ if (format === "long") {
474
+ return `${minutes} ${minutes === 1 ? "minute" : "minutes"} read`;
475
+ }
476
+ return `${minutes} min read`;
477
+ }
478
+
327
479
  // src/components/richTextParser.ts
328
480
  var DEFAULT_ALLOWLIST = [
329
481
  "p",
@@ -1458,8 +1610,11 @@ function RichTextContent({
1458
1610
 
1459
1611
  exports.AsteroidCMSProvider = AsteroidCMSProvider;
1460
1612
  exports.RichTextContent = RichTextContent;
1613
+ exports.buildCmsQuery = buildCmsQuery;
1461
1614
  exports.cmsImage = cmsImage;
1462
1615
  exports.createApolloClient = createApolloClient;
1616
+ exports.fetchCmsContent = fetchCmsContent;
1617
+ exports.getContentReadTime = getContentReadTime;
1463
1618
  exports.parseRichText = parseRichText;
1464
1619
  exports.removeEmptyParagraphs = removeEmptyParagraphs;
1465
1620
  exports.useAsteroidCMSConfig = useAsteroidCMSConfig;