@cimplify/sdk 0.49.1 → 0.50.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/server.d.mts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { C as CimplifyClient } from './client-BZZK1txR.mjs';
2
2
  export { aN as Result } from './client-BZZK1txR.mjs';
3
+ import { IncrementalCache } from '@opennextjs/aws/types/overrides';
3
4
  export { ap as Category, h as CimplifyError, ar as Collection, X as Product, aa as ProductWithDetails } from './product-C-xLzh7Q.mjs';
4
5
  import './payment-9L_-GWqQ.mjs';
5
6
 
@@ -84,21 +85,91 @@ declare const tags: {
84
85
  readonly order: (id: string) => string;
85
86
  };
86
87
 
87
- /** Next 16 `revalidateTag` profile arg — built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
88
- type RevalidateProfile$1 = string | {
89
- expire: number;
90
- };
91
88
  /**
92
- * Invalidate every cache entry tagged with the products list. Call after a
93
- * Server Action that creates / deletes / reorders products. The optional
94
- * `profile` is the Next 16 cacheLife profile (defaults to `'max'` SWR).
89
+ * Cimplify's opinionated cacheLife profiles for storefront server caches.
90
+ *
91
+ * Pass either of these to Next 16's `cacheLife(...)` inside a `'use cache'`
92
+ * server function. They're typed-literal exports so a typo fails at the SDK
93
+ * import site, not silently at runtime (Next's own `cacheLife(profile: string)`
94
+ * overload would accept anything and look it up as a custom profile).
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * import { cacheLife } from "next/cache";
99
+ * import { CACHE_LIFE_DEFAULT, CACHE_LIFE_PROBE, tags } from "@cimplify/sdk/server";
100
+ *
101
+ * async function getProducts() {
102
+ * "use cache";
103
+ * cacheTag(tags.products());
104
+ * const r = await getServerClient().catalogue.getProducts();
105
+ * // Don't lock in empties / failures — a transient bad render would
106
+ * // otherwise sit cached for the full "max" window.
107
+ * if (!r.ok || r.value.items.length === 0) {
108
+ * cacheLife(CACHE_LIFE_PROBE);
109
+ * return r;
110
+ * }
111
+ * cacheLife(CACHE_LIFE_DEFAULT);
112
+ * return r;
113
+ * }
114
+ * ```
95
115
  */
96
- declare function revalidateProducts(profile?: RevalidateProfile$1): Promise<void>;
97
116
  /**
98
- * Invalidate the cached detail of a single product (and the products list,
99
- * since list-shaped caches typically embed each product's denormalized
100
- * fields). Call after a Server Action that edits a product.
117
+ * The default cacheLife for cached storefront reads. Resolves to `"max"`,
118
+ * which is Next 16's longest built-in profile (stale 5min, revalidate 30d,
119
+ * never expires). Safe because Cimplify's tag-cache + CF cache-purge wiring
120
+ * invalidates on-demand within ~1s of a merchant edit — there's no benefit
121
+ * to short timer-based expirations on data Cimplify owns.
122
+ */
123
+ declare const CACHE_LIFE_DEFAULT: "max";
124
+ /**
125
+ * Short-lived cacheLife for "probe" results — empty arrays, errors, 404s,
126
+ * anything that *might* be a transient bad render. Resolves to `"seconds"`
127
+ * (stale 30s, revalidate 1s, expires 1min). Use this when the fetch returned
128
+ * no usable data so a momentary backend blip can't get locked into the cache
129
+ * for `CACHE_LIFE_DEFAULT`'s entire window.
130
+ *
131
+ * The tag still gets attached, so a real `revalidateTag(...)` from Cimplify
132
+ * will refresh the entry the moment the underlying data changes.
101
133
  */
