@contello/astro 3.1.0 → 4.0.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
@@ -1,434 +1,326 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var index_exports = {};
32
- __export(index_exports, {
33
- Contello: () => Contello,
34
- createContello: () => createContello
35
- });
36
- module.exports = __toCommonJS(index_exports);
37
-
38
- // src/contello.ts
39
- var import_node_async_hooks = require("async_hooks");
40
- var import_i18n = require("@astroscope/i18n");
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";
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let node_async_hooks = require("node:async_hooks");
3
+ let _astroscope_i18n = require("@astroscope/i18n");
4
+ let _astroscope_node_boot = require("@astroscope/node/boot");
5
+ let _contello_media = require("@contello/media");
6
+ let _contello_store = require("@contello/store");
7
+ let astro_middleware = require("astro/middleware");
8
+ let _contello_opentelemetry = require("@contello/opentelemetry");
9
+ let _astroscope_node_excludes = require("@astroscope/node/excludes");
10
+ //#region src/telemetry.ts
11
+ const { wrap } = (0, _contello_opentelemetry.createOperationTelemetry)("@contello/astro");
12
+ //#endregion
13
+ //#region src/assets-middleware.ts
14
+ const DEFAULT_IMAGES_CACHE_CONTROL = "public, max-age=31536000";
91
15
  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
- });
16
+ const imagesPrefix = contello.media.imagesPath;
17
+ const imagesCacheControl = options?.images?.cacheControl ?? DEFAULT_IMAGES_CACHE_CONTROL;
18
+ const filesPrefix = contello.media.filesPath;
19
+ const filesCacheControl = options?.files?.cacheControl;
20
+ const videoPrefix = contello.media.videosPath;
21
+ return (0, astro_middleware.defineMiddleware)((ctx, next) => {
22
+ const { pathname } = ctx.url;
23
+ const isImage = pathname.startsWith(imagesPrefix);
24
+ const isFile = !isImage && pathname.startsWith(filesPrefix);
25
+ const isVideo = !isImage && !isFile && pathname.startsWith(videoPrefix);
26
+ if (!isImage && !isFile && !isVideo) return next();
27
+ if (!contello.isReady) {
28
+ console.warn(`[@contello/astro] not initialized, passing through: ${pathname}`);
29
+ return next();
30
+ }
31
+ if (isImage) return handleFile(contello.client, next, pathname.slice(imagesPrefix.length), imagesCacheControl);
32
+ if (isFile) return handleFile(contello.client, next, pathname.slice(filesPrefix.length), filesCacheControl);
33
+ return handleVideo(contello.client, next, pathname.slice(videoPrefix.length), ctx.request.signal);
34
+ });
117
35
  }
118
36
  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 > 0) {
131
- headers.set("content-length", String(result.size));
132
- }
133
- return new Response(result.stream(), { headers });
134
- },
135
- () => new Response(null, { status: 404 })
136
- );
37
+ const dot = rest.indexOf(".");
38
+ const fileId = dot === -1 ? rest : rest.slice(0, dot);
39
+ if (!fileId) return next();
40
+ return (async () => {
41
+ try {
42
+ const result = await wrap("assets:file", () => client.download(fileId));
43
+ const headers = new Headers({ "content-type": result.mimeType });
44
+ if (cacheControl) headers.set("cache-control", cacheControl);
45
+ if (result.size > 0) headers.set("content-length", String(result.size));
46
+ return new Response(result.stream(), { headers });
47
+ } catch {
48
+ return new Response(null, { status: 404 });
49
+ }
50
+ })();
137
51
  }
138
52
  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
- );
53
+ if (!path) return next();
54
+ return (async () => {
55
+ try {
56
+ const result = await wrap("assets:hls", () => client.proxyHls(path, signal));
57
+ return new Response(result.stream(), {
58
+ status: result.status,
59
+ headers: result.headers
60
+ });
61
+ } catch {
62
+ return new Response("Upstream is down", {
63
+ status: 502,
64
+ headers: { "content-type": "text/plain" }
65
+ });
66
+ }
67
+ })();
146
68
  }
