@contello/astro 1.4.2 → 2.1.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/dist/index.js CHANGED
@@ -5,6 +5,203 @@ import { createMediaResolver } from "@contello/media";
5
5
  import {
6
6
  createStore
7
7
  } from "@contello/store";
8
+
9
+ // src/assets-middleware.ts
10
+ import { defineMiddleware } from "astro/middleware";
11
+
12
+ // src/diagnostics.ts
13
+ import dc from "diagnostics_channel";
14
+ var channels = {
15
+ start: "@contello/astro:start",
16
+ end: "@contello/astro:end",
17
+ error: "@contello/astro:error"
18
+ };
19
+ var onStart = dc.channel(channels.start);
20
+ var onEnd = dc.channel(channels.end);
21
+ var onError = dc.channel(channels.error);
22
+ function hasSubscribers() {
23
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
24
+ }
25
+ function wrap(name, fn) {
26
+ if (!hasSubscribers()) {
27
+ return fn();
28
+ }
29
+ const start = performance.now();
30
+ onStart.publish({ name });
31
+ let result;
32
+ try {
33
+ result = fn();
34
+ } catch (error) {
35
+ onError.publish({ name, error, durationMs: performance.now() - start });
36
+ throw error;
37
+ }
38
+ if (result instanceof Promise) {
39
+ return result.then(
40
+ (r) => {
41
+ onEnd.publish({ name, durationMs: performance.now() - start });
42
+ return r;
43
+ },
44
+ (error) => {
45
+ onError.publish({ name, error, durationMs: performance.now() - start });
46
+ throw error;
47
+ }
48
+ );
49
+ }
50
+ onEnd.publish({ name, durationMs: performance.now() - start });
51
+ return result;
52
+ }
53
+
54
+ // src/assets-middleware.ts
55
+ var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
56
+ function createBoundAssetsMiddleware(contello, options) {
57
+ const imagesPrefix = contello.media.imagesPath;
58
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
59
+ const filesPrefix = contello.media.filesPath;
60
+ const filesCacheControl = options?.files?.cacheControl;
61
+ const videoPrefix = contello.media.videosPath;
62
+ return defineMiddleware((ctx, next) => {
63
+ const { pathname } = ctx.url;
64
+ const isImage = pathname.startsWith(imagesPrefix);
65
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
66
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
67
+ if (!isImage && !isFile && !isVideo) {
68
+ return next();
69
+ }
70
+ if (!contello.isReady) {
71
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
72
+ return next();
73
+ }
74
+ if (isImage) {
75
+ return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
76
+ }
77
+ if (isFile) {
78
+ return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
79
+ }
80
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
81
+ });
82
+ }
83
+ function handleFile(client, next, rest, cacheControl) {
84
+ const dot = rest.indexOf(".");
85
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
86
+ if (!fileId) {
87
+ return next();
88
+ }
89
+ return wrap("assets:file", () => client.download(fileId)).then(
90
+ (result) => {
91
+ const headers = new Headers({ "content-type": result.mimeType });
92
+ if (cacheControl) {
93
+ headers.set("cache-control", cacheControl);
94
+ }
95
+ if (result.size) {
96
+ headers.set("content-length", String(result.size));
97
+ }
98
+ return new Response(result.stream(), { headers });
99
+ },
100
+ () => new Response(null, { status: 404 })
101
+ );
102
+ }
103
+ function handleVideo(client, next, path, signal) {
104
+ if (!path) {
105
+ return next();
106
+ }
107
+ return wrap("assets:hls", () => client.proxyHls(path, signal)).then(
108
+ (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
109
+ () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
110
+ );
111
+ }
112
+
113
+ // src/routing-middleware.ts
114
+ import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
115
+ import {
116
+ maybeThen
117
+ } from "@contello/store";
118
+ import { defineMiddleware as defineMiddleware2 } from "astro/middleware";
119
+ function customHeaders(headers) {
120
+ const result = {};
121
+ for (const h of headers) {
122
+ result[h.name] = h.value;
123
+ }
124
+ return result;
125
+ }
126
+ function createBoundRoutingMiddleware(contello, routes, exclude) {
127
+ return defineMiddleware2((ctx, next) => {
128
+ if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
129
+ return next();
130
+ }
131
+ if (!contello.isReady) {
132
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
133
+ return next();
134
+ }
135
+ const { url } = ctx;
136
+ if (url.pathname.startsWith("/contello/entities/")) {
137
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
138
+ }
139
+ const lookup = routes.getByPath(url.pathname);
140
+ return maybeThen(lookup, (route) => {
141
+ if (!route) {
142
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
143
+ }
144
+ switch (route.type) {
145
+ case "redirect":
146
+ return contello[runRequest](
147
+ { url, route, rewritten: false },
148
+ () => wrap(
149
+ "route:redirect",
150
+ () => new Response(null, {
151
+ status: route.status,
152
+ headers: {
153
+ Location: route.location,
154
+ ...customHeaders(route.customHeaders)
155
+ }
156
+ })
157
+ )
158
+ );
159
+ case "text":
160
+ return contello[runRequest](
161
+ { url, route, rewritten: false },
162
+ () => wrap(
163
+ "route:text",
164
+ () => new Response(route.content, {
165
+ status: 200,
166
+ headers: {
167
+ "Content-Type": route.mimeType,
168
+ ...customHeaders(route.customHeaders)
169
+ }
170
+ })
171
+ )
172
+ );
173
+ case "asset":
174
+ return contello[runRequest](
175
+ { url, route, rewritten: false },
176
+ () => wrap("route:asset", async () => {
177
+ const result = await contello.client.download(route.fileId);
178
+ const headers = new Headers({ "content-type": result.mimeType });
179
+ if (result.size) {
180
+ headers.set("content-length", String(result.size));
181
+ }
182
+ for (const { name, value } of route.customHeaders) {
183
+ headers.set(name, value);
184
+ }
185
+ return new Response(result.stream(), { headers });
186
+ })
187
+ );
188
+ case "entity":
189
+ return contello[runRequest](
190
+ { url, route, rewritten: true },
191
+ () => wrap(`route:entity:${route.model}`, async () => {
192
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
193
+ for (const { name, value } of route.customHeaders) {
194
+ response.headers.set(name, value);
195
+ }
196
+ return response;
197
+ })
198
+ );
199
+ }
200
+ });
201
+ });
202
+ }
203
+
204
+ // src/contello.ts
8
205
  var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