134
+ declare const CACHE_LIFE_PROBE: "seconds";
135
+ /** The TS type of {@link CACHE_LIFE_DEFAULT} — the `"max"` literal. */
136
+ type CacheLifeDefault = typeof CACHE_LIFE_DEFAULT;
137
+ /** The TS type of {@link CACHE_LIFE_PROBE} — the `"seconds"` literal. */
138
+ type CacheLifeProbe = typeof CACHE_LIFE_PROBE;
139
+
140
+ /**
141
+ * Cimplify incremental-cache override for Workers for Platforms storefronts.
142
+ *
143
+ * Replaces opennext's stale-while-revalidate model with an evict-on-invalidate
144
+ * model that fits Cimplify's event-driven domain:
145
+ *
146
+ * - `get`: standard R2 fetch. Returns the cached value or null.
147
+ * - `set`: writes to R2 AND emits a tag→cache_key index update to the shared
148
+ * `CIMPLIFY_PATH_INDEX` Durable Object (hosted in cimplify-tag-cache).
149
+ * - `delete`: standard R2 delete (called by opennext on explicit invalidate;
150
+ * also called by us from the Rust EvictionDispatcher path on tag events).
151
+ *
152
+ * The Rust EvictionDispatcher reads the index on bus events, deletes the
153
+ * matching R2 entries directly, and prunes the index — there is no SWR
154
+ * "background refresh" path. opennext's queue and `isStale` checks become
155
+ * no-ops; cached entries are by definition fresh (existed at write time and
156
+ * haven't been evicted), and absence means the next request synchronously
157
+ * re-renders.
158
+ *
159
+ * Why this exists: WfP user workers cannot have `WORKER_SELF_REFERENCE`,
160
+ * which is the binding every built-in opennext queue requires. Rather than
161
+ * recreate SWR via self-fetch tricks, we drop SWR for our domain — Cimplify
162
+ * always knows when data changes (every catalog mutation flows through the
163
+ * bus), so timer-based refresh adds no value.
164
+ */
165
+
166
+ declare const evictIncrementalCache: IncrementalCache;
167
+
168
+ /** Next 16 cacheLife profile — a built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
169
+ type RevalidateProfile$1 = string | {
170
+ expire: number;
171
+ };
172
+ declare function revalidateProducts(profile?: RevalidateProfile$1): Promise<void>;
102
173
  declare function revalidateProduct(id: string, profile?: RevalidateProfile$1): Promise<void>;
103
174
  declare function revalidateCategories(profile?: RevalidateProfile$1): Promise<void>;
104
175
  declare function revalidateCategory(id: string, profile?: RevalidateProfile$1): Promise<void>;
@@ -114,15 +185,9 @@ declare function revalidateAddOn(id: string, profile?: RevalidateProfile$1): Pro
114
185
  declare function revalidateSubscriptions(profile?: RevalidateProfile$1): Promise<void>;
115
186
  declare function revalidateSubscription(id: string, profile?: RevalidateProfile$1): Promise<void>;
116
187
  declare function revalidateStock(productId?: string, profile?: RevalidateProfile$1): Promise<void>;
117
- /**
118
- * Escape hatch: invalidate by raw tag string. Prefer the typed helpers
119
- * above where possible — they keep the tag scheme in one place.
120
- */
121
188
  declare function revalidateByTag(tag: string, profile?: RevalidateProfile$1): Promise<void>;
122
189
 
123
- /** Expire the products list with read-your-writes. Call from a Server Action that creates / deletes / reorders. */
124
190
  declare function updateProducts(): Promise<void>;
125
- /** Expire a single product + the products list with read-your-writes. */
126
191
  declare function updateProduct(id: string): Promise<void>;
127
192
  declare function updateCategories(): Promise<void>;
128
193
  declare function updateCategory(id: string): Promise<void>;
@@ -138,25 +203,23 @@ declare function updateAddOn(id: string): Promise<void>;
138
203
  declare function updateSubscriptions(): Promise<void>;
139
204
  declare function updateSubscription(id: string): Promise<void>;
140
205
  declare function updateStock(productId?: string): Promise<void>;
141
- /** Escape hatch: expire a raw tag with read-your-writes. Prefer the typed helpers above. */
142
206
  declare function updateByTag(tag: string): Promise<void>;
143
- /**
144
- * Refresh uncached data on the current page (notification counts, live
145
- * metrics, status indicators). Server-Action-only. Complements
146
- * `router.refresh()` on the client.
147
- */
148
207
  declare function refreshPage(): Promise<void>;
149
208
 
150
- /** Next 16 `revalidateTag` profile arg — built-in name (`'max'`/`'hours'`/…) or inline `{expire: secs}`. */
209
+ /** Next 16 cacheLife profile — a built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
151
210
  type RevalidateProfile = string | {
152
211
  expire: number;
153
212
  };
154
213
  interface RevalidateRouteOptions {
214
+ /** Defaults to `process.env.CIMPLIFY_REVALIDATE_SECRET`. */
155
215
  secret?: string;
