@contello/astro 2.0.0 → 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.cjs CHANGED
@@ -31,9 +31,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
31
31
  var index_exports = {};
32
32
  __export(index_exports, {
33
33
  Contello: () => Contello,
34
- createAssetsMiddleware: () => createAssetsMiddleware,
35
- createContello: () => createContello,
36
- createRoutingMiddleware: () => createRoutingMiddleware
34
+ createContello: () => createContello
37
35
  });
38
36
  module.exports = __toCommonJS(index_exports);
39
37
 
@@ -41,7 +39,202 @@ module.exports = __toCommonJS(index_exports);
41
39
  var import_node_async_hooks = require("async_hooks");
42
40
  var import_i18n = require("@astroscope/i18n");
43
41
  var import_media = require("@contello/media");
42
+ var import_store2 = require("@contello/store");
43
+
44
+ // src/assets-middleware.ts
45
+ var import_middleware = require("astro/middleware");
46
+
47
+ // src/diagnostics.ts
48
+ var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
49
+ var channels = {
50
+ start: "@contello/astro:start",
51
+ end: "@contello/astro:end",
52
+ error: "@contello/astro:error"
53
+ };
54
+ var onStart = import_node_diagnostics_channel.default.channel(channels.start);
55
+ var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
56
+ var onError = import_node_diagnostics_channel.default.channel(channels.error);
57
+ function hasSubscribers() {
58
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
59
+ }
60
+ function wrap(name, fn) {
61
+ if (!hasSubscribers()) {
62
+ return fn();
63
+ }
64
+ const start = performance.now();
65
+ onStart.publish({ name });
66
+ let result;
67
+ try {
68
+ result = fn();
69
+ } catch (error) {
70
+ onError.publish({ name, error, durationMs: performance.now() - start });
71
+ throw error;
72
+ }
73
+ if (result instanceof Promise) {
74
+ return result.then(
75
+ (r) => {
76
+ onEnd.publish({ name, durationMs: performance.now() - start });
77
+ return r;
78
+ },
79
+ (error) => {
80
+ onError.publish({ name, error, durationMs: performance.now() - start });
81
+ throw error;
82
+ }
83
+ );
84
+ }
85
+ onEnd.publish({ name, durationMs: performance.now() - start });
86
+ return result;
87
+ }
88
+
89
+ // src/assets-middleware.ts
90
+ var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
91
+ function createBoundAssetsMiddleware(contello, options) {
92
+ const imagesPrefix = contello.media.imagesPath;
93
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
94
+ const filesPrefix = contello.media.filesPath;
95
+ const filesCacheControl = options?.files?.cacheControl;
96
+ const videoPrefix = contello.media.videosPath;
97
+ return (0, import_middleware.defineMiddleware)((ctx, next) => {
98
+ const { pathname } = ctx.url;
99
+ const isImage = pathname.startsWith(imagesPrefix);
100
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
101
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
102
+ if (!isImage && !isFile && !isVideo) {
103
+ return next();
104
+ }
105
+ if (!contello.isReady) {
106
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
107
+ return next();
108
+ }
109
+ if (isImage) {
110
+ return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
111
+ }
112
+ if (isFile) {
113
+ return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
114
+ }
115
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
116
+ });
117
+ }
118
+ function handleFile(client, next, rest, cacheControl) {
119
+ const dot = rest.indexOf(".");
120
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
121
+ if (!fileId) {
122
+ return next();
123
+ }
124
+ return wrap("assets:file", () => client.download(fileId)).then(
125
+ (result) => {
126
+ const headers = new Headers({ "content-type": result.mimeType });
127
+ if (cacheControl) {
128
+ headers.set("cache-control", cacheControl);
129
+ }
130
+ if (result.size) {
131
+ headers.set("content-length", String(result.size));
132
+ }
133
+ return new Response(result.stream(), { headers });
134
+ },
135
+ () => new Response(null, { status: 404 })
136
+ );
137
+ }
138
+ function handleVideo(client, next, path, signal) {
139
+ if (!path) {
140
+ return next();
141
+ }
142
+ return wrap("assets:hls", () => client.proxyHls(path, signal)).then(
143
+ (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
144
+ () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
145
+ );
146
+ }
147
+
148
+ // src/routing-middleware.ts
149
+ var import_excludes = require("@astroscope/excludes");
44
150
  var import_store = require("@contello/store");
151
+ var import_middleware2 = require("astro/middleware");
152
+ function customHeaders(headers) {
153
+ const result = {};
154
+ for (const h of headers) {
155
+ result[h.name] = h.value;
156
+ }
157
+ return result;
158
+ }
159
+ function createBoundRoutingMiddleware(contello, routes, exclude) {
160
+ return (0, import_middleware2.defineMiddleware)((ctx, next) => {
161
+ if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
162
+ return next();
163
+ }
164
+ if (!contello.isReady) {
165
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
166
+ return next();
167
+ }
168
+ const { url } = ctx;
169
+ if (url.pathname.startsWith("/contello/entities/")) {
170
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
171
+ }
172
+ const lookup = routes.getByPath(url.pathname);
173
+ return (0, import_store.maybeThen)(lookup, (route) => {
174
+ if (!route) {
175
+ return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
176
+ }
177
+ switch (route.type) {
178
+ case "redirect":
179
+ return contello[runRequest](
180
+ { url, route, rewritten: false },
181
+ () => wrap(
182
+ "route:redirect",
183
+ () => new Response(null, {
184
+ status: route.status,
185
+ headers: {
186
+ Location: route.location,
187
+ ...customHeaders(route.customHeaders)
188
+ }
189
+ })
190
+ )
191
+ );
192
+ case "text":
193
+ return contello[runRequest](
194
+ { url, route, rewritten: false },
195
+ () => wrap(
196
+ "route:text",
197
+ () => new Response(route.content, {
198
+ status: 200,
199
+ headers: {
200
+ "Content-Type": route.mimeType,
201
+ ...customHeaders(route.customHeaders)
202
+ }
203
+ })
204
+ )
205
+ );
206
+ case "asset":
207
+ return contello[runRequest](
208
+ { url, route, rewritten: false },
209
+ () => wrap("route:asset", async () => {
210
+ const result = await contello.client.download(route.fileId);
211
+ const headers = new Headers({ "content-type": result.mimeType });
212
+ if (result.size) {
213
+ headers.set("content-length", String(result.size));
214
+ }
215
+ for (const { name, value } of route.customHeaders) {
216
+ headers.set(name, value);
217
+ }
218
+ return new Response(result.stream(), { headers });
219
+ })
220
+ );
221
+ case "entity":
222
+ return contello[runRequest](
223
+ { url, route, rewritten: true },
224
+ () => wrap(`route:entity:${route.model}`, async () => {
225
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
226
+ for (const { name, value } of route.customHeaders) {
227
+ response.headers.set(name, value);
228
+ }
229
+ return response;
230
+ })
231
+ );
232
+ }
233
+ });
234
+ });
235
+ }
236
+
237
+ // src/contello.ts
45
238
  var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