9
206
  var DEFAULT_FILES_PREFIX = "/_contello/f/";
10
207
  var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
@@ -46,12 +243,12 @@ async function applyTranslations(messages) {
46
243
  var Contello = class {
47
244
  _store;
48
245
  _options;
49
- _assets;
50
- _routes;
51
246
  _i18nMessages;
52
- _i18nSubscription;
247
+ _i18nUnsubscribe;
53
248
  _initialized = false;
54
249
  _als = new AsyncLocalStorage();
250
+ _autoEagerRoutes;
251
+ _autoLazyRoutes;
55
252
  media;
56
253
  constructor(options) {
57
254
  this._options = options;
@@ -67,12 +264,10 @@ var Contello = class {
67
264
  async init(options) {
68
265
  try {
69
266
  await this._store.init();
70
- this._assets = this._store.defineAssets(this._options.assets);
71
- this._routes = this._store.defineRoutes(this._options.routes);
72
267
  if (this._options.i18n) {
73
- const { collection, languages } = this._options.i18n;
268
+ const { collection, languages, cache } = this._options.i18n;
74
269
  const { register = true, load = true } = options?.i18n ?? {};
75
- this._i18nMessages = this._store.defineI18nMessages({ collection });
270
+ this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
76
271
  await i18n.configure({ locales: languages });
77
272
  if (register) {
78
273
  const registrations = buildI18nRegistrations();
@@ -83,12 +278,20 @@ var Contello = class {
83
278
  if (load) {
84
279
  await applyTranslations(this._i18nMessages);
85
280
  const messages = this._i18nMessages;
86
- this._i18nSubscription = messages.refresh$.subscribe(() => applyTranslations(messages));
281
+ const controller = new AbortController();
282
+ this._i18nUnsubscribe = () => controller.abort();
283
+ void (async () => {
284
+ for await (const _ of messages.refresh$) {
285
+ if (controller.signal.aborted) {
286
+ return;
287
+ }
288
+ await applyTranslations(messages);
289
+ }
290
+ })();
87
291
  }
88
292
  }
89
- if (options?.load) {
90
- await Promise.all(options.load.map((l) => l.load()));
91
- }
293
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
294
+ await Promise.all(loadables.map((l) => l.load()));
92
295
  this._initialized = true;
93
296
  } catch (err) {
94
297
  await this.destroy().catch(() => {
@@ -98,11 +301,9 @@ var Contello = class {
98
301
  }
99
302
  async destroy() {
100
303
  this._initialized = false;
101
- this._i18nSubscription?.unsubscribe();
102
- this._i18nSubscription = void 0;
304
+ this._i18nUnsubscribe?.();
305
+ this._i18nUnsubscribe = void 0;
103
306
  await this._store.destroy();
104
- this._assets = void 0;
105
- this._routes = void 0;
106
307
  this._i18nMessages = void 0;
107
308
  }
108
309
  ping() {
@@ -111,18 +312,8 @@ var Contello = class {
111
312
  get isReady() {
112
313
  return this._initialized;
113
314
  }
114
- // --- pre-wired collections ---
115
- get assets() {
116
- if (!this._assets) {
117
- throw new Error("@contello/astro: .assets accessed before init()");
118
- }
119
- return this._assets;
120
- }
121
- get routes() {
122
- if (!this._routes) {
123
- throw new Error("@contello/astro: .routes accessed before init()");
124
- }
125
- return this._routes;
315
+ get client() {
316
+ return this._store.client;
126
317
  }
127
318
  get i18nMessages() {
128
319
  if (!this._i18nMessages) {
@@ -146,223 +337,64 @@ var Contello = class {
146
337
  });
147
338
  }
148
339
  // --- store delegation ---
149
- defineSingleton(def) {
150
- return this._store.defineSingleton(def);
340
+ defineSingleton(sourceOrKey, options) {
341
+ return this._store.defineSingleton(sourceOrKey, options);
151
342
  }
152
- defineSingletonSync(def) {
153
- return this._store.defineSingletonSync(def);
343
+ defineSingletonSync(sourceOrKey, options) {
344
+ return this._store.defineSingletonSync(sourceOrKey, options);
154
345
  }
155
- defineCollection(def) {
156
- return this._store.defineCollection(def);
346
+ defineCollection(sourceOrKey, options) {
347
+ return this._store.defineCollection(sourceOrKey, options);
157
348
  }
158
- defineCollectionSync(def) {
159
- return this._store.defineCollectionSync(def);
349
+ defineCollectionSync(sourceOrKey, options) {
350
+ return this._store.defineCollectionSync(sourceOrKey, options);
160
351
  }
161
- defineLazyCollection(def) {
162
- return this._store.defineLazyCollection(def);
352
+ defineLazyCollection(sourceOrKey, options) {
353
+ return this._store.defineLazyCollection(sourceOrKey, options);
163
354
  }
164
- // --- ALS run ---
165
- [runRequest](ctx, fn) {
166
- return this._als.run(ctx, fn);
355
+ defineRoutes(options) {
356
+ return this._store.defineRoutes(options);
167
357
  }
168
- };
169
- function createContello(options) {
170
- return new Contello(options);
171
- }
172
-
173
- // src/assets-middleware.ts
174
- import { defineMiddleware } from "astro/middleware";
175
-
176
- // src/diagnostics.ts
177
- import dc from "diagnostics_channel";
178
- var channels = {
179
- start: "@contello/astro:start",
180
- end: "@contello/astro:end",
181
- error: "@contello/astro:error"
182
- };
183
- var onStart = dc.channel(channels.start);
184
- var onEnd = dc.channel(channels.end);
185
- var onError = dc.channel(channels.error);
186
- function hasSubscribers() {
187
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
188
- }
189
- function wrap(name, fn) {
190
- if (!hasSubscribers()) {
191
- return fn();
358
+ defineRoutesSync(options) {
359
+ return this._store.defineRoutesSync(options);
192
360
  }
193
- const start = performance.now();
194
- onStart.publish({ name });
195
- let result;
196
- try {
197
- result = fn();
198
- } catch (error) {
199
- onError.publish({ name, error, durationMs: performance.now() - start });
200
- throw error;
361
+ defineLazyRoutes(options) {
362
+ return this._store.defineLazyRoutes(options);
201
363
  }
202
- if (result instanceof Promise) {
203
- return result.then(
204
- (r) => {
205
- onEnd.publish({ name, durationMs: performance.now() - start });
206
- return r;
207
- },
208
- (error) => {
209
- onError.publish({ name, error, durationMs: performance.now() - start });
210
- throw error;
211
- }
212
- );
364
+ defineAssets(options) {
365
+ return this._store.defineAssets(options);
213
366
  }
214
- onEnd.publish({ name, durationMs: performance.now() - start });
215
- return result;
216
- }
217
-
218
- // src/assets-middleware.ts
219
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
220
- function createAssetsMiddleware(instance, options) {
221
- const imagesPrefix = instance.media.imagesPath;
222
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
223
- const filesPrefix = instance.media.filesPath;
224
- const filesCacheControl = options?.files?.cacheControl;
225
- const videoPrefix = instance.media.videosPath;
226
- return defineMiddleware((ctx, next) => {
227
- const { pathname } = ctx.url;
228
- const isImage = pathname.startsWith(imagesPrefix);
229
- const isFile = !isImage && pathname.startsWith(filesPrefix);
230
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
231
- if (!isImage && !isFile && !isVideo) {
232
- return next();
233
- }
234
- if (!instance.isReady) {
235
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
236
- return next();
237
- }
238
- if (isImage) {
239
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
240
- }
241
- if (isFile) {
242
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
243
- }
244
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
245
- });
246
- }
247
- function handleFile(instance, next, rest, cacheControl) {
248
- const dot = rest.indexOf(".");
249
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
250
- if (!fileId) {
251
- return next();
367
+ defineAssetsSync(options) {
368
+ return this._store.defineAssetsSync(options);
252
369
  }
253
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
254
- (result) => {
255
- const headers = new Headers({ "content-type": result.mimeType });
256
- if (cacheControl) {
257
- headers.set("cache-control", cacheControl);
258
- }
259
- if (result.size) {
260
- headers.set("content-length", String(result.size));
261
- }
262
- return new Response(result.stream(), { headers });
263
- },
264
- () => new Response(null, { status: 404 })
265
- );
266
- }
267
- function handleVideo(instance, next, path, signal) {
268
- if (!path) {
269
- return next();
370
+ defineLazyAssets(options) {
371
+ return this._store.defineLazyAssets(options);
270
372
  }
271
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
272
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
273
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
274
- );
275
- }
276
-
277
- // src/routing-middleware.ts
278
- import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
279
- import { defineMiddleware as defineMiddleware2 } from "astro/middleware";
280
- function customHeaders(headers) {
281
- const result = {};
282
- for (const h of headers) {
283
- result[h.name] = h.value;
284
- }
285
- return result;
286
- }
287
- function createRoutingMiddleware(instance, options) {
288
- const { exclude } = options ?? {};
289
- return defineMiddleware2(async (ctx, next) => {
290
- if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
291
- return next();
292
- }
293
- if (!instance.isReady) {
294
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
295
- return next();
296
- }
297
- const { url } = ctx;
298
- if (url.pathname.startsWith("/contello/entities/")) {
299
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
300
- }
301
- const route = await instance.routes.getByPath(url.pathname);
302
- if (!route) {
303
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
373
+ // --- middleware factories (arrow fields so destructuring works) ---
374
+ createRoutingMiddleware = (options) => {
375
+ const routesOption = options?.routes ?? "eager";
376
+ let routes;
377
+ if (routesOption === "eager") {
378
+ routes = this._autoEagerRoutes ??= this.defineRoutesSync();
379
+ } else if (routesOption === "lazy") {
380
+ routes = this._autoLazyRoutes ??= this.defineLazyRoutes();
381
+ } else {
382
+ routes = routesOption;
304
383
  }
305
- switch (route.type) {
306
- case "redirect":
307
- return instance[runRequest](
308
- { url, route, rewritten: false },
309
- () => wrap(
310
- "route:redirect",
311
- () => new Response(null, {
312
- status: route.status,
313
- headers: {
314
- Location: route.location,
315
- ...customHeaders(route.customHeaders)
316
- }
317
- })
318
- )
319
- );
320
- case "text":
321
- return instance[runRequest](
322
- { url, route, rewritten: false },
323
- () => wrap(
324
- "route:text",
325
- () => new Response(route.content, {
326
- status: 200,
327
- headers: {
328
- "Content-Type": route.mimeType,
329
- ...customHeaders(route.customHeaders)
330
- }
331
- })
332
- )
333
- );
334
- case "asset":
335
- return instance[runRequest](
336
- { url, route, rewritten: false },
337
- () => wrap("route:asset", async () => {
338
- const result = await instance.assets.download(route.fileId);
339
- const headers = new Headers({ "content-type": result.mimeType });
340
- if (result.size) {
341
- headers.set("content-length", String(result.size));
342
- }
343
- for (const { name, value } of route.customHeaders) {
344
- headers.set(name, value);
345
- }
346
- return new Response(result.stream(), { headers });
347
- })
348
- );
349
- case "entity":
350
- return instance[runRequest](
351
- { url, route, rewritten: true },
352
- () => wrap(`route:entity:${route.model}`, async () => {
353
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
354
- for (const { name, value } of route.customHeaders) {
355
- response.headers.set(name, value);
356
- }
357
- return response;
358
- })
359
- );
360
- }
361
- });
384
+ return createBoundRoutingMiddleware(this, routes, options?.exclude);
385
+ };
386
+ createAssetsMiddleware = (options) => {
387
+ return createBoundAssetsMiddleware(this, options);
388
+ };
389
+ // --- ALS run ---
390
+ [runRequest](ctx, fn) {
391
+ return this._als.run(ctx, fn);
392
+ }
393
+ };
394
+ function createContello(options) {
395
+ return new Contello(options);
362
396
  }
363
397
  export {
364
398
  Contello,
365
- createAssetsMiddleware,
366
- createContello,
367
- createRoutingMiddleware
399
+ createContello
368
400
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/astro",
3
- "version": "1.4.2",
3
+ "version": "2.1.0",
4
4
  "description": "Astro integration for Contello CMS — route middleware and i18n bridge",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -14,9 +14,9 @@
14
14
  "@astroscope/excludes": ">=0.1.0",
15
15
  "@astroscope/i18n": ">=0.3.0",
16
16
  "astro": "^6.0.0",
17
- "@contello/client": "^1.1.1",
18
- "@contello/store": "^1.5.1",
19
- "@contello/media": "^1.0.0"
17
+ "@contello/client": "^2.2.0",
18
+ "@contello/media": "^1.0.1",
19
+ "@contello/store": "^2.1.0"
20
20
  },
21
21
  "peerDependenciesMeta": {
22
22
  "@astroscope/i18n": {
@@ -27,9 +27,9 @@
27
27
  "@astroscope/excludes": "^0.3.2",
28
28
  "@astroscope/i18n": "^0.4.5",
29
29
  "astro": "^6.1.8",
30
- "@contello/client": "^1.1.1",
31
- "@contello/store": "^1.5.1",
32
- "@contello/media": "^1.0.0"
30
+ "@contello/client": "^2.2.0",
31
+ "@contello/media": "^1.0.1",
32
+ "@contello/store": "^2.1.0"
33
33
  },
34
34
  "files": [
35
35
  "dist"