216
+ /** Defaults to a lazy import of `next/cache.revalidateTag`. Override for tests. */
156
217
  revalidateTag?: (tag: string, profile: RevalidateProfile) => void;
218
+ /** Defaults to `Date.now`. Override for tests. */
157
219
  now?: () => number;
220
+ /** Profile used when the request body doesn't include one. Defaults to `'max'`. */
158
221
  defaultProfile?: RevalidateProfile;
159
222
  }
160
223
  declare function revalidateRouteHandler(req: Request, options?: RevalidateRouteOptions): Promise<Response>;
161
224
 
162
- export { CimplifyClient, type RevalidateProfile$1 as RevalidateProfile, type RevalidateRouteOptions, type RevalidateProfile as RevalidateRouteProfile, type ServerClientOptions, getServerClient, refreshPage, revalidateAddOn, revalidateAddOns, revalidateBrand, revalidateBusiness, revalidateByTag, revalidateCategories, revalidateCategory, revalidateCollection, revalidateCollections, revalidateLocation, revalidateLocations, revalidatePricing, revalidateProduct, revalidateProducts, revalidateRouteHandler, revalidateStock, revalidateSubscription, revalidateSubscriptions, tags, updateAddOn, updateAddOns, updateBrand, updateBusiness, updateByTag, updateCategories, updateCategory, updateCollection, updateCollections, updateLocation, updateLocations, updatePricing, updateProduct, updateProducts, updateStock, updateSubscription, updateSubscriptions };
225
+ export { CACHE_LIFE_DEFAULT, CACHE_LIFE_PROBE, type CacheLifeDefault, type CacheLifeProbe, CimplifyClient, type RevalidateProfile$1 as RevalidateProfile, type RevalidateRouteOptions, type RevalidateProfile as RevalidateRouteProfile, type ServerClientOptions, evictIncrementalCache, getServerClient, refreshPage, revalidateAddOn, revalidateAddOns, revalidateBrand, revalidateBusiness, revalidateByTag, revalidateCategories, revalidateCategory, revalidateCollection, revalidateCollections, revalidateLocation, revalidateLocations, revalidatePricing, revalidateProduct, revalidateProducts, revalidateRouteHandler, revalidateStock, revalidateSubscription, revalidateSubscriptions, tags, updateAddOn, updateAddOns, updateBrand, updateBusiness, updateByTag, updateCategories, updateCategory, updateCollection, updateCollections, updateLocation, updateLocations, updatePricing, updateProduct, updateProducts, updateStock, updateSubscription, updateSubscriptions };
package/dist/server.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { C as CimplifyClient } from './client-B8tJnOde.js';
2
2
  export { aN as Result } from './client-B8tJnOde.js';
3
+ import { IncrementalCache } from '@opennextjs/aws/types/overrides';
3
4
  export { ap as Category, h as CimplifyError, ar as Collection, X as Product, aa as ProductWithDetails } from './product-C-xLzh7Q.js';
4
5
  import './payment-_e99nSRj.js';
5
6
 
@@ -84,21 +85,91 @@ declare const tags: {
84
85
  readonly order: (id: string) => string;
85
86
  };
86
87
 
87
- /** Next 16 `revalidateTag` profile arg — built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
88
- type RevalidateProfile$1 = string | {
89
- expire: number;
90
- };
91
88
  /**
92
- * Invalidate every cache entry tagged with the products list. Call after a
93
- * Server Action that creates / deletes / reorders products. The optional
94
- * `profile` is the Next 16 cacheLife profile (defaults to `'max'` SWR).
89
+ * Cimplify's opinionated cacheLife profiles for storefront server caches.
90
+ *
91
+ * Pass either of these to Next 16's `cacheLife(...)` inside a `'use cache'`
92
+ * server function. They're typed-literal exports so a typo fails at the SDK
93
+ * import site, not silently at runtime (Next's own `cacheLife(profile: string)`
94
+ * overload would accept anything and look it up as a custom profile).
95
+ *
96
+ * @example
97
+ * ```ts
98
+ * import { cacheLife } from "next/cache";
99
+ * import { CACHE_LIFE_DEFAULT, CACHE_LIFE_PROBE, tags } from "@cimplify/sdk/server";
100
+ *
101
+ * async function getProducts() {
102
+ * "use cache";
103
+ * cacheTag(tags.products());
104
+ * const r = await getServerClient().catalogue.getProducts();
105
+ * // Don't lock in empties / failures — a transient bad render would
106
+ * // otherwise sit cached for the full "max" window.
107
+ * if (!r.ok || r.value.items.length === 0) {
108
+ * cacheLife(CACHE_LIFE_PROBE);
109
+ * return r;
110
+ * }
111
+ * cacheLife(CACHE_LIFE_DEFAULT);
112
+ * return r;
113
+ * }
114
+ * ```
95
115
  */