46
239
  var DEFAULT_FILES_PREFIX = "/_contello/f/";
47
240
  var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
@@ -83,16 +276,16 @@ async function applyTranslations(messages) {
83
276
  var Contello = class {
84
277
  _store;
85
278
  _options;
86
- _assets;
87
- _routes;
88
279
  _i18nMessages;
89
280
  _i18nUnsubscribe;
90
281
  _initialized = false;
91
282
  _als = new import_node_async_hooks.AsyncLocalStorage();
283
+ _autoEagerRoutes;
284
+ _autoLazyRoutes;
92
285
  media;
93
286
  constructor(options) {
94
287
  this._options = options;
95
- this._store = (0, import_store.createStore)(options);
288
+ this._store = (0, import_store2.createStore)(options);
96
289
  this.media = {
97
290
  baseUrl: options.media?.baseUrl ?? "",
98
291
  imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
@@ -104,12 +297,10 @@ var Contello = class {
104
297
  async init(options) {
105
298
  try {
106
299
  await this._store.init();
107
- this._assets = this._store.defineAssets(this._options.assets);
108
- this._routes = this._store.defineRoutes(this._options.routes);
109
300
  if (this._options.i18n) {
110
- const { collection, languages } = this._options.i18n;
301
+ const { collection, languages, cache } = this._options.i18n;
111
302
  const { register = true, load = true } = options?.i18n ?? {};
112
- this._i18nMessages = this._store.defineI18nMessages({ collection });
303
+ this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
113
304
  await import_i18n.i18n.configure({ locales: languages });
114
305
  if (register) {
115
306
  const registrations = buildI18nRegistrations();
@@ -132,9 +323,8 @@ var Contello = class {
132
323
  })();
133
324
  }
134
325
  }
135
- if (options?.load) {
136
- await Promise.all(options.load.map((l) => l.load()));
137
- }
326
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
327
+ await Promise.all(loadables.map((l) => l.load()));
138
328
  this._initialized = true;
139
329
  } catch (err) {
140
330
  await this.destroy().catch(() => {
@@ -147,8 +337,6 @@ var Contello = class {
147
337
  this._i18nUnsubscribe?.();
148
338
  this._i18nUnsubscribe = void 0;
149
339
  await this._store.destroy();
150
- this._assets = void 0;
151
- this._routes = void 0;
152
340
  this._i18nMessages = void 0;
153
341
  }
154
342
  ping() {
@@ -157,18 +345,8 @@ var Contello = class {
157
345
  get isReady() {
158
346
  return this._initialized;
159
347
  }
160
- // --- pre-wired collections ---
161
- get assets() {
162
- if (!this._assets) {
163
- throw new Error("@contello/astro: .assets accessed before init()");
164
- }
165
- return this._assets;
166
- }
167
- get routes() {
168
- if (!this._routes) {
169
- throw new Error("@contello/astro: .routes accessed before init()");
170
- }
171
- return this._routes;
348
+ get client() {
349
+ return this._store.client;
172
350
  }
173
351
  get i18nMessages() {
174
352
  if (!this._i18nMessages) {
@@ -207,209 +385,50 @@ var Contello = class {
207
385
  defineLazyCollection(sourceOrKey, options) {
208
386
  return this._store.defineLazyCollection(sourceOrKey, options);
209
387
  }
210
- // --- ALS run ---
211
- [runRequest](ctx, fn) {
212
- return this._als.run(ctx, fn);
213
- }
214
- };
215
- function createContello(options) {
216
- return new Contello(options);
217
- }
218
-
219
- // src/assets-middleware.ts
220
- var import_middleware = require("astro/middleware");
221
-
222
- // src/diagnostics.ts
223
- var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
224
- var channels = {
225
- start: "@contello/astro:start",
226
- end: "@contello/astro:end",
227
- error: "@contello/astro:error"
228
- };
229
- var onStart = import_node_diagnostics_channel.default.channel(channels.start);
230
- var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
231
- var onError = import_node_diagnostics_channel.default.channel(channels.error);
232
- function hasSubscribers() {
233
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
234
- }
235
- function wrap(name, fn) {
236
- if (!hasSubscribers()) {
237
- return fn();
388
+ defineRoutes(options) {
389
+ return this._store.defineRoutes(options);
238
390
  }
239
- const start = performance.now();
240
- onStart.publish({ name });
241
- let result;
242
- try {
243
- result = fn();
244
- } catch (error) {
245
- onError.publish({ name, error, durationMs: performance.now() - start });
246
- throw error;
391
+ defineRoutesSync(options) {
392
+ return this._store.defineRoutesSync(options);
247
393
  }
248
- if (result instanceof Promise) {
249
- return result.then(
250
- (r) => {
251
- onEnd.publish({ name, durationMs: performance.now() - start });
252
- return r;
253
- },
254
- (error) => {
255
- onError.publish({ name, error, durationMs: performance.now() - start });
256
- throw error;
257
- }
258
- );
394
+ defineLazyRoutes(options) {
395
+ return this._store.defineLazyRoutes(options);
259
396
  }
260
- onEnd.publish({ name, durationMs: performance.now() - start });
261
- return result;
262
- }
263
-
264
- // src/assets-middleware.ts
265
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
266
- function createAssetsMiddleware(instance, options) {
267
- const imagesPrefix = instance.media.imagesPath;
268
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
269
- const filesPrefix = instance.media.filesPath;
270
- const filesCacheControl = options?.files?.cacheControl;
271
- const videoPrefix = instance.media.videosPath;
272
- return (0, import_middleware.defineMiddleware)((ctx, next) => {
273
- const { pathname } = ctx.url;
274
- const isImage = pathname.startsWith(imagesPrefix);
275
- const isFile = !isImage && pathname.startsWith(filesPrefix);
276
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
277
- if (!isImage && !isFile && !isVideo) {
278
- return next();
279
- }
280
- if (!instance.isReady) {
281
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
282
- return next();
283
- }
284
- if (isImage) {
285
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
286
- }
287
- if (isFile) {
288
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
289
- }
290
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
291
- });
292
- }
293
- function handleFile(instance, next, rest, cacheControl) {
294
- const dot = rest.indexOf(".");
295
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
296
- if (!fileId) {
297
- return next();
397
+ defineAssets(options) {
398
+ return this._store.defineAssets(options);
298
399
  }
299
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
300
- (result) => {
301
- const headers = new Headers({ "content-type": result.mimeType });
302
- if (cacheControl) {
303
- headers.set("cache-control", cacheControl);
304
- }
305
- if (result.size) {
306
- headers.set("content-length", String(result.size));
307
- }
308
- return new Response(result.stream(), { headers });
309
- },
310
- () => new Response(null, { status: 404 })
311
- );
312
- }
313
- function handleVideo(instance, next, path, signal) {
314
- if (!path) {
315
- return next();
400
+ defineAssetsSync(options) {
401
+ return this._store.defineAssetsSync(options);
316
402
  }
317
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
318
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
319
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
320
- );
321
- }
322
-
323
- // src/routing-middleware.ts
324
- var import_excludes = require("@astroscope/excludes");
325
- var import_middleware2 = require("astro/middleware");
326
- function customHeaders(headers) {
327
- const result = {};
328
- for (const h of headers) {
329
- result[h.name] = h.value;
403
+ defineLazyAssets(options) {
404
+ return this._store.defineLazyAssets(options);
330
405
  }
331
- return result;
332
- }
333
- function createRoutingMiddleware(instance, options) {
334
- const { exclude } = options ?? {};
335
- return (0, import_middleware2.defineMiddleware)(async (ctx, next) => {
336
- if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
337
- return next();
338
- }
339
- if (!instance.isReady) {
340
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
341
- return next();
342
- }
343
- const { url } = ctx;
344
- if (url.pathname.startsWith("/contello/entities/")) {
345
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
346
- }
347
- const route = await instance.routes.getByPath(url.pathname);
348
- if (!route) {
349
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
406
+ // --- middleware factories (arrow fields so destructuring works) ---
407
+ createRoutingMiddleware = (options) => {
408
+ const routesOption = options?.routes ?? "eager";
409
+ let routes;
410
+ if (routesOption === "eager") {
411
+ routes = this._autoEagerRoutes ??= this.defineRoutesSync();
412
+ } else if (routesOption === "lazy") {
413
+ routes = this._autoLazyRoutes ??= this.defineLazyRoutes();
414
+ } else {
415
+ routes = routesOption;
350
416
  }
351
- switch (route.type) {
352
- case "redirect":
353
- return instance[runRequest](
354
- { url, route, rewritten: false },
355
- () => wrap(
356
- "route:redirect",
357
- () => new Response(null, {
358
- status: route.status,
359
- headers: {
360
- Location: route.location,
361
- ...customHeaders(route.customHeaders)
362
- }
363
- })
364
- )
365
- );
366
- case "text":
367
- return instance[runRequest](
368
- { url, route, rewritten: false },
369
- () => wrap(
370
- "route:text",
371
- () => new Response(route.content, {
372
- status: 200,
373
- headers: {
374
- "Content-Type": route.mimeType,
375
- ...customHeaders(route.customHeaders)
376
- }
377
- })
378
- )
379
- );
380
- case "asset":
381
- return instance[runRequest](
382
- { url, route, rewritten: false },
383
- () => wrap("route:asset", async () => {
384
- const result = await instance.assets.download(route.fileId);
385
- const headers = new Headers({ "content-type": result.mimeType });
386
- if (result.size) {
387
- headers.set("content-length", String(result.size));
388
- }
389
- for (const { name, value } of route.customHeaders) {
390
- headers.set(name, value);
391
- }
392
- return new Response(result.stream(), { headers });
393
- })
394
- );
395
- case "entity":
396
- return instance[runRequest](
397
- { url, route, rewritten: true },
398
- () => wrap(`route:entity:${route.model}`, async () => {
399
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
400
- for (const { name, value } of route.customHeaders) {
401
- response.headers.set(name, value);
402
- }
403
- return response;
404
- })
405
- );
406
- }
407
- });
417
+ return createBoundRoutingMiddleware(this, routes, options?.exclude);
418
+ };
419
+ createAssetsMiddleware = (options) => {
420
+ return createBoundAssetsMiddleware(this, options);
421
+ };
422
+ // --- ALS run ---
423
+ [runRequest](ctx, fn) {
424
+ return this._als.run(ctx, fn);
425
+ }
426
+ };
427
+ function createContello(options) {
428
+ return new Contello(options);
408
429
  }
409
430
  // Annotate the CommonJS export names for ESM import in node:
410
431
  0 && (module.exports = {
411
432
  Contello,
412
- createAssetsMiddleware,
413
- createContello,
414
- createRoutingMiddleware
433
+ createContello
415
434
  });
package/dist/index.d.cts CHANGED
@@ -1,9 +1,33 @@
1
- import { Schema, SourceDef } from '@contello/client';
2
- import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
3
- import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Loadable, Assets, Routes, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection } from '@contello/store';
4
1
  import * as astro from 'astro';
2
+ import { Schema, ContelloClient, SourceDef } from '@contello/client';
3
+ import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
4
+ import { Routes, RoutesSync, LazyRoutes, CreateStoreOptions, SyncCacheOptions, Loadable, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection, RoutesOptions, RoutesSyncOptions, LazyRoutesOptions, AssetsOptions, Assets, AssetsSyncOptions, AssetsSync, LazyAssetsOptions, LazyAssets } from '@contello/store';
5
5
  import { ExcludePattern } from '@astroscope/excludes';
6
6
 
7
+ type ContelloAssetsImagesOptions = {
8
+ cacheControl?: string | undefined;
9
+ };
10
+ type ContelloAssetsFilesOptions = {
11
+ cacheControl?: string | undefined;
12
+ };
13
+ type ContelloAssetsVideoOptions = {};
14
+ type ContelloAssetsMiddlewareOptions = {
15
+ images?: ContelloAssetsImagesOptions | undefined;
16
+ files?: ContelloAssetsFilesOptions | undefined;
17
+ video?: ContelloAssetsVideoOptions | undefined;
18
+ };
19
+
20
+ type AnyRoutes = Routes | RoutesSync | LazyRoutes;
21
+ type ContelloRoutingMiddlewareOptions = {
22
+ /**
23
+ * - `'eager'` (default) — use a `RoutesSync` instance managed by contello (auto-loaded by `contello.init()`)
24
+ * - `'lazy'` — use a `LazyRoutes` instance managed by contello
25
+ * - a user-defined routes instance (`Routes` / `RoutesSync` / `LazyRoutes`) — consumer manages its lifecycle
26
+ */
27
+ routes?: 'eager' | 'lazy' | AnyRoutes | undefined;
28
+ exclude?: ExcludePattern[] | undefined;
29
+ };
30
+
7
31
  type ContelloRequestContext = {
8
32
  url: URL;
9
33
  route: ReadonlyDeep<StoreRoute> | undefined;
@@ -12,6 +36,7 @@ type ContelloRequestContext = {
12
36
  type ContelloI18nOptions = {
13
37
  collection: string;
14
38
  languages: string[];
39
+ cache?: SyncCacheOptions | undefined;
15
40
  };
16
41
  type ContelloInitOptions = {
17
42
  load?: Loadable[] | undefined;
@@ -27,9 +52,7 @@ type ContelloMediaConfig = {
27
52
  readonly filesPath: string;
28
53
  };
29
54
  type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {
30
- assets?: AssetCollectionOptions | undefined;
31
55
  i18n?: ContelloI18nOptions | undefined;
32
- routes?: RouteCollectionOptions | undefined;
33
56
  media?: Partial<ContelloMediaConfig> | undefined;
34
57
  };
35
58
  type HasFallback<O> = O extends {
@@ -46,20 +69,19 @@ type SingletonRaw<TSchema, TArg> = ExtractSourceResult<Extract<ResolveSource<TSc
46
69
  declare class Contello<TSchema extends Schema | undefined = undefined> {
47
70
  private readonly _store;
48
71
  private readonly _options;
49
- private _assets;
50
- private _routes;
51
72
  private _i18nMessages;
52
73
  private _i18nUnsubscribe;
53
74
  private _initialized;
54
75
  private readonly _als;
76
+ private _autoEagerRoutes?;
77
+ private _autoLazyRoutes?;
55
78
  readonly media: ContelloMediaConfig;
56
79
  constructor(options: ContelloOptions<TSchema>);
57
80
  init(options?: ContelloInitOptions | undefined): Promise<void>;
58
81
  destroy(): Promise<void>;
59
82
  ping(): Promise<void>;
60
83
  get isReady(): boolean;
61
- get assets(): Assets;
62
- get routes(): Routes;
84
+ get client(): ContelloClient<TSchema>;
63
85
  get i18nMessages(): I18nMessages;
64
86
  get request(): ContelloRequestContext;
65
87
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -80,27 +102,16 @@ declare class Contello<TSchema extends Schema | undefined = undefined> {
80
102
  } = CollectionRaw<TSchema, TArg> & {
81
103
  id: string;
82
104
  }>(sourceOrKey: TArg, options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>): LazyCollection<TMapped>;
105
+ defineRoutes(options?: RoutesOptions | undefined): Routes;
106
+ defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync;
107
+ defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes;
108
+ defineAssets(options?: AssetsOptions | undefined): Assets;
109
+ defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync;
110
+ defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets;
111
+ createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => astro.MiddlewareHandler;
112
+ createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => astro.MiddlewareHandler;
83
113
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
84
114
  }
85
115
  declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
86
116
 
87
- type ContelloAssetsImagesOptions = {
88
- cacheControl?: string | undefined;
89
- };
90
- type ContelloAssetsFilesOptions = {
91
- cacheControl?: string | undefined;
92
- };
93
- type ContelloAssetsVideoOptions = {};
94
- type ContelloAssetsMiddlewareOptions = {
95
- images?: ContelloAssetsImagesOptions | undefined;
96
- files?: ContelloAssetsFilesOptions | undefined;
97
- video?: ContelloAssetsVideoOptions | undefined;
98
- };
99
- declare function createAssetsMiddleware(instance: Contello<any>, options?: ContelloAssetsMiddlewareOptions | undefined): astro.MiddlewareHandler;
100
-
101
- type ContelloMiddlewareOptions = {
102
- exclude?: ExcludePattern[] | undefined;
103
- };
104
- declare function createRoutingMiddleware(instance: Contello<any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
105
-
106
- export { Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createAssetsMiddleware, createContello, createRoutingMiddleware };
117
+ export { type AnyRoutes, Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloOptions, type ContelloRequestContext, type ContelloRoutingMiddlewareOptions, createContello };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,33 @@
1
- import { Schema, SourceDef } from '@contello/client';
2
- import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
3
- import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Loadable, Assets, Routes, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection } from '@contello/store';
4
1
  import * as astro from 'astro';
2
+ import { Schema, ContelloClient, SourceDef } from '@contello/client';
3
+ import { MediaResolverOptions, MediaResolver, ImageDef } from '@contello/media';
4
+ import { Routes, RoutesSync, LazyRoutes, CreateStoreOptions, SyncCacheOptions, Loadable, I18nMessages, ReadonlyDeep, StoreRoute, SourceKeysOf, ExtractSourceResult, ResolveSource, SingletonOptions, Singleton, SingletonSyncOptions, SingletonSync, CollectionOptions, Collection, CollectionSyncOptions, CollectionSync, LazyCollectionOptions, LazyCollection, RoutesOptions, RoutesSyncOptions, LazyRoutesOptions, AssetsOptions, Assets, AssetsSyncOptions, AssetsSync, LazyAssetsOptions, LazyAssets } from '@contello/store';
5
5
  import { ExcludePattern } from '@astroscope/excludes';
6
6
 
7
+ type ContelloAssetsImagesOptions = {
8
+ cacheControl?: string | undefined;
9
+ };
10
+ type ContelloAssetsFilesOptions = {
11
+ cacheControl?: string | undefined;
12
+ };
13
+ type ContelloAssetsVideoOptions = {};
14
+ type ContelloAssetsMiddlewareOptions = {
15
+ images?: ContelloAssetsImagesOptions | undefined;
16
+ files?: ContelloAssetsFilesOptions | undefined;
17
+ video?: ContelloAssetsVideoOptions | undefined;
18
+ };
19
+
20
+ type AnyRoutes = Routes | RoutesSync | LazyRoutes;
21
+ type ContelloRoutingMiddlewareOptions = {
22
+ /**
23
+ * - `'eager'` (default) — use a `RoutesSync` instance managed by contello (auto-loaded by `contello.init()`)
24
+ * - `'lazy'` — use a `LazyRoutes` instance managed by contello
25
+ * - a user-defined routes instance (`Routes` / `RoutesSync` / `LazyRoutes`) — consumer manages its lifecycle
26
+ */
27
+ routes?: 'eager' | 'lazy' | AnyRoutes | undefined;
28
+ exclude?: ExcludePattern[] | undefined;
29
+ };
30
+
7
31
  type ContelloRequestContext = {
8
32
  url: URL;
9
33
  route: ReadonlyDeep<StoreRoute> | undefined;
@@ -12,6 +36,7 @@ type ContelloRequestContext = {
12
36
  type ContelloI18nOptions = {
13
37
  collection: string;
14
38
  languages: string[];
39
+ cache?: SyncCacheOptions | undefined;
15
40
  };
16
41
  type ContelloInitOptions = {
17
42
  load?: Loadable[] | undefined;
@@ -27,9 +52,7 @@ type ContelloMediaConfig = {
27
52
  readonly filesPath: string;
28
53
  };
29
54
  type ContelloOptions<TSchema extends Schema | undefined = undefined> = CreateStoreOptions<TSchema> & {
30
- assets?: AssetCollectionOptions | undefined;
31
55
  i18n?: ContelloI18nOptions | undefined;
32
- routes?: RouteCollectionOptions | undefined;
33
56
  media?: Partial<ContelloMediaConfig> | undefined;
34
57
  };
35
58
  type HasFallback<O> = O extends {
@@ -46,20 +69,19 @@ type SingletonRaw<TSchema, TArg> = ExtractSourceResult<Extract<ResolveSource<TSc
46
69
  declare class Contello<TSchema extends Schema | undefined = undefined> {
47
70
  private readonly _store;
48
71
  private readonly _options;
49
- private _assets;
50
- private _routes;
51
72
  private _i18nMessages;
52
73
  private _i18nUnsubscribe;
53
74
  private _initialized;
54
75
  private readonly _als;
76
+ private _autoEagerRoutes?;
77
+ private _autoLazyRoutes?;
55
78
  readonly media: ContelloMediaConfig;
56
79
  constructor(options: ContelloOptions<TSchema>);
57
80
  init(options?: ContelloInitOptions | undefined): Promise<void>;
58
81
  destroy(): Promise<void>;
59
82
  ping(): Promise<void>;
60
83
  get isReady(): boolean;
61
- get assets(): Assets;
62
- get routes(): Routes;
84
+ get client(): ContelloClient<TSchema>;
63
85
  get i18nMessages(): I18nMessages;
64
86
  get request(): ContelloRequestContext;
65
87
  defineMediaResolver<O extends Partial<MediaResolverOptions>>(options?: O): MediaResolver<HasFallback<O>>;
@@ -80,27 +102,16 @@ declare class Contello<TSchema extends Schema | undefined = undefined> {
80
102
  } = CollectionRaw<TSchema, TArg> & {
81
103
  id: string;
82
104
  }>(sourceOrKey: TArg, options?: LazyCollectionOptions<CollectionRaw<TSchema, TArg>, TMapped, ModelsOf<TSchema>>): LazyCollection<TMapped>;
105
+ defineRoutes(options?: RoutesOptions | undefined): Routes;
106
+ defineRoutesSync(options?: RoutesSyncOptions | undefined): RoutesSync;
107
+ defineLazyRoutes(options?: LazyRoutesOptions | undefined): LazyRoutes;
108
+ defineAssets(options?: AssetsOptions | undefined): Assets;
109
+ defineAssetsSync(options?: AssetsSyncOptions | undefined): AssetsSync;
110
+ defineLazyAssets(options?: LazyAssetsOptions | undefined): LazyAssets;
111
+ createRoutingMiddleware: (options?: ContelloRoutingMiddlewareOptions | undefined) => astro.MiddlewareHandler;
112
+ createAssetsMiddleware: (options?: ContelloAssetsMiddlewareOptions | undefined) => astro.MiddlewareHandler;
83
113
  [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
84
114
  }
85
115
  declare function createContello<TSchema extends Schema | undefined = undefined>(options: ContelloOptions<TSchema>): Contello<TSchema>;
86
116
 
87
- type ContelloAssetsImagesOptions = {
88
- cacheControl?: string | undefined;
89
- };
90
- type ContelloAssetsFilesOptions = {
91
- cacheControl?: string | undefined;
92
- };
93
- type ContelloAssetsVideoOptions = {};
94
- type ContelloAssetsMiddlewareOptions = {
95
- images?: ContelloAssetsImagesOptions | undefined;
96
- files?: ContelloAssetsFilesOptions | undefined;
97
- video?: ContelloAssetsVideoOptions | undefined;
98
- };
99
- declare function createAssetsMiddleware(instance: Contello<any>, options?: ContelloAssetsMiddlewareOptions | undefined): astro.MiddlewareHandler;
100
-
101
- type ContelloMiddlewareOptions = {
102
- exclude?: ExcludePattern[] | undefined;
103
- };
104
- declare function createRoutingMiddleware(instance: Contello<any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
105
-
106
- export { Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createAssetsMiddleware, createContello, createRoutingMiddleware };
117
+ export { type AnyRoutes, Contello, type ContelloAssetsFilesOptions, type ContelloAssetsImagesOptions, type ContelloAssetsMiddlewareOptions, type ContelloAssetsVideoOptions, type ContelloI18nOptions, type ContelloInitOptions, type ContelloOptions, type ContelloRequestContext, type ContelloRoutingMiddlewareOptions, createContello };
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
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();
@@ -95,9 +290,8 @@ var Contello = class {
95
290
  })();
96
291
  }
97
292
  }
98
- if (options?.load) {
99
- await Promise.all(options.load.map((l) => l.load()));
100
- }
293
+ const loadables = [...options?.load ?? [], ...this._autoEagerRoutes ? [this._autoEagerRoutes] : []];
294
+ await Promise.all(loadables.map((l) => l.load()));
101
295
  this._initialized = true;
102
296
  } catch (err) {
103
297
  await this.destroy().catch(() => {
@@ -110,8 +304,6 @@ var Contello = class {
110
304
  this._i18nUnsubscribe?.();
111
305
  this._i18nUnsubscribe = void 0;
112
306
  await this._store.destroy();
113
- this._assets = void 0;
114
- this._routes = void 0;
115
307
  this._i18nMessages = void 0;
116
308
  }
117
309
  ping() {
@@ -120,18 +312,8 @@ var Contello = class {
120
312
  get isReady() {
121
313
  return this._initialized;
122
314
  }
123
- // --- pre-wired collections ---
124
- get assets() {
125
- if (!this._assets) {
126
- throw new Error("@contello/astro: .assets accessed before init()");
127
- }
128
- return this._assets;
129
- }
130
- get routes() {
131
- if (!this._routes) {
132
- throw new Error("@contello/astro: .routes accessed before init()");
133
- }
134
- return this._routes;
315
+ get client() {
316
+ return this._store.client;
135
317
  }
136
318
  get i18nMessages() {
137
319
  if (!this._i18nMessages) {
@@ -170,208 +352,49 @@ var Contello = class {
170
352
  defineLazyCollection(sourceOrKey, options) {
171
353
  return this._store.defineLazyCollection(sourceOrKey, options);
172
354
  }
173
- // --- ALS run ---
174
- [runRequest](ctx, fn) {
175
- return this._als.run(ctx, fn);
355
+ defineRoutes(options) {
356
+ return this._store.defineRoutes(options);
176
357
  }
177
- };
178
- function createContello(options) {
179
- return new Contello(options);
180
- }
181
-
182
- // src/assets-middleware.ts
183
- import { defineMiddleware } from "astro/middleware";
184
-
185
- // src/diagnostics.ts
186
- import dc from "diagnostics_channel";
187
- var channels = {
188
- start: "@contello/astro:start",
189
- end: "@contello/astro:end",
190
- error: "@contello/astro:error"
191
- };
192
- var onStart = dc.channel(channels.start);
193
- var onEnd = dc.channel(channels.end);
194
- var onError = dc.channel(channels.error);
195
- function hasSubscribers() {
196
- return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
197
- }
198
- function wrap(name, fn) {
199
- if (!hasSubscribers()) {
200
- return fn();
358
+ defineRoutesSync(options) {
359
+ return this._store.defineRoutesSync(options);
201
360
  }
202
- const start = performance.now();
203
- onStart.publish({ name });
204
- let result;
205
- try {
206
- result = fn();
207
- } catch (error) {
208
- onError.publish({ name, error, durationMs: performance.now() - start });
209
- throw error;
210
- }
211
- if (result instanceof Promise) {
212
- return result.then(
213
- (r) => {
214
- onEnd.publish({ name, durationMs: performance.now() - start });
215
- return r;
216
- },
217
- (error) => {
218
- onError.publish({ name, error, durationMs: performance.now() - start });
219
- throw error;
220
- }
221
- );
361
+ defineLazyRoutes(options) {
362
+ return this._store.defineLazyRoutes(options);
222
363
  }
223
- onEnd.publish({ name, durationMs: performance.now() - start });
224
- return result;
225
- }
226
-
227
- // src/assets-middleware.ts
228
- var DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
229
- function createAssetsMiddleware(instance, options) {
230
- const imagesPrefix = instance.media.imagesPath;
231
- const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
232
- const filesPrefix = instance.media.filesPath;
233
- const filesCacheControl = options?.files?.cacheControl;
234
- const videoPrefix = instance.media.videosPath;
235
- return defineMiddleware((ctx, next) => {
236
- const { pathname } = ctx.url;
237
- const isImage = pathname.startsWith(imagesPrefix);
238
- const isFile = !isImage && pathname.startsWith(filesPrefix);
239
- const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
240
- if (!isImage && !isFile && !isVideo) {
241
- return next();
242
- }
243
- if (!instance.isReady) {
244
- console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
245
- return next();
246
- }
247
- if (isImage) {
248
- return handleFile(instance, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
249
- }
250
- if (isFile) {
251
- return handleFile(instance, next, pathname.slice(filesPrefix.length), filesCacheControl);
252
- }
253
- return handleVideo(instance, next, pathname.slice(videoPrefix.length), ctx.request.signal);
254
- });
255
- }
256
- function handleFile(instance, next, rest, cacheControl) {
257
- const dot = rest.indexOf(".");
258
- const fileId = dot === -1 ? rest : rest.slice(0, dot);
259
- if (!fileId) {
260
- return next();
364
+ defineAssets(options) {
365
+ return this._store.defineAssets(options);
261
366
  }
262
- return wrap("assets:file", () => instance.assets.download(fileId)).then(
263
- (result) => {
264
- const headers = new Headers({ "content-type": result.mimeType });
265
- if (cacheControl) {
266
- headers.set("cache-control", cacheControl);
267
- }
268
- if (result.size) {
269
- headers.set("content-length", String(result.size));
270
- }
271
- return new Response(result.stream(), { headers });
272
- },
273
- () => new Response(null, { status: 404 })
274
- );
275
- }
276
- function handleVideo(instance, next, path, signal) {
277
- if (!path) {
278
- return next();
367
+ defineAssetsSync(options) {
368
+ return this._store.defineAssetsSync(options);
279
369
  }
280
- return wrap("assets:hls", () => instance.assets.proxyHls(path, signal)).then(
281
- (result) => new Response(result.stream(), { status: result.status, headers: result.headers }),
282
- () => new Response("Upstream is down", { status: 502, headers: { "content-type": "text/plain" } })
283
- );
284
- }
285
-
286
- // src/routing-middleware.ts
287
- import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
288
- import { defineMiddleware as defineMiddleware2 } from "astro/middleware";
289
- function customHeaders(headers) {
290
- const result = {};
291
- for (const h of headers) {
292
- result[h.name] = h.value;
370
+ defineLazyAssets(options) {
371
+ return this._store.defineLazyAssets(options);
293
372
  }
294
- return result;
295
- }
296
- function createRoutingMiddleware(instance, options) {
297
- const { exclude } = options ?? {};
298
- return defineMiddleware2(async (ctx, next) => {
299
- if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
300
- return next();
301
- }
302
- if (!instance.isReady) {
303
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
304
- return next();
305
- }
306
- const { url } = ctx;
307
- if (url.pathname.startsWith("/contello/entities/")) {
308
- return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
309
- }
310
- const route = await instance.routes.getByPath(url.pathname);
311
- if (!route) {
312
- 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;
313
383
  }
314
- switch (route.type) {
315
- case "redirect":
316
- return instance[runRequest](
317
- { url, route, rewritten: false },
318
- () => wrap(
319
- "route:redirect",
320
- () => new Response(null, {
321
- status: route.status,
322
- headers: {
323
- Location: route.location,
324
- ...customHeaders(route.customHeaders)
325
- }
326
- })
327
- )
328
- );
329
- case "text":
330
- return instance[runRequest](
331
- { url, route, rewritten: false },
332
- () => wrap(
333
- "route:text",
334
- () => new Response(route.content, {
335
- status: 200,
336
- headers: {
337
- "Content-Type": route.mimeType,
338
- ...customHeaders(route.customHeaders)
339
- }
340
- })
341
- )
342
- );
343
- case "asset":
344
- return instance[runRequest](
345
- { url, route, rewritten: false },
346
- () => wrap("route:asset", async () => {
347
- const result = await instance.assets.download(route.fileId);
348
- const headers = new Headers({ "content-type": result.mimeType });
349
- if (result.size) {
350
- headers.set("content-length", String(result.size));
351
- }
352
- for (const { name, value } of route.customHeaders) {
353
- headers.set(name, value);
354
- }
355
- return new Response(result.stream(), { headers });
356
- })
357
- );
358
- case "entity":
359
- return instance[runRequest](
360
- { url, route, rewritten: true },
361
- () => wrap(`route:entity:${route.model}`, async () => {
362
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
363
- for (const { name, value } of route.customHeaders) {
364
- response.headers.set(name, value);
365
- }
366
- return response;
367
- })
368
- );
369
- }
370
- });
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);
371
396
  }
372
397
  export {
373
398
  Contello,
374
- createAssetsMiddleware,
375
- createContello,
376
- createRoutingMiddleware
399
+ createContello
377
400
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@contello/astro",
3
- "version": "2.0.0",
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": "^2.0.0",
17
+ "@contello/client": "^2.2.0",
18
18
  "@contello/media": "^1.0.1",
19
- "@contello/store": "^2.0.0"
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": "^2.0.0",
30
+ "@contello/client": "^2.2.0",
31
31
  "@contello/media": "^1.0.1",
32
- "@contello/store": "^2.0.0"
32
+ "@contello/store": "^2.1.0"
33
33
  },
34
34
  "files": [
35
35
  "dist"