147
-
148
- // src/routing-middleware.ts
149
- var import_excludes = require("@astroscope/excludes");
150
- var import_store = require("@contello/store");
151
- var import_middleware2 = require("astro/middleware");
69
+ //#endregion
70
+ //#region src/routing-middleware.ts
152
71
  function customHeaders(headers) {
153
- const result = {};
154
- for (const h of headers) {
155
- result[h.name] = h.value;
156
- }
157
- return result;
72
+ const result = {};
73
+ for (const h of headers) result[h.name] = h.value;
74
+ return result;
158
75
  }
159
- var VALID_REDIRECT_STATUSES = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
76
+ const VALID_REDIRECT_STATUSES = /* @__PURE__ */ new Set([
77
+ 301,
78
+ 302,
79
+ 303,
80
+ 307,
81
+ 308
82
+ ]);
160
83
  function toRedirectStatus(status) {
161
- return VALID_REDIRECT_STATUSES.has(status) ? status : 302;
84
+ return VALID_REDIRECT_STATUSES.has(status) ? status : 302;
162
85
  }
163
86
  function createBoundRoutingMiddleware(contello, routes, exclude, resolveRoutePath) {
164
- return (0, import_middleware2.defineMiddleware)((ctx, next) => {
165
- if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
166
- return next();
167
- }
168
- if (!contello.isReady) {
169
- console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
170
- return next();
171
- }
172
- const { url } = ctx;
173
- if (url.pathname.startsWith("/contello/entities/")) {
174
- return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
175
- }
176
- const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
177
- const lookup = routes.getByPath(path);
178
- return (0, import_store.maybeThen)(lookup, (route) => {
179
- if (!route) {
180
- return contello[runRequest]({ url, route: void 0, rewritten: false }, () => next());
181
- }
182
- switch (route.type) {
183
- case "redirect": {
184
- return contello[runRequest](
185
- { url, route, rewritten: false },
186
- () => wrap(
187
- "route:redirect",
188
- () => new Response(null, {
189
- status: toRedirectStatus(route.status),
190
- headers: {
191
- Location: route.location,
192
- ...customHeaders(route.customHeaders)
193
- }
194
- })
195
- )
196
- );
197
- }
198
- case "text": {
199
- return contello[runRequest](
200
- { url, route, rewritten: false },
201
- () => wrap(
202
- "route:text",
203
- () => new Response(route.content, {
204
- status: 200,
205
- headers: {
206
- "Content-Type": route.mimeType,
207
- ...customHeaders(route.customHeaders)
208
- }
209
- })
210
- )
211
- );
212
- }
213
- case "asset": {
214
- return contello[runRequest](
215
- { url, route, rewritten: false },
216
- () => wrap("route:asset", async () => {
217
- const result = await contello.client.download(route.fileId);
218
- const headers = new Headers({ "content-type": route.mimeType || result.mimeType });
219
- headers.set("content-disposition", route.contentDisposition);
220
- if (result.size > 0) {
221
- headers.set("content-length", String(result.size));
222
- }
223
- for (const { name, value } of route.customHeaders) {
224
- headers.set(name, value);
225
- }
226
- return new Response(result.stream(), { headers });
227
- })
228
- );
229
- }
230
- case "entity": {
231
- return contello[runRequest](
232
- { url, route, rewritten: true },
233
- () => wrap(`route:entity:${route.model}`, async () => {
234
- const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
235
- for (const { name, value } of route.customHeaders) {
236
- response.headers.set(name, value);
237
- }
238
- return response;
239
- })
240
- );
241
- }
242
- }
243
- });
244
- });
87
+ return (0, astro_middleware.defineMiddleware)((ctx, next) => {
88
+ if ((0, _astroscope_node_excludes.shouldExclude)(ctx, exclude ?? _astroscope_node_excludes.RECOMMENDED_EXCLUDES)) return next();
89
+ if (!contello.isReady) {
90
+ console.warn(`[@contello/astro] not initialized, passing through: ${ctx.url.pathname}`);
91
+ return next();
92
+ }
93
+ const { url } = ctx;
94
+ if (url.pathname.startsWith("/contello/entities/")) return contello[runRequest]({
95
+ url,
96
+ route: void 0,
97
+ rewritten: false
98
+ }, () => next());
99
+ const path = resolveRoutePath ? resolveRoutePath(ctx) : url.pathname;
100
+ return (0, _contello_store.maybeThen)(routes.getByPath(path), (route) => {
101
+ if (!route) return contello[runRequest]({
102
+ url,
103
+ route: void 0,
104
+ rewritten: false
105
+ }, () => next());
106
+ switch (route.type) {
107
+ case "redirect": return contello[runRequest]({
108
+ url,
109
+ route,
110
+ rewritten: false
111
+ }, () => wrap("route:redirect", () => new Response(null, {
112
+ status: toRedirectStatus(route.status),
113
+ headers: {
114
+ Location: route.location,
115
+ ...customHeaders(route.customHeaders)
116
+ }
117
+ })));
118
+ case "text": return contello[runRequest]({
119
+ url,
120
+ route,
121
+ rewritten: false
122
+ }, () => wrap("route:text", () => new Response(route.content, {
123
+ status: 200,
124
+ headers: {
125
+ "Content-Type": route.mimeType,
126
+ ...customHeaders(route.customHeaders)
127
+ }
128
+ })));
129
+ case "asset": return contello[runRequest]({
130
+ url,
131
+ route,
132
+ rewritten: false
133
+ }, () => wrap("route:asset", async () => {
134
+ const result = await contello.client.download(route.fileId);
135
+ const headers = new Headers({ "content-type": route.mimeType || result.mimeType });
136
+ headers.set("content-disposition", route.contentDisposition);
137
+ if (result.size > 0) headers.set("content-length", String(result.size));
138
+ for (const { name, value } of route.customHeaders) headers.set(name, value);
139
+ return new Response(result.stream(), { headers });
140
+ }));
141
+ case "entity": return contello[runRequest]({
142
+ url,
143
+ route,
144
+ rewritten: true
145
+ }, () => wrap(`route:entity:${route.model}`, async () => {
146
+ const response = await next(`/contello/entities/${route.model}/${route.entityId}${url.search}`);
147
+ for (const { name, value } of route.customHeaders) response.headers.set(name, value);
148
+ return response;
149
+ }));
150
+ }
151
+ });
152
+ });
245
153
  }
246
-
247
- // src/contello.ts
248
- var DEFAULT_IMAGES_PREFIX = "/_contello/i/";
249
- var DEFAULT_FILES_PREFIX = "/_contello/f/";
250
- var DEFAULT_VIDEO_PREFIX = "/_contello/v/";
251
- var runRequest = /* @__PURE__ */ Symbol("@contello/astro/runRequest");
154
+ //#endregion
155
+ //#region src/contello.ts
156
+ const DEFAULT_IMAGES_PREFIX = "/_contello/i/";
157
+ const DEFAULT_FILES_PREFIX = "/_contello/f/";
158
+ const DEFAULT_VIDEO_PREFIX = "/_contello/v/";
159
+ const runRequest = Symbol("@contello/astro/runRequest");
252
160
  function buildI18nRegistrations() {
253
- const manifest = import_i18n.i18n.getManifest();
254
- const defaultLanguage = import_i18n.i18n.getConfig().defaultLocale;
255
- return manifest.keys.map((extracted) => ({
256
- token: extracted.key,
257
- example: extracted.meta.fallback,
258
- description: extracted.meta.description ?? "",
259
- variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
260
- name,
261
- description: def?.description ?? "",
262
- example: def?.fallback ?? ""
263
- })),
264
- initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }]
265
- }));
161
+ const manifest = _astroscope_i18n.i18n.getManifest();
162
+ const defaultLanguage = _astroscope_i18n.i18n.getConfig().defaultLocale;
163
+ return manifest.keys.map((extracted) => ({
164
+ token: extracted.key,
165
+ example: extracted.meta.fallback,
166
+ description: extracted.meta.description ?? "",
167
+ variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
168
+ name,
169
+ description: def?.description ?? "",
170
+ example: def?.fallback ?? ""
171
+ })),
172
+ initialTranslations: [{
173
+ language: defaultLanguage,
174
+ message: extracted.meta.fallback
175
+ }]
176
+ }));
266
177
  }
267
178
  async function applyTranslations(messages) {
268
- const config = import_i18n.i18n.getConfig();
269
- const all = await messages.getAll();
270
- const byLocale = /* @__PURE__ */ new Map();
271
- for (const locale of config.locales) {
272
- byLocale.set(locale, {});
273
- }
274
- for (const msg of all) {
275
- msg.translations.forEach((value, language) => {
276
- const raw = byLocale.get(language);
277
- if (raw) {
278
- raw[msg.token] = value;
279
- }
280
- });
281
- }
282
- for (const [locale, translations] of byLocale.entries()) {
283
- import_i18n.i18n.setTranslations(locale, translations);
284
- }
179
+ const config = _astroscope_i18n.i18n.getConfig();
180
+ const all = await messages.getAll();
181
+ const byLocale = /* @__PURE__ */ new Map();
182
+ for (const locale of config.locales) byLocale.set(locale, {});
183
+ for (const msg of all) msg.translations.forEach((value, language) => {
184
+ const raw = byLocale.get(language);
185
+ if (raw) raw[msg.token] = value;
186
+ });
187
+ for (const [locale, translations] of byLocale) _astroscope_i18n.i18n.setTranslations(locale, translations);
285
188
  }
286
189
  var Contello = class {
287
- _store;
288
- _options;
289
- _i18nMessages;
290
- _i18nUnsubscribe;
291
- _initialized = false;
292
- _als = new import_node_async_hooks.AsyncLocalStorage();
293
- _autoLazyRoutes;
294
- media;
295
- constructor(options) {
296
- this._options = options;
297
- this._store = (0, import_store2.createStore)(options);
298
- this.media = {
299
- baseUrl: options.media?.baseUrl ?? "",
300
- imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
301
- videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,
302
- filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
303
- };
304
- }
305
- // --- lifecycle ---
306
- async init(options) {
307
- try {
308
- await this._store.init();
309
- if (this._options.i18n) {
310
- const { collection, languages, cache } = this._options.i18n;
311
- const { register = true, load = true } = options?.i18n ?? {};
312
- this._i18nMessages = this._store.defineI18nMessages({ collection, cache });
313
- await import_i18n.i18n.configure({ locales: languages });
314
- if (register) {
315
- const registrations = buildI18nRegistrations();
316
- if (registrations.length > 0) {
317
- await this._i18nMessages.register(registrations);
318
- }
319
- }
320
- if (load) {
321
- await applyTranslations(this._i18nMessages);
322
- const messages = this._i18nMessages;
323
- const controller = new AbortController();
324
- this._i18nUnsubscribe = () => controller.abort();
325
- void (async () => {
326
- for await (const _ of messages.refresh$) {
327
- if (controller.signal.aborted) {
328
- return;
329
- }
330
- await applyTranslations(messages);
331
- }
332
- })();
333
- }
334
- }
335
- await Promise.all((options?.load ?? []).map((l) => l.load()));
336
- this._initialized = true;
337
- } catch (error) {
338
- await this.destroy().catch(() => {
339
- });
340
- throw error;
341
- }
342
- }
343
- async destroy() {
344
- this._initialized = false;
345
- this._i18nUnsubscribe?.();
346
- this._i18nUnsubscribe = void 0;
347
- await this._store.destroy();
348
- this._i18nMessages = void 0;
349
- }
350
- ping() {
351
- return this._store.ping();
352
- }
353
- get isReady() {
354
- return this._initialized;
355
- }
356
- get client() {
357
- return this._store.client;
358
- }
359
- get i18nMessages() {
360
- if (!this._i18nMessages) {
361
- throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
362
- }
363
- return this._i18nMessages;
364
- }
365
- // --- ALS request context ---
366
- get request() {
367
- const ctx = this._als.getStore();
368
- if (!ctx) {
369
- throw new Error("@contello/astro: .request accessed outside of request context");
370
- }
371
- return ctx;
372
- }
373
- // --- media resolvers (on-demand) ---
374
- defineMediaResolver(options) {
375
- return (0, import_media.createMediaResolver)({
376
- ...this.media,
377
- ...options
378
- });
379
- }
380
- // --- store delegation ---
381
- defineSingleton(sourceOrKey, options) {
382
- return this._store.defineSingleton(sourceOrKey, options);
383
- }
384
- defineSingletonSync(sourceOrKey, options) {
385
- return this._store.defineSingletonSync(sourceOrKey, options);
386
- }
387
- defineCollection(sourceOrKey, options) {
388
- return this._store.defineCollection(sourceOrKey, options);
389
- }
390
- defineCollectionSync(sourceOrKey, options) {
391
- return this._store.defineCollectionSync(sourceOrKey, options);
392
- }
393
- defineLazyCollection(sourceOrKey, options) {
394
- return this._store.defineLazyCollection(sourceOrKey, options);
395
- }
396
- defineRoutes(options) {
397
- return this._store.defineRoutes(options);
398
- }
399
- defineRoutesSync(options) {
400
- return this._store.defineRoutesSync(options);
401
- }
402
- defineLazyRoutes(options) {
403
- return this._store.defineLazyRoutes(options);
404
- }
405
- defineAssets(options) {
406
- return this._store.defineAssets(options);
407
- }
408
- defineAssetsSync(options) {
409
- return this._store.defineAssetsSync(options);
410
- }
411
- defineLazyAssets(options) {
412
- return this._store.defineLazyAssets(options);
413
- }
414
- // --- middleware factories (arrow fields so destructuring works) ---
415
- createRoutingMiddleware = (options) => {
416
- const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
417
- return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
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
- }
190
+ _store;
191
+ _options;
192
+ _i18nMessages;
193
+ _i18nUnsubscribe;
194
+ _initialized = false;
195
+ _als = new node_async_hooks.AsyncLocalStorage();
196
+ _autoLazyRoutes;
197
+ media;
198
+ createRoutingMiddleware = (options) => {
199
+ const routes = options?.routes ?? (this._autoLazyRoutes ??= this.defineLazyRoutes());
200
+ return createBoundRoutingMiddleware(this, routes, options?.exclude, options?.resolveRoutePath);
201
+ };
202
+ createAssetsMiddleware = (options) => {
203
+ return createBoundAssetsMiddleware(this, options);
204
+ };
205
+ constructor(options) {
206
+ this._options = options;
207
+ this._store = (0, _contello_store.createStore)(options);
208
+ this.media = {
209
+ baseUrl: options.media?.baseUrl ?? "",
210
+ imagesPath: options.media?.imagesPath ?? DEFAULT_IMAGES_PREFIX,
211
+ videosPath: options.media?.videosPath ?? DEFAULT_VIDEO_PREFIX,
212
+ filesPath: options.media?.filesPath ?? DEFAULT_FILES_PREFIX
213
+ };
214
+ }
215
+ async init(options) {
216
+ try {
217
+ await this._store.init();
218
+ if (this._options.i18n) {
219
+ const { collection, languages, cache } = this._options.i18n;
220
+ const dev = (0, _astroscope_node_boot.getBootContext)()?.dev ?? false;
221
+ const { register = !dev, load = true } = options?.i18n ?? {};
222
+ this._i18nMessages = this._store.defineI18nMessages({
223
+ collection,
224
+ cache
225
+ });
226
+ await _astroscope_i18n.i18n.configure({ locales: languages });
227
+ if (register) {
228
+ const registrations = buildI18nRegistrations();
229
+ if (registrations.length > 0) await this._i18nMessages.register(registrations);
230
+ }
231
+ if (load) {
232
+ await applyTranslations(this._i18nMessages);
233
+ const messages = this._i18nMessages;
234
+ const controller = new AbortController();
235
+ this._i18nUnsubscribe = () => controller.abort();
236
+ (async () => {
237
+ for await (const _ of messages.refresh$) {
238
+ if (controller.signal.aborted) return;
239
+ await applyTranslations(messages);
240
+ }
241
+ })();
242
+ }
243
+ }
244
+ await Promise.all((options?.load ?? []).map((l) => l.load()));
245
+ this._initialized = true;
246
+ } catch (error) {
247
+ try {
248
+ await this.destroy();
249
+ } catch {}
250
+ throw error;
251
+ }
252
+ }
253
+ async destroy() {
254
+ this._initialized = false;
255
+ this._i18nUnsubscribe?.();
256
+ this._i18nUnsubscribe = void 0;
257
+ await this._store.destroy();
258
+ this._i18nMessages = void 0;
259
+ }
260
+ ping() {
261
+ return this._store.ping();
262
+ }
263
+ get isReady() {
264
+ return this._initialized;
265
+ }
266
+ get client() {
267
+ return this._store.client;
268
+ }
269
+ get i18nMessages() {
270
+ if (!this._i18nMessages) throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
271
+ return this._i18nMessages;
272
+ }
273
+ get request() {
274
+ const ctx = this._als.getStore();
275
+ if (!ctx) throw new Error("@contello/astro: .request accessed outside of request context");
276
+ return ctx;
277
+ }
278
+ defineMediaResolver(options) {
279
+ return (0, _contello_media.createMediaResolver)({
280
+ ...this.media,
281
+ ...options
282
+ });
283
+ }
284
+ defineSingleton(sourceOrKey, options) {
285
+ return this._store.defineSingleton(sourceOrKey, options);
286
+ }
287
+ defineSingletonSync(sourceOrKey, options) {
288
+ return this._store.defineSingletonSync(sourceOrKey, options);
289
+ }
290
+ defineCollection(sourceOrKey, options) {
291
+ return this._store.defineCollection(sourceOrKey, options);
292
+ }
293
+ defineCollectionSync(sourceOrKey, options) {
294
+ return this._store.defineCollectionSync(sourceOrKey, options);
295
+ }
296
+ defineLazyCollection(sourceOrKey, options) {
297
+ return this._store.defineLazyCollection(sourceOrKey, options);
298
+ }
299
+ defineRoutes(options) {
300
+ return this._store.defineRoutes(options);
301
+ }
302
+ defineRoutesSync(options) {
303
+ return this._store.defineRoutesSync(options);
304
+ }
305
+ defineLazyRoutes(options) {
306
+ return this._store.defineLazyRoutes(options);
307
+ }
308
+ defineAssets(options) {
309
+ return this._store.defineAssets(options);
310
+ }
311
+ defineAssetsSync(options) {
312
+ return this._store.defineAssetsSync(options);
313
+ }
314
+ defineLazyAssets(options) {
315
+ return this._store.defineLazyAssets(options);
316
+ }
317
+ [runRequest](ctx, fn) {
318
+ return this._als.run(ctx, fn);
319
+ }
426
320
  };
427
321
  function createContello(options) {
428
- return new Contello(options);
322
+ return new Contello(options);
429
323
  }
430
- // Annotate the CommonJS export names for ESM import in node:
431
- 0 && (module.exports = {
432
- Contello,
433
- createContello
434
- });
324
+ //#endregion
325
+ exports.Contello = Contello;
326
+ exports.createContello = createContello;