96
- declare function revalidateProducts(profile?: RevalidateProfile$1): Promise<void>;
97
116
  /**
98
- * Invalidate the cached detail of a single product (and the products list,
99
- * since list-shaped caches typically embed each product's denormalized
100
- * fields). Call after a Server Action that edits a product.
117
+ * The default cacheLife for cached storefront reads. Resolves to `"max"`,
118
+ * which is Next 16's longest built-in profile (stale 5min, revalidate 30d,
119
+ * never expires). Safe because Cimplify's tag-cache + CF cache-purge wiring
120
+ * invalidates on-demand within ~1s of a merchant edit — there's no benefit
121
+ * to short timer-based expirations on data Cimplify owns.
122
+ */
123
+ declare const CACHE_LIFE_DEFAULT: "max";
124
+ /**
125
+ * Short-lived cacheLife for "probe" results — empty arrays, errors, 404s,
126
+ * anything that *might* be a transient bad render. Resolves to `"seconds"`
127
+ * (stale 30s, revalidate 1s, expires 1min). Use this when the fetch returned
128
+ * no usable data so a momentary backend blip can't get locked into the cache
129
+ * for `CACHE_LIFE_DEFAULT`'s entire window.
130
+ *
131
+ * The tag still gets attached, so a real `revalidateTag(...)` from Cimplify
132
+ * will refresh the entry the moment the underlying data changes.
101
133
  */
134
+ declare const CACHE_LIFE_PROBE: "seconds";
135
+ /** The TS type of {@link CACHE_LIFE_DEFAULT} — the `"max"` literal. */
136
+ type CacheLifeDefault = typeof CACHE_LIFE_DEFAULT;
137
+ /** The TS type of {@link CACHE_LIFE_PROBE} — the `"seconds"` literal. */
138
+ type CacheLifeProbe = typeof CACHE_LIFE_PROBE;
139
+
140
+ /**
141
+ * Cimplify incremental-cache override for Workers for Platforms storefronts.
142
+ *
143
+ * Replaces opennext's stale-while-revalidate model with an evict-on-invalidate
144
+ * model that fits Cimplify's event-driven domain:
145
+ *
146
+ * - `get`: standard R2 fetch. Returns the cached value or null.
147
+ * - `set`: writes to R2 AND emits a tag→cache_key index update to the shared
148
+ * `CIMPLIFY_PATH_INDEX` Durable Object (hosted in cimplify-tag-cache).
149
+ * - `delete`: standard R2 delete (called by opennext on explicit invalidate;
150
+ * also called by us from the Rust EvictionDispatcher path on tag events).
151
+ *
152
+ * The Rust EvictionDispatcher reads the index on bus events, deletes the
153
+ * matching R2 entries directly, and prunes the index — there is no SWR
154
+ * "background refresh" path. opennext's queue and `isStale` checks become
155
+ * no-ops; cached entries are by definition fresh (existed at write time and
156
+ * haven't been evicted), and absence means the next request synchronously
157
+ * re-renders.
158
+ *
159
+ * Why this exists: WfP user workers cannot have `WORKER_SELF_REFERENCE`,
160
+ * which is the binding every built-in opennext queue requires. Rather than
161
+ * recreate SWR via self-fetch tricks, we drop SWR for our domain — Cimplify
162
+ * always knows when data changes (every catalog mutation flows through the
163
+ * bus), so timer-based refresh adds no value.
164
+ */
165
+
166
+ declare const evictIncrementalCache: IncrementalCache;
167
+
168
+ /** Next 16 cacheLife profile — a built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
169
+ type RevalidateProfile$1 = string | {
170
+ expire: number;
171
+ };
172
+ declare function revalidateProducts(profile?: RevalidateProfile$1): Promise<void>;
102
173
  declare function revalidateProduct(id: string, profile?: RevalidateProfile$1): Promise<void>;
103
174
  declare function revalidateCategories(profile?: RevalidateProfile$1): Promise<void>;
104
175
  declare function revalidateCategory(id: string, profile?: RevalidateProfile$1): Promise<void>;
@@ -114,15 +185,9 @@ declare function revalidateAddOn(id: string, profile?: RevalidateProfile$1): Pro
114
185
  declare function revalidateSubscriptions(profile?: RevalidateProfile$1): Promise<void>;
115
186
  declare function revalidateSubscription(id: string, profile?: RevalidateProfile$1): Promise<void>;
116
187
  declare function revalidateStock(productId?: string, profile?: RevalidateProfile$1): Promise<void>;
117
- /**
118
- * Escape hatch: invalidate by raw tag string. Prefer the typed helpers
119
- * above where possible — they keep the tag scheme in one place.
120
- */
121
188
  declare function revalidateByTag(tag: string, profile?: RevalidateProfile$1): Promise<void>;
122
189
 
123
- /** Expire the products list with read-your-writes. Call from a Server Action that creates / deletes / reorders. */
124
190
  declare function updateProducts(): Promise<void>;
125
- /** Expire a single product + the products list with read-your-writes. */
126
191
  declare function updateProduct(id: string): Promise<void>;
127
192
  declare function updateCategories(): Promise<void>;
128
193
  declare function updateCategory(id: string): Promise<void>;
@@ -138,25 +203,23 @@ declare function updateAddOn(id: string): Promise<void>;
138
203
  declare function updateSubscriptions(): Promise<void>;
139
204
  declare function updateSubscription(id: string): Promise<void>;
140
205
  declare function updateStock(productId?: string): Promise<void>;
141
- /** Escape hatch: expire a raw tag with read-your-writes. Prefer the typed helpers above. */
142
206
  declare function updateByTag(tag: string): Promise<void>;
143
- /**
144
- * Refresh uncached data on the current page (notification counts, live
145
- * metrics, status indicators). Server-Action-only. Complements
146
- * `router.refresh()` on the client.
147
- */
148
207
  declare function refreshPage(): Promise<void>;
149
208
 
150
- /** Next 16 `revalidateTag` profile arg — built-in name (`'max'`/`'hours'`/…) or inline `{expire: secs}`. */
209
+ /** Next 16 cacheLife profile — a built-in name (`'max'`/`'hours'`/…) or `{expire: secs}`. */
151
210
  type RevalidateProfile = string | {
152
211
  expire: number;
153
212
  };
154
213
  interface RevalidateRouteOptions {
214
+ /** Defaults to `process.env.CIMPLIFY_REVALIDATE_SECRET`. */
155
215
  secret?: string;
216
+ /** Defaults to a lazy import of `next/cache.revalidateTag`. Override for tests. */
156
217
  revalidateTag?: (tag: string, profile: RevalidateProfile) => void;
218
+ /** Defaults to `Date.now`. Override for tests. */
157
219
  now?: () => number;
220
+ /** Profile used when the request body doesn't include one. Defaults to `'max'`. */
158
221
  defaultProfile?: RevalidateProfile;
159
222
  }
160
223
  declare function revalidateRouteHandler(req: Request, options?: RevalidateRouteOptions): Promise<Response>;
161
224
 
162
- export { CimplifyClient, type RevalidateProfile$1 as RevalidateProfile, type RevalidateRouteOptions, type RevalidateProfile as RevalidateRouteProfile, type ServerClientOptions, getServerClient, refreshPage, revalidateAddOn, revalidateAddOns, revalidateBrand, revalidateBusiness, revalidateByTag, revalidateCategories, revalidateCategory, revalidateCollection, revalidateCollections, revalidateLocation, revalidateLocations, revalidatePricing, revalidateProduct, revalidateProducts, revalidateRouteHandler, revalidateStock, revalidateSubscription, revalidateSubscriptions, tags, updateAddOn, updateAddOns, updateBrand, updateBusiness, updateByTag, updateCategories, updateCategory, updateCollection, updateCollections, updateLocation, updateLocations, updatePricing, updateProduct, updateProducts, updateStock, updateSubscription, updateSubscriptions };
225
+ export { CACHE_LIFE_DEFAULT, CACHE_LIFE_PROBE, type CacheLifeDefault, type CacheLifeProbe, CimplifyClient, type RevalidateProfile$1 as RevalidateProfile, type RevalidateRouteOptions, type RevalidateProfile as RevalidateRouteProfile, type ServerClientOptions, evictIncrementalCache, getServerClient, refreshPage, revalidateAddOn, revalidateAddOns, revalidateBrand, revalidateBusiness, revalidateByTag, revalidateCategories, revalidateCategory, revalidateCollection, revalidateCollections, revalidateLocation, revalidateLocations, revalidatePricing, revalidateProduct, revalidateProducts, revalidateRouteHandler, revalidateStock, revalidateSubscription, revalidateSubscriptions, tags, updateAddOn, updateAddOns, updateBrand, updateBusiness, updateByTag, updateCategories, updateCategory, updateCollection, updateCollections, updateLocation, updateLocations, updatePricing, updateProduct, updateProducts, updateStock, updateSubscription, updateSubscriptions };
package/dist/server.js CHANGED
@@ -5,8 +5,14 @@ require('./chunk-DR4UPU6P.js');
5
5
  require('./chunk-6RP6OPYO.js');
6
6
  var chunkTKOTACKZ_js = require('./chunk-TKOTACKZ.js');
7
7
  var react = require('react');
8
+ var crypto$1 = require('crypto');
8
9
 
10
+ var DEFAULT_PROD_URL = "https://storefronts.cimplify.io";
9
11
  var DEFAULT_DEV_URL = "http://127.0.0.1:8787";
12
+ function defaultBaseUrl() {
13
+ const proc = globalThis.process;
14
+ return proc?.env?.NODE_ENV === "production" ? DEFAULT_PROD_URL : DEFAULT_DEV_URL;
15
+ }
10
16
  function readEnv(...keys) {
11
17
  const env = globalThis.process?.env;
12
18
  if (!env) return void 0;
@@ -17,7 +23,7 @@ function readEnv(...keys) {
17
23
  return void 0;
18
24
  }
19
25
  var getServerClient = react.cache((opts = {}) => {
20
- const baseUrl = opts.apiUrl ?? readEnv("CIMPLIFY_API_URL", "NEXT_PUBLIC_CIMPLIFY_API_URL") ?? DEFAULT_DEV_URL;
26
+ const baseUrl = opts.apiUrl ?? readEnv("CIMPLIFY_API_URL", "NEXT_PUBLIC_CIMPLIFY_API_URL") ?? defaultBaseUrl();
21
27
  const publicKey = opts.secretKey ?? readEnv("CIMPLIFY_SECRET_KEY", "NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY") ?? "mock-dev";
22
28
  const client = chunkCYGLTD7D_js.createCimplifyClient({
23
29
  baseUrl,
@@ -58,8 +64,174 @@ var tags = {
58
64
  order: (id) => `cimplify:order:${id}`
59
65
  };
60
66
 
67
+ // src/server/cache-life.ts
68
+ var CACHE_LIFE_DEFAULT = "max";
69
+ var CACHE_LIFE_PROBE = "seconds";
70
+
71
+ // ../node_modules/.bun/@opennextjs+cloudflare@1.19.11+2f5a8389dca7b522/node_modules/@opennextjs/cloudflare/dist/api/cloudflare-context.js
72
+ var cloudflareContextSymbol = /* @__PURE__ */ Symbol.for("__cloudflare-context__");
73
+ function getCloudflareContext(options = { async: false }) {
74
+ return options.async ? getCloudflareContextAsync() : getCloudflareContextSync();
75
+ }
76
+ function getCloudflareContextFromGlobalScope() {
77
+ const global = globalThis;
78
+ return global[cloudflareContextSymbol];
79
+ }
80
+ function inSSG() {
81
+ const global = globalThis;
82
+ return global.__NEXT_DATA__?.nextExport === true;
83
+ }
84
+ function getCloudflareContextSync() {
85
+ const cloudflareContext = getCloudflareContextFromGlobalScope();
86
+ if (cloudflareContext) {
87
+ return cloudflareContext;
88
+ }
89
+ if (inSSG()) {
90
+ throw new Error(`
91
+
92
+ ERROR: \`getCloudflareContext\` has been called in sync mode in either a static route or at the top level of a non-static one, both cases are not allowed but can be solved by either:
93
+ - make sure that the call is not at the top level and that the route is not static
94
+ - call \`getCloudflareContext({async: true})\` to use the \`async\` mode
95
+ - avoid calling \`getCloudflareContext\` in the route
96
+ `);
97
+ }
98
+ throw new Error(initOpenNextCloudflareForDevErrorMsg);
99
+ }
100
+ async function getCloudflareContextAsync() {
101
+ const cloudflareContext = getCloudflareContextFromGlobalScope();
102
+ if (cloudflareContext) {
103
+ return cloudflareContext;
104
+ }
105
+ const inNodejsRuntime = process.env.NEXT_RUNTIME === "nodejs";
106
+ if (inNodejsRuntime || inSSG()) {
107
+ const cloudflareContext2 = await getCloudflareContextFromWrangler();
108
+ addCloudflareContextToNodejsGlobal(cloudflareContext2);
109
+ return cloudflareContext2;
110
+ }
111
+ throw new Error(initOpenNextCloudflareForDevErrorMsg);
112
+ }
113
+ function addCloudflareContextToNodejsGlobal(cloudflareContext) {
114
+ const global = globalThis;
115
+ global[cloudflareContextSymbol] = cloudflareContext;
116
+ }
117
+ async function getCloudflareContextFromWrangler(options) {
118
+ const { getPlatformProxy } = await import(
119
+ /* webpackIgnore: true */
120
+ `${"__wrangler".replaceAll("_", "")}`
121
+ );
122
+ const environment = process.env.NEXT_DEV_WRANGLER_ENV;
123
+ const { env, cf, ctx } = await getPlatformProxy({
124
+ ...options,
125
+ // The `env` passed to the fetch handler does not contain variables from `.env*` files.
126
+ // because we invoke wrangler with `CLOUDFLARE_LOAD_DEV_VARS_FROM_DOT_ENV`=`"false"`.
127
+ // Initializing `envFiles` with an empty list is the equivalent for this API call.
128
+ envFiles: [],
129
+ environment
130
+ });
131
+ return {
132
+ env,
133
+ cf,
134
+ ctx
135
+ };
136
+ }
137
+ var initOpenNextCloudflareForDevErrorMsg = `
138
+
139
+ ERROR: \`getCloudflareContext\` has been called without having called \`initOpenNextCloudflareForDev\` from the Next.js config file.
140
+ You should update your Next.js config file as shown below:
141
+
142
+ \`\`\`
143
+ // next.config.mjs
144
+
145
+ import { initOpenNextCloudflareForDev } from "@opennextjs/cloudflare";
146
+
147
+ initOpenNextCloudflareForDev();
148
+
149
+ const nextConfig = { ... };
150
+ export default nextConfig;
151
+ \`\`\`
152
+
153
+ `;
154
+
155
+ // ../node_modules/.bun/@opennextjs+cloudflare@1.19.11+2f5a8389dca7b522/node_modules/@opennextjs/cloudflare/dist/api/overrides/internal.js
156
+ var FALLBACK_BUILD_ID = "no-build-id";
157
+ var DEFAULT_PREFIX = "incremental-cache";
158
+ function computeCacheKey(key, options) {
159
+ const { cacheType = "cache", prefix = DEFAULT_PREFIX, buildId = FALLBACK_BUILD_ID } = options;
160
+ const hash = crypto$1.createHash("sha256").update(key).digest("hex");
161
+ return `${prefix}/${buildId}/${hash}.${cacheType}`.replace(/\/+/g, "/");
162
+ }
163
+
164
+ // src/server/overrides/evict-incremental-cache.ts
165
+ var R2_BUCKET_BINDING = "NEXT_INC_CACHE_R2_BUCKET";
166
+ var R2_PREFIX_ENV = "NEXT_INC_CACHE_R2_PREFIX";
167
+ var PATH_INDEX_BINDING = "CIMPLIFY_PATH_INDEX";
168
+ var CIMPLIFY_TAG_PREFIX = "cimplify:";
169
+ function r2Key(env, key, cacheType) {
170
+ return computeCacheKey(key, {
171
+ prefix: env[R2_PREFIX_ENV],
172
+ buildId: globalThis.process?.env?.OPEN_NEXT_BUILD_ID,
173
+ cacheType
174
+ });
175
+ }
176
+ function cimplifyTags(value) {
177
+ return (value?.tags ?? []).filter((t) => t.startsWith(CIMPLIFY_TAG_PREFIX));
178
+ }
179
+ function pathIndexFor(env) {
180
+ const ns = env[PATH_INDEX_BINDING];
181
+ const prefix = env[R2_PREFIX_ENV];
182
+ if (!ns || !prefix) return null;
183
+ return ns.get(ns.idFromName(prefix));
184
+ }
185
+ var evictIncrementalCache = {
186
+ name: "cimplify-evict-r2-cache",
187
+ async get(key, cacheType) {
188
+ const env = getCloudflareContext().env;
189
+ const r2 = env[R2_BUCKET_BINDING];
190
+ if (!r2) return null;
191
+ try {
192
+ const obj = await r2.get(r2Key(env, key, cacheType));
193
+ if (!obj) return null;
194
+ return {
195
+ value: await obj.json(),
196
+ lastModified: obj.uploaded.getTime()
197
+ };
198
+ } catch {
199
+ return null;
200
+ }
201
+ },
202
+ async set(key, value, cacheType) {
203
+ const env = getCloudflareContext().env;
204
+ const r2 = env[R2_BUCKET_BINDING];
205
+ if (!r2) return;
206
+ const k = r2Key(env, key, cacheType);
207
+ try {
208
+ await r2.put(k, JSON.stringify(value));
209
+ } catch {
210
+ return;
211
+ }
212
+ const tags2 = cimplifyTags(value);
213
+ if (tags2.length === 0) return;
214
+ const index = pathIndexFor(env);
215
+ if (!index) return;
216
+ try {
217
+ await index.indexAdd(key, tags2, cacheType === "fetch");
218
+ } catch {
219
+ }
220
+ },
221
+ async delete(key) {
222
+ const env = getCloudflareContext().env;
223
+ const r2 = env[R2_BUCKET_BINDING];
224
+ if (!r2) return;
225
+ try {
226
+ await r2.delete(r2Key(env, key));
227
+ } catch {
228
+ }
229
+ }
230
+ };
231
+ var evict_incremental_cache_default = evictIncrementalCache;
232
+
61
233
  // src/server/revalidate.ts
62
- var DEFAULT_PROFILE = "max";
234
+ var DEFAULT_PROFILE = CACHE_LIFE_DEFAULT;
63
235
  var _revalidateTag = null;
64
236
  async function getRevalidateTag() {
65
237
  if (_revalidateTag) return _revalidateTag;
@@ -230,7 +402,7 @@ var SIGNATURE_HEADER = "x-cimplify-signature";
230
402
  var SIGNATURE_PREFIX = "sha256=";
231
403
  var MAX_SKEW_MS = 5 * 60 * 1e3;
232
404
  var SECRET_ENV = "CIMPLIFY_REVALIDATE_SECRET";
233
- var DEFAULT_PROFILE2 = "max";
405
+ var DEFAULT_PROFILE2 = CACHE_LIFE_DEFAULT;
234
406
  async function revalidateRouteHandler(req, options = {}) {
235
407
  const secret = options.secret ?? envSecret();
236
408
  if (!secret) return text(`revalidate disabled: ${SECRET_ENV} not set`, 500);
@@ -313,6 +485,9 @@ Object.defineProperty(exports, "CimplifyError", {
313
485
  enumerable: true,
314
486
  get: function () { return chunkTKOTACKZ_js.CimplifyError; }
315
487
  });
488
+ exports.CACHE_LIFE_DEFAULT = CACHE_LIFE_DEFAULT;
489
+ exports.CACHE_LIFE_PROBE = CACHE_LIFE_PROBE;
490
+ exports.evictIncrementalCache = evict_incremental_cache_default;
316
491
  exports.getServerClient = getServerClient;
317
492
  exports.refreshPage = refreshPage;
318
493
  exports.revalidateAddOn = revalidateAddOn;