From 52af9ad18840ffa4e2996386c82cbe34d9fd076a Mon Sep 17 00:00:00 2001
From: Bjorn Lu <bjornlu.dev@gmail.com>
Date: Fri, 26 May 2023 16:59:51 +0800
Subject: [PATCH] Add error message if `Astro.glob` is called outside (#7204)

---
 .changeset/moody-coats-develop.md                   |  5 +++++
 packages/astro/src/runtime/server/astro-global.ts   |  5 +++++
 .../astro/test/units/runtime/astro-global.test.js   | 13 +++++++++++++
 3 files changed, 23 insertions(+)
 create mode 100644 .changeset/moody-coats-develop.md
 create mode 100644 packages/astro/test/units/runtime/astro-global.test.js

diff --git a/.changeset/moody-coats-develop.md b/.changeset/moody-coats-develop.md
new file mode 100644
index 000000000000..20c12708c468
--- /dev/null
+++ b/.changeset/moody-coats-develop.md
@@ -0,0 +1,5 @@
+---
+'astro': patch
+---
+
+Add error message if `Astro.glob` is called outside of an Astro file
diff --git a/packages/astro/src/runtime/server/astro-global.ts b/packages/astro/src/runtime/server/astro-global.ts
index 7ed51132239d..70c4e565b41e 100644
--- a/packages/astro/src/runtime/server/astro-global.ts
+++ b/packages/astro/src/runtime/server/astro-global.ts
@@ -4,6 +4,11 @@ import { ASTRO_VERSION } from '../../core/constants.js';
 /** Create the Astro.glob() runtime function. */
 function createAstroGlobFn() {
 	const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => {
+		if (typeof importMetaGlobResult === 'string') {
+			throw new Error(
+				'Astro.glob() does not work outside of an Astro file. Use `import.meta.glob()` instead.'
+			);
+		}
 		let allEntries = [...Object.values(importMetaGlobResult)];
 		if (allEntries.length === 0) {
 			throw new Error(`Astro.glob(${JSON.stringify(globValue())}) - no matches found.`);
diff --git a/packages/astro/test/units/runtime/astro-global.test.js b/packages/astro/test/units/runtime/astro-global.test.js
new file mode 100644
index 000000000000..975651b76687
--- /dev/null
+++ b/packages/astro/test/units/runtime/astro-global.test.js
@@ -0,0 +1,13 @@
+import { expect } from 'chai';
+import { createAstro } from '../../../dist/runtime/server/index.js';
+
+describe('astro global', () => {
+	it('Glob should error if passed incorrect value', async () => {
+		const Astro = createAstro(undefined);
+		expect(() => {
+			Astro.glob('./**/*.md');
+		}).to.throw(
+			'Astro.glob() does not work outside of an Astro file. Use `import.meta.glob()` instead.'
+		);
+	});
+});