@contello/astro 1.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 ADDED
@@ -0,0 +1,302 @@
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
+ createRoutingMiddleware: () => createRoutingMiddleware
36
+ });
37
+ module.exports = __toCommonJS(index_exports);
38
+
39
+ // src/contello.ts
40
+ var import_node_async_hooks = require("async_hooks");
41
+ var import_i18n = require("@astroscope/i18n");
42
+ var import_store = require("@contello/store");
43
+ var runRequest = /* @__PURE__ */ Symbol("@contello/astro/runRequest");
44
+ function buildI18nRegistrations() {
45
+ const manifest = import_i18n.i18n.getManifest();
46
+ const defaultLanguage = import_i18n.i18n.getConfig().defaultLocale;
47
+ return manifest.keys.map((extracted) => ({
48
+ token: extracted.key,
49
+ example: extracted.meta.fallback,
50
+ description: extracted.meta.description ?? "",
51
+ variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
52
+ name,
53
+ description: def?.description ?? "",
54
+ example: def?.fallback ?? ""
55
+ })),
56
+ initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }]
57
+ }));
58
+ }
59
+ async function applyTranslations(messages) {
60
+ const config = import_i18n.i18n.getConfig();
61
+ const all = await messages.getAll();
62
+ const byLocale = /* @__PURE__ */ new Map();
63
+ for (const locale of config.locales) {
64
+ byLocale.set(locale, {});
65
+ }
66
+ for (const msg of all) {
67
+ msg.translations.forEach((value, language) => {
68
+ const raw = byLocale.get(language);
69
+ if (raw) {
70
+ raw[msg.token] = value;
71
+ }
72
+ });
73
+ }
74
+ for (const [locale, translations] of byLocale.entries()) {
75
+ import_i18n.i18n.setTranslations(locale, translations);
76
+ }
77
+ }
78
+ var Contello = class {
79
+ _store;
80
+ _options;
81
+ _assets;
82
+ _routes;
83
+ _i18nMessages;
84
+ _i18nSubscription;
85
+ _als = new import_node_async_hooks.AsyncLocalStorage();
86
+ constructor(options) {
87
+ this._options = options;
88
+ this._store = (0, import_store.createStore)(options);
89
+ }
90
+ // --- lifecycle ---
91
+ async init() {
92
+ await this._store.init();
93
+ this._assets = this._store.defineAssets(this._options.assets);
94
+ this._routes = this._store.defineRoutes(this._options.routes);
95
+ if (this._options.i18n) {
96
+ const { collection, locales, register = true, load = true } = this._options.i18n;
97
+ this._i18nMessages = this._store.defineI18nMessages({ collection });
98
+ await import_i18n.i18n.configure({ locales });
99
+ if (register) {
100
+ const registrations = buildI18nRegistrations();
101
+ if (registrations.length > 0) {
102
+ await this._i18nMessages.register(registrations);
103
+ }
104
+ }
105
+ if (load) {
106
+ await applyTranslations(this._i18nMessages);
107
+ const messages = this._i18nMessages;
108
+ this._i18nSubscription = messages.refresh$.subscribe(() => applyTranslations(messages));
109
+ }
110
+ }
111
+ }
112
+ async destroy() {
113
+ this._i18nSubscription?.unsubscribe();
114
+ this._i18nSubscription = void 0;
115
+ await this._store.destroy();
116
+ this._assets = void 0;
117
+ this._routes = void 0;
118
+ this._i18nMessages = void 0;
119
+ }
120
+ ping() {
121
+ return this._store.ping();
122
+ }
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;
135
+ }
136
+ get i18nMessages() {
137
+ if (!this._i18nMessages) {
138
+ throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
139
+ }
140
+ return this._i18nMessages;
141
+ }
142
+ // --- ALS request context ---
143
+ get request() {
144
+ const ctx = this._als.getStore();
145
+ if (!ctx) {
146
+ throw new Error("@contello/astro: .request accessed outside of request context");
147
+ }
148
+ return ctx;
149
+ }
150
+ // --- store delegation ---
151
+ defineSingleton(def) {
152
+ return this._store.defineSingleton(def);
153
+ }
154
+ defineSingletonSync(def) {
155
+ return this._store.defineSingletonSync(def);
156
+ }
157
+ defineCollection(def) {
158
+ return this._store.defineCollection(def);
159
+ }
160
+ defineCollectionSync(def) {
161
+ return this._store.defineCollectionSync(def);
162
+ }
163
+ defineLazyCollection(def) {
164
+ return this._store.defineLazyCollection(def);
165
+ }
166
+ // --- ALS run ---
167
+ [runRequest](ctx, fn) {
168
+ return this._als.run(ctx, fn);
169
+ }
170
+ };
171
+ function createContello(options) {
172
+ return new Contello(options);
173
+ }
174
+
175
+ // src/middleware.ts
176
+ var import_excludes = require("@astroscope/excludes");
177
+ var import_middleware = require("astro/middleware");
178
+
179
+ // src/diagnostics.ts
180
+ var import_node_diagnostics_channel = __toESM(require("diagnostics_channel"), 1);
181
+ var channels = {
182
+ start: "contello:astro.start",
183
+ end: "contello:astro.end",
184
+ error: "contello:astro.error"
185
+ };
186
+ var onStart = import_node_diagnostics_channel.default.channel(channels.start);
187
+ var onEnd = import_node_diagnostics_channel.default.channel(channels.end);
188
+ var onError = import_node_diagnostics_channel.default.channel(channels.error);
189
+ function hasSubscribers() {
190
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
191
+ }
192
+ function wrap(name, fn) {
193
+ if (!hasSubscribers()) {
194
+ return fn();
195
+ }
196
+ const start = performance.now();
197
+ onStart.publish({ name });
198
+ let result;
199
+ try {
200
+ result = fn();
201
+ } catch (error) {
202
+ onError.publish({ name, error, durationMs: performance.now() - start });
203
+ throw error;
204
+ }
205
+ if (result instanceof Promise) {
206
+ return result.then(
207
+ (r) => {
208
+ onEnd.publish({ name, durationMs: performance.now() - start });
209
+ return r;
210
+ },
211
+ (error) => {
212
+ onError.publish({ name, error, durationMs: performance.now() - start });
213
+ throw error;
214
+ }
215
+ );
216
+ }
217
+ onEnd.publish({ name, durationMs: performance.now() - start });
218
+ return result;
219
+ }
220
+
221
+ // src/middleware.ts
222
+ function customHeaders(headers) {
223
+ const result = {};
224
+ for (const h of headers) {
225
+ result[h.name] = h.value;
226
+ }
227
+ return result;
228
+ }
229
+ function createRoutingMiddleware(instance, options) {
230
+ const { exclude } = options ?? {};
231
+ return (0, import_middleware.defineMiddleware)(async (ctx, next) => {
232
+ if ((0, import_excludes.shouldExclude)(ctx, exclude ?? import_excludes.RECOMMENDED_EXCLUDES)) {
233
+ return next();
234
+ }
235
+ const { url } = ctx;
236
+ if (url.pathname.startsWith("/contello/entities/")) {
237
+ return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
238
+ }
239
+ const route = await instance.routes.getByPath(url.pathname);
240
+ if (!route) {
241
+ return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
242
+ }
243
+ switch (route.type) {
244
+ case "redirect":
245
+ return instance[runRequest](
246
+ { url, route, rewritten: false },
247
+ () => wrap(
248
+ "route:redirect",
249
+ () => new Response(null, {
250
+ status: route.status,
251
+ headers: {
252
+ Location: route.location,
253
+ ...customHeaders(route.customHeaders)
254
+ }
255
+ })
256
+ )
257
+ );
258
+ case "text":
259
+ return instance[runRequest](
260
+ { url, route, rewritten: false },
261
+ () => wrap(
262
+ "route:text",
263
+ () => new Response(route.content, {
264
+ status: 200,
265
+ headers: {
266
+ "Content-Type": route.mimeType,
267
+ ...customHeaders(route.customHeaders)
268
+ }
269
+ })
270
+ )
271
+ );
272
+ case "asset":
273
+ return instance[runRequest](
274
+ { url, route, rewritten: false },
275
+ () => wrap("route:asset", async () => {
276
+ const response = await instance.assets.download(route.fileId);
277
+ for (const { name, value } of route.customHeaders) {
278
+ response.headers.set(name, value);
279
+ }
280
+ return response;
281
+ })
282
+ );
283
+ case "entity":
284
+ return instance[runRequest](
285
+ { url, route, rewritten: true },
286
+ () => wrap(`route:entity:${route.entityType}`, async () => {
287
+ const response = await next(`/contello/entities/${route.entityType}/${route.entityId}${url.search}`);
288
+ for (const { name, value } of route.customHeaders) {
289
+ response.headers.set(name, value);
290
+ }
291
+ return response;
292
+ })
293
+ );
294
+ }
295
+ });
296
+ }
297
+ // Annotate the CommonJS export names for ESM import in node:
298
+ 0 && (module.exports = {
299
+ Contello,
300
+ createContello,
301
+ createRoutingMiddleware
302
+ });
@@ -0,0 +1,58 @@
1
+ import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Assets, Routes, I18nMessages, StoreRoute, SingletonDef, Singleton, SingletonSyncDef, SingletonSync, CollectionDef, Collection, CollectionSyncDef, CollectionSync, LazyCollectionDef, LazyCollection } from '@contello/store';
2
+ import * as astro from 'astro';
3
+ import { ExcludePattern } from '@astroscope/excludes';
4
+
5
+ type ContelloRequestContext = {
6
+ url: URL;
7
+ route: StoreRoute | undefined;
8
+ rewritten: boolean;
9
+ };
10
+ type ContelloI18nOptions = {
11
+ collection: string;
12
+ locales: string[];
13
+ register?: boolean | undefined;
14
+ load?: boolean | undefined;
15
+ };
16
+ type ContelloOptions<TSdk, TEntityTypes extends string = string> = CreateStoreOptions<TSdk, TEntityTypes> & {
17
+ assets?: AssetCollectionOptions | undefined;
18
+ i18n?: ContelloI18nOptions | undefined;
19
+ routes?: RouteCollectionOptions | undefined;
20
+ };
21
+ declare const runRequest: unique symbol;
22
+ declare class Contello<TSdk, TEntityTypes extends string = string> {
23
+ private readonly _store;
24
+ private readonly _options;
25
+ private _assets;
26
+ private _routes;
27
+ private _i18nMessages;
28
+ private _i18nSubscription;
29
+ private readonly _als;
30
+ constructor(options: ContelloOptions<TSdk, TEntityTypes>);
31
+ init(): Promise<void>;
32
+ destroy(): Promise<void>;
33
+ ping(): Promise<void>;
34
+ get assets(): Assets;
35
+ get routes(): Routes;
36
+ get i18nMessages(): I18nMessages;
37
+ get request(): ContelloRequestContext;
38
+ defineSingleton<TModel extends TEntityTypes, TRaw, TMapped>(def: SingletonDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): Singleton<TMapped>;
39
+ defineSingletonSync<TModel extends TEntityTypes, TRaw, TMapped>(def: SingletonSyncDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): SingletonSync<TMapped>;
40
+ defineCollection<TModel extends TEntityTypes, TRaw, TMapped extends {
41
+ id: string;
42
+ }>(def: CollectionDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): Collection<TMapped>;
43
+ defineCollectionSync<TModel extends TEntityTypes, TRaw, TMapped extends {
44
+ id: string;
45
+ }>(def: CollectionSyncDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): CollectionSync<TMapped>;
46
+ defineLazyCollection<TModel extends TEntityTypes, TRaw, TMapped extends {
47
+ id: string;
48
+ }>(def: LazyCollectionDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): LazyCollection<TMapped>;
49
+ [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
50
+ }
51
+ declare function createContello<TSdk, TEntityTypes extends string = string>(options: ContelloOptions<TSdk, TEntityTypes>): Contello<TSdk, TEntityTypes>;
52
+
53
+ type ContelloMiddlewareOptions = {
54
+ exclude?: ExcludePattern[] | undefined;
55
+ };
56
+ declare function createRoutingMiddleware(instance: Contello<any, any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
57
+
58
+ export { Contello, type ContelloI18nOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createContello, createRoutingMiddleware };
@@ -0,0 +1,58 @@
1
+ import { CreateStoreOptions, AssetCollectionOptions, RouteCollectionOptions, Assets, Routes, I18nMessages, StoreRoute, SingletonDef, Singleton, SingletonSyncDef, SingletonSync, CollectionDef, Collection, CollectionSyncDef, CollectionSync, LazyCollectionDef, LazyCollection } from '@contello/store';
2
+ import * as astro from 'astro';
3
+ import { ExcludePattern } from '@astroscope/excludes';
4
+
5
+ type ContelloRequestContext = {
6
+ url: URL;
7
+ route: StoreRoute | undefined;
8
+ rewritten: boolean;
9
+ };
10
+ type ContelloI18nOptions = {
11
+ collection: string;
12
+ locales: string[];
13
+ register?: boolean | undefined;
14
+ load?: boolean | undefined;
15
+ };
16
+ type ContelloOptions<TSdk, TEntityTypes extends string = string> = CreateStoreOptions<TSdk, TEntityTypes> & {
17
+ assets?: AssetCollectionOptions | undefined;
18
+ i18n?: ContelloI18nOptions | undefined;
19
+ routes?: RouteCollectionOptions | undefined;
20
+ };
21
+ declare const runRequest: unique symbol;
22
+ declare class Contello<TSdk, TEntityTypes extends string = string> {
23
+ private readonly _store;
24
+ private readonly _options;
25
+ private _assets;
26
+ private _routes;
27
+ private _i18nMessages;
28
+ private _i18nSubscription;
29
+ private readonly _als;
30
+ constructor(options: ContelloOptions<TSdk, TEntityTypes>);
31
+ init(): Promise<void>;
32
+ destroy(): Promise<void>;
33
+ ping(): Promise<void>;
34
+ get assets(): Assets;
35
+ get routes(): Routes;
36
+ get i18nMessages(): I18nMessages;
37
+ get request(): ContelloRequestContext;
38
+ defineSingleton<TModel extends TEntityTypes, TRaw, TMapped>(def: SingletonDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): Singleton<TMapped>;
39
+ defineSingletonSync<TModel extends TEntityTypes, TRaw, TMapped>(def: SingletonSyncDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): SingletonSync<TMapped>;
40
+ defineCollection<TModel extends TEntityTypes, TRaw, TMapped extends {
41
+ id: string;
42
+ }>(def: CollectionDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): Collection<TMapped>;
43
+ defineCollectionSync<TModel extends TEntityTypes, TRaw, TMapped extends {
44
+ id: string;
45
+ }>(def: CollectionSyncDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): CollectionSync<TMapped>;
46
+ defineLazyCollection<TModel extends TEntityTypes, TRaw, TMapped extends {
47
+ id: string;
48
+ }>(def: LazyCollectionDef<TSdk, TModel, TRaw, TMapped, TEntityTypes>): LazyCollection<TMapped>;
49
+ [runRequest]<T>(ctx: ContelloRequestContext, fn: () => T): T;
50
+ }
51
+ declare function createContello<TSdk, TEntityTypes extends string = string>(options: ContelloOptions<TSdk, TEntityTypes>): Contello<TSdk, TEntityTypes>;
52
+
53
+ type ContelloMiddlewareOptions = {
54
+ exclude?: ExcludePattern[] | undefined;
55
+ };
56
+ declare function createRoutingMiddleware(instance: Contello<any, any>, options?: ContelloMiddlewareOptions | undefined): astro.MiddlewareHandler;
57
+
58
+ export { Contello, type ContelloI18nOptions, type ContelloMiddlewareOptions, type ContelloOptions, type ContelloRequestContext, createContello, createRoutingMiddleware };
package/dist/index.js ADDED
@@ -0,0 +1,265 @@
1
+ // src/contello.ts
2
+ import { AsyncLocalStorage } from "async_hooks";
3
+ import { i18n } from "@astroscope/i18n";
4
+ import {
5
+ createStore
6
+ } from "@contello/store";
7
+ var runRequest = /* @__PURE__ */ Symbol("@contello/astro/runRequest");
8
+ function buildI18nRegistrations() {
9
+ const manifest = i18n.getManifest();
10
+ const defaultLanguage = i18n.getConfig().defaultLocale;
11
+ return manifest.keys.map((extracted) => ({
12
+ token: extracted.key,
13
+ example: extracted.meta.fallback,
14
+ description: extracted.meta.description ?? "",
15
+ variables: Object.entries(extracted.meta.variables ?? {}).map(([name, def]) => ({
16
+ name,
17
+ description: def?.description ?? "",
18
+ example: def?.fallback ?? ""
19
+ })),
20
+ initialTranslations: [{ language: defaultLanguage, message: extracted.meta.fallback }]
21
+ }));
22
+ }
23
+ async function applyTranslations(messages) {
24
+ const config = i18n.getConfig();
25
+ const all = await messages.getAll();
26
+ const byLocale = /* @__PURE__ */ new Map();
27
+ for (const locale of config.locales) {
28
+ byLocale.set(locale, {});
29
+ }
30
+ for (const msg of all) {
31
+ msg.translations.forEach((value, language) => {
32
+ const raw = byLocale.get(language);
33
+ if (raw) {
34
+ raw[msg.token] = value;
35
+ }
36
+ });
37
+ }
38
+ for (const [locale, translations] of byLocale.entries()) {
39
+ i18n.setTranslations(locale, translations);
40
+ }
41
+ }
42
+ var Contello = class {
43
+ _store;
44
+ _options;
45
+ _assets;
46
+ _routes;
47
+ _i18nMessages;
48
+ _i18nSubscription;
49
+ _als = new AsyncLocalStorage();
50
+ constructor(options) {
51
+ this._options = options;
52
+ this._store = createStore(options);
53
+ }
54
+ // --- lifecycle ---
55
+ async init() {
56
+ await this._store.init();
57
+ this._assets = this._store.defineAssets(this._options.assets);
58
+ this._routes = this._store.defineRoutes(this._options.routes);
59
+ if (this._options.i18n) {
60
+ const { collection, locales, register = true, load = true } = this._options.i18n;
61
+ this._i18nMessages = this._store.defineI18nMessages({ collection });
62
+ await i18n.configure({ locales });
63
+ if (register) {
64
+ const registrations = buildI18nRegistrations();
65
+ if (registrations.length > 0) {
66
+ await this._i18nMessages.register(registrations);
67
+ }
68
+ }
69
+ if (load) {
70
+ await applyTranslations(this._i18nMessages);
71
+ const messages = this._i18nMessages;
72
+ this._i18nSubscription = messages.refresh$.subscribe(() => applyTranslations(messages));
73
+ }
74
+ }
75
+ }
76
+ async destroy() {
77
+ this._i18nSubscription?.unsubscribe();
78
+ this._i18nSubscription = void 0;
79
+ await this._store.destroy();
80
+ this._assets = void 0;
81
+ this._routes = void 0;
82
+ this._i18nMessages = void 0;
83
+ }
84
+ ping() {
85
+ return this._store.ping();
86
+ }
87
+ // --- pre-wired collections ---
88
+ get assets() {
89
+ if (!this._assets) {
90
+ throw new Error("@contello/astro: .assets accessed before init()");
91
+ }
92
+ return this._assets;
93
+ }
94
+ get routes() {
95
+ if (!this._routes) {
96
+ throw new Error("@contello/astro: .routes accessed before init()");
97
+ }
98
+ return this._routes;
99
+ }
100
+ get i18nMessages() {
101
+ if (!this._i18nMessages) {
102
+ throw new Error("@contello/astro: .i18nMessages accessed before init() with i18n config");
103
+ }
104
+ return this._i18nMessages;
105
+ }
106
+ // --- ALS request context ---
107
+ get request() {
108
+ const ctx = this._als.getStore();
109
+ if (!ctx) {
110
+ throw new Error("@contello/astro: .request accessed outside of request context");
111
+ }
112
+ return ctx;
113
+ }
114
+ // --- store delegation ---
115
+ defineSingleton(def) {
116
+ return this._store.defineSingleton(def);
117
+ }
118
+ defineSingletonSync(def) {
119
+ return this._store.defineSingletonSync(def);
120
+ }
121
+ defineCollection(def) {
122
+ return this._store.defineCollection(def);
123
+ }
124
+ defineCollectionSync(def) {
125
+ return this._store.defineCollectionSync(def);
126
+ }
127
+ defineLazyCollection(def) {
128
+ return this._store.defineLazyCollection(def);
129
+ }
130
+ // --- ALS run ---
131
+ [runRequest](ctx, fn) {
132
+ return this._als.run(ctx, fn);
133
+ }
134
+ };
135
+ function createContello(options) {
136
+ return new Contello(options);
137
+ }
138
+
139
+ // src/middleware.ts
140
+ import { RECOMMENDED_EXCLUDES, shouldExclude } from "@astroscope/excludes";
141
+ import { defineMiddleware } from "astro/middleware";
142
+
143
+ // src/diagnostics.ts
144
+ import dc from "diagnostics_channel";
145
+ var channels = {
146
+ start: "contello:astro.start",
147
+ end: "contello:astro.end",
148
+ error: "contello:astro.error"
149
+ };
150
+ var onStart = dc.channel(channels.start);
151
+ var onEnd = dc.channel(channels.end);
152
+ var onError = dc.channel(channels.error);
153
+ function hasSubscribers() {
154
+ return onStart.hasSubscribers || onEnd.hasSubscribers || onError.hasSubscribers;
155
+ }
156
+ function wrap(name, fn) {
157
+ if (!hasSubscribers()) {
158
+ return fn();
159
+ }
160
+ const start = performance.now();
161
+ onStart.publish({ name });
162
+ let result;
163
+ try {
164
+ result = fn();
165
+ } catch (error) {
166
+ onError.publish({ name, error, durationMs: performance.now() - start });
167
+ throw error;
168
+ }
169
+ if (result instanceof Promise) {
170
+ return result.then(
171
+ (r) => {
172
+ onEnd.publish({ name, durationMs: performance.now() - start });
173
+ return r;
174
+ },
175
+ (error) => {
176
+ onError.publish({ name, error, durationMs: performance.now() - start });
177
+ throw error;
178
+ }
179
+ );
180
+ }
181
+ onEnd.publish({ name, durationMs: performance.now() - start });
182
+ return result;
183
+ }
184
+
185
+ // src/middleware.ts
186
+ function customHeaders(headers) {
187
+ const result = {};
188
+ for (const h of headers) {
189
+ result[h.name] = h.value;
190
+ }
191
+ return result;
192
+ }
193
+ function createRoutingMiddleware(instance, options) {
194
+ const { exclude } = options ?? {};
195
+ return defineMiddleware(async (ctx, next) => {
196
+ if (shouldExclude(ctx, exclude ?? RECOMMENDED_EXCLUDES)) {
197
+ return next();
198
+ }
199
+ const { url } = ctx;
200
+ if (url.pathname.startsWith("/contello/entities/")) {
201
+ return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
202
+ }
203
+ const route = await instance.routes.getByPath(url.pathname);
204
+ if (!route) {
205
+ return instance[runRequest]({ url, route: void 0, rewritten: false }, () => next());
206
+ }
207
+ switch (route.type) {
208
+ case "redirect":
209
+ return instance[runRequest](
210
+ { url, route, rewritten: false },
211
+ () => wrap(
212
+ "route:redirect",
213
+ () => new Response(null, {
214
+ status: route.status,
215
+ headers: {
216
+ Location: route.location,
217
+ ...customHeaders(route.customHeaders)
218
+ }
219
+ })
220
+ )
221
+ );
222
+ case "text":
223
+ return instance[runRequest](
224
+ { url, route, rewritten: false },
225
+ () => wrap(
226
+ "route:text",
227
+ () => new Response(route.content, {
228
+ status: 200,
229
+ headers: {
230
+ "Content-Type": route.mimeType,
231
+ ...customHeaders(route.customHeaders)
232
+ }
233
+ })
234
+ )
235
+ );
236
+ case "asset":
237
+ return instance[runRequest](
238
+ { url, route, rewritten: false },
239
+ () => wrap("route:asset", async () => {
240
+ const response = await instance.assets.download(route.fileId);
241
+ for (const { name, value } of route.customHeaders) {
242
+ response.headers.set(name, value);
243
+ }
244
+ return response;
245
+ })
246
+ );
247
+ case "entity":
248
+ return instance[runRequest](
249
+ { url, route, rewritten: true },
250
+ () => wrap(`route:entity:${route.entityType}`, async () => {
251
+ const response = await next(`/contello/entities/${route.entityType}/${route.entityId}${url.search}`);
252
+ for (const { name, value } of route.customHeaders) {
253
+ response.headers.set(name, value);
254
+ }
255
+ return response;
256
+ })
257
+ );
258
+ }
259
+ });
260
+ }
261
+ export {
262
+ Contello,
263
+ createContello,
264
+ createRoutingMiddleware
265
+ };
package/package.json ADDED
@@ -0,0 +1,50 @@
1
+ {
2
+ "name": "@contello/astro",
3
+ "version": "1.0.0",
4
+ "description": "Astro integration for Contello CMS — route middleware and i18n bridge",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "author": "admin@entwico.com",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/entwico/contello-js",
11
+ "directory": "packages/astro"
12
+ },
13
+ "scripts": {
14
+ "build": "tsup",
15
+ "lint": "eslint .",
16
+ "lint:fix": "eslint . --fix",
17
+ "typecheck": "tsc --noEmit"
18
+ },
19
+ "peerDependencies": {
20
+ "@astroscope/excludes": ">=0.1.0",
21
+ "@astroscope/i18n": ">=0.3.0",
22
+ "@contello/store": ">=0.0.0",
23
+ "astro": "^6.0.0"
24
+ },
25
+ "peerDependenciesMeta": {
26
+ "@astroscope/i18n": {
27
+ "optional": true
28
+ }
29
+ },
30
+ "devDependencies": {
31
+ "@astroscope/excludes": "^0.3.0",
32
+ "@astroscope/i18n": "^0.4.0",
33
+ "@contello/store": "workspace:*",
34
+ "astro": "^6.0.4"
35
+ },
36
+ "files": [
37
+ "dist"
38
+ ],
39
+ "types": "./dist/index.d.ts",
40
+ "exports": {
41
+ ".": {
42
+ "import": "./dist/index.js",
43
+ "require": "./dist/index.cjs"
44
+ }
45
+ },
46
+ "publishConfig": {
47
+ "access": "public",
48
+ "registry": "https://registry.npmjs.org"
49
+ }
50
